blob: 94cd80a4b0b9c52ae6eb461e21053f48a504daea [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
Richard Smith0621a8f2019-05-31 00:45:10 +00001897 // If we want to determine whether the variable should be captured from the
1898 // perspective of the current capturing scope, and we've already left all the
1899 // capturing scopes of the top directive on the stack, check from the
1900 // perspective of its parent directive (if any) instead.
1901 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1902 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1903
Samuel Antao4be30e92015-10-02 17:14:03 +00001904 // If we are attempting to capture a global variable in a directive with
1905 // 'target' we return true so that this global is also mapped to the device.
1906 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001907 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001908 if (VD && !VD->hasLocalStorage() &&
1909 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1910 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001911 // Try to mark variable as declare target if it is used in capturing
1912 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001913 if (LangOpts.OpenMP <= 45 &&
1914 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001915 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001916 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001917 } else if (isInOpenMPTargetExecutionDirective()) {
1918 // If the declaration is enclosed in a 'declare target' directive,
1919 // then it should not be captured.
1920 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001921 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001922 return nullptr;
1923 return VD;
1924 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001925 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001926
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001927 if (CheckScopeInfo) {
1928 bool OpenMPFound = false;
1929 for (unsigned I = StopAt + 1; I > 0; --I) {
1930 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1931 if(!isa<CapturingScopeInfo>(FSI))
1932 return nullptr;
1933 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1934 if (RSI->CapRegionKind == CR_OpenMP) {
1935 OpenMPFound = true;
1936 break;
1937 }
1938 }
1939 if (!OpenMPFound)
1940 return nullptr;
1941 }
1942
Alexey Bataev48977c32015-08-04 08:10:48 +00001943 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1944 (!DSAStack->isClauseParsingMode() ||
1945 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001946 auto &&Info = DSAStack->isLoopControlVariable(D);
1947 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001948 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001949 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001950 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001951 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001952 DSAStackTy::DSAVarData DVarPrivate =
1953 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001954 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001955 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00001956 // Threadprivate variables must not be captured.
1957 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
1958 return nullptr;
1959 // The variable is not private or it is the variable in the directive with
1960 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001961 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1962 [](OpenMPDirectiveKind) { return true; },
1963 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001964 if (DVarPrivate.CKind != OMPC_unknown ||
1965 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001966 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001967 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001968 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001969}
1970
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001971void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1972 unsigned Level) const {
1973 SmallVector<OpenMPDirectiveKind, 4> Regions;
1974 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1975 FunctionScopesIndex -= Regions.size();
1976}
1977
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001978void Sema::startOpenMPLoop() {
1979 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1980 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1981 DSAStack->loopInit();
1982}
1983
Alexey Bataevbef93a92019-10-07 18:54:57 +00001984void Sema::startOpenMPCXXRangeFor() {
1985 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1986 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1987 DSAStack->resetPossibleLoopCounter();
1988 DSAStack->loopStart();
1989 }
1990}
1991
Alexey Bataeve3727102018-04-18 15:57:46 +00001992bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001993 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001994 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1995 if (DSAStack->getAssociatedLoops() > 0 &&
1996 !DSAStack->isLoopStarted()) {
1997 DSAStack->resetPossibleLoopCounter(D);
1998 DSAStack->loopStart();
1999 return true;
2000 }
2001 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2002 DSAStack->isLoopControlVariable(D).first) &&
2003 !DSAStack->hasExplicitDSA(
2004 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2005 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2006 return true;
2007 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002008 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2009 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2010 DSAStack->isForceVarCapturing() &&
2011 !DSAStack->hasExplicitDSA(
2012 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2013 return true;
2014 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002015 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002016 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002017 (DSAStack->isClauseParsingMode() &&
2018 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002019 // Consider taskgroup reduction descriptor variable a private to avoid
2020 // possible capture in the region.
2021 (DSAStack->hasExplicitDirective(
2022 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2023 Level) &&
2024 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002025}
2026
Alexey Bataeve3727102018-04-18 15:57:46 +00002027void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2028 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002029 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2030 D = getCanonicalDecl(D);
2031 OpenMPClauseKind OMPC = OMPC_unknown;
2032 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2033 const unsigned NewLevel = I - 1;
2034 if (DSAStack->hasExplicitDSA(D,
2035 [&OMPC](const OpenMPClauseKind K) {
2036 if (isOpenMPPrivate(K)) {
2037 OMPC = K;
2038 return true;
2039 }
2040 return false;
2041 },
2042 NewLevel))
2043 break;
2044 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2045 D, NewLevel,
2046 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2047 OpenMPClauseKind) { return true; })) {
2048 OMPC = OMPC_map;
2049 break;
2050 }
2051 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2052 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002053 OMPC = OMPC_map;
2054 if (D->getType()->isScalarType() &&
2055 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
2056 DefaultMapAttributes::DMA_tofrom_scalar)
2057 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002058 break;
2059 }
2060 }
2061 if (OMPC != OMPC_unknown)
2062 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2063}
2064
Alexey Bataeve3727102018-04-18 15:57:46 +00002065bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2066 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002067 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2068 // Return true if the current level is no longer enclosed in a target region.
2069
Alexey Bataeve3727102018-04-18 15:57:46 +00002070 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002071 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002072 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2073 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002074}
2075
Alexey Bataeved09d242014-05-28 05:53:51 +00002076void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002077
Alexey Bataev729e2422019-08-23 16:11:14 +00002078void Sema::finalizeOpenMPDelayedAnalysis() {
2079 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2080 // Diagnose implicit declare target functions and their callees.
2081 for (const auto &CallerCallees : DeviceCallGraph) {
2082 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2083 OMPDeclareTargetDeclAttr::getDeviceType(
2084 CallerCallees.getFirst()->getMostRecentDecl());
2085 // Ignore host functions during device analyzis.
2086 if (LangOpts.OpenMPIsDevice && DevTy &&
2087 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2088 continue;
2089 // Ignore nohost functions during host analyzis.
2090 if (!LangOpts.OpenMPIsDevice && DevTy &&
2091 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2092 continue;
2093 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2094 &Callee : CallerCallees.getSecond()) {
2095 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2096 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2097 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2098 if (LangOpts.OpenMPIsDevice && DevTy &&
2099 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2100 // Diagnose host function called during device codegen.
2101 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2102 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2103 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2104 << HostDevTy << 0;
2105 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2106 diag::note_omp_marked_device_type_here)
2107 << HostDevTy;
2108 continue;
2109 }
2110 if (!LangOpts.OpenMPIsDevice && DevTy &&
2111 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2112 // Diagnose nohost function called during host codegen.
2113 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2114 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2115 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2116 << NoHostDevTy << 1;
2117 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2118 diag::note_omp_marked_device_type_here)
2119 << NoHostDevTy;
2120 continue;
2121 }
2122 }
2123 }
2124}
2125
Alexey Bataev758e55e2013-09-06 18:03:48 +00002126void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2127 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002128 Scope *CurScope, SourceLocation Loc) {
2129 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002130 PushExpressionEvaluationContext(
2131 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002132}
2133
Alexey Bataevaac108a2015-06-23 04:51:00 +00002134void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2135 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002136}
2137
Alexey Bataevaac108a2015-06-23 04:51:00 +00002138void Sema::EndOpenMPClause() {
2139 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002140}
2141
Alexey Bataeve106f252019-04-01 14:25:31 +00002142static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2143 ArrayRef<OMPClause *> Clauses);
2144
Alexey Bataev758e55e2013-09-06 18:03:48 +00002145void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002146 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2147 // A variable of class type (or array thereof) that appears in a lastprivate
2148 // clause requires an accessible, unambiguous default constructor for the
2149 // class type, unless the list item is also specified in a firstprivate
2150 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002151 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2152 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002153 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2154 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002155 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002156 if (DE->isValueDependent() || DE->isTypeDependent()) {
2157 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002158 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002159 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002160 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002161 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002162 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002163 const DSAStackTy::DSAVarData DVar =
2164 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002165 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002166 // Generate helper private variable and initialize it with the
2167 // default value. The address of the original variable is replaced
2168 // by the address of the new private variable in CodeGen. This new
2169 // variable is not added to IdResolver, so the code in the OpenMP
2170 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002171 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002172 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002173 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002174 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002175 if (VDPrivate->isInvalidDecl()) {
2176 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002177 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002178 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002179 PrivateCopies.push_back(buildDeclRefExpr(
2180 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002181 } else {
2182 // The variable is also a firstprivate, so initialization sequence
2183 // for private copy is generated already.
2184 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002185 }
2186 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002187 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002188 }
2189 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002190 // Check allocate clauses.
2191 if (!CurContext->isDependentContext())
2192 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002193 }
2194
Alexey Bataev758e55e2013-09-06 18:03:48 +00002195 DSAStack->pop();
2196 DiscardCleanupsInEvaluationContext();
2197 PopExpressionEvaluationContext();
2198}
2199
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002200static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2201 Expr *NumIterations, Sema &SemaRef,
2202 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002203
Alexey Bataeva769e072013-03-22 06:34:35 +00002204namespace {
2205
Alexey Bataeve3727102018-04-18 15:57:46 +00002206class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002207private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002208 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002209
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002210public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002211 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002212 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002213 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002214 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002215 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002216 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2217 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002218 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002219 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002220 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002221
2222 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002223 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002224 }
2225
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002226};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002227
Alexey Bataeve3727102018-04-18 15:57:46 +00002228class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002229private:
2230 Sema &SemaRef;
2231
2232public:
2233 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2234 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2235 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002236 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2237 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002238 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2239 SemaRef.getCurScope());
2240 }
2241 return false;
2242 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002243
2244 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002245 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002246 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002247};
2248
Alexey Bataeved09d242014-05-28 05:53:51 +00002249} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002250
2251ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2252 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002253 const DeclarationNameInfo &Id,
2254 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002255 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2256 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2257
2258 if (Lookup.isAmbiguous())
2259 return ExprError();
2260
2261 VarDecl *VD;
2262 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002263 VarDeclFilterCCC CCC(*this);
2264 if (TypoCorrection Corrected =
2265 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2266 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002267 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002268 PDiag(Lookup.empty()
2269 ? diag::err_undeclared_var_use_suggest
2270 : diag::err_omp_expected_var_arg_suggest)
2271 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002272 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002273 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002274 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2275 : diag::err_omp_expected_var_arg)
2276 << Id.getName();
2277 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002278 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002279 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2280 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2281 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2282 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002283 }
2284 Lookup.suppressDiagnostics();
2285
2286 // OpenMP [2.9.2, Syntax, C/C++]
2287 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002288 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002289 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002290 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002291 bool IsDecl =
2292 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002293 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002294 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2295 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002296 return ExprError();
2297 }
2298
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002299 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002300 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002301 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2302 // A threadprivate directive for file-scope variables must appear outside
2303 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002304 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2305 !getCurLexicalContext()->isTranslationUnit()) {
2306 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002307 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002308 bool IsDecl =
2309 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2310 Diag(VD->getLocation(),
2311 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2312 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002313 return ExprError();
2314 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2316 // A threadprivate directive for static class member variables must appear
2317 // in the class definition, in the same scope in which the member
2318 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002319 if (CanonicalVD->isStaticDataMember() &&
2320 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2321 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002322 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002323 bool IsDecl =
2324 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2325 Diag(VD->getLocation(),
2326 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2327 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002328 return ExprError();
2329 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002330 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2331 // A threadprivate directive for namespace-scope variables must appear
2332 // outside any definition or declaration other than the namespace
2333 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002334 if (CanonicalVD->getDeclContext()->isNamespace() &&
2335 (!getCurLexicalContext()->isFileContext() ||
2336 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2337 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002338 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002339 bool IsDecl =
2340 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2341 Diag(VD->getLocation(),
2342 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2343 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002344 return ExprError();
2345 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002346 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2347 // A threadprivate directive for static block-scope variables must appear
2348 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002349 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002350 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002351 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002352 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002353 bool IsDecl =
2354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2355 Diag(VD->getLocation(),
2356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2357 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002358 return ExprError();
2359 }
2360
2361 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2362 // A threadprivate directive must lexically precede all references to any
2363 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002364 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2365 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002366 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002367 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002368 return ExprError();
2369 }
2370
2371 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002372 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2373 SourceLocation(), VD,
2374 /*RefersToEnclosingVariableOrCapture=*/false,
2375 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002376}
2377
Alexey Bataeved09d242014-05-28 05:53:51 +00002378Sema::DeclGroupPtrTy
2379Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2380 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002381 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002382 CurContext->addDecl(D);
2383 return DeclGroupPtrTy::make(DeclGroupRef(D));
2384 }
David Blaikie0403cb12016-01-15 23:43:25 +00002385 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002386}
2387
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002388namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002389class LocalVarRefChecker final
2390 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002391 Sema &SemaRef;
2392
2393public:
2394 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002395 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002396 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002397 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002398 diag::err_omp_local_var_in_threadprivate_init)
2399 << E->getSourceRange();
2400 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2401 << VD << VD->getSourceRange();
2402 return true;
2403 }
2404 }
2405 return false;
2406 }
2407 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002408 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002409 if (Child && Visit(Child))
2410 return true;
2411 }
2412 return false;
2413 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002414 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002415};
2416} // namespace
2417
Alexey Bataeved09d242014-05-28 05:53:51 +00002418OMPThreadPrivateDecl *
2419Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002420 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002421 for (Expr *RefExpr : VarList) {
2422 auto *DE = cast<DeclRefExpr>(RefExpr);
2423 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002424 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002425
Alexey Bataev376b4a42016-02-09 09:41:09 +00002426 // Mark variable as used.
2427 VD->setReferenced();
2428 VD->markUsed(Context);
2429
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002430 QualType QType = VD->getType();
2431 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2432 // It will be analyzed later.
2433 Vars.push_back(DE);
2434 continue;
2435 }
2436
Alexey Bataeva769e072013-03-22 06:34:35 +00002437 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2438 // A threadprivate variable must not have an incomplete type.
2439 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002440 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002441 continue;
2442 }
2443
2444 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2445 // A threadprivate variable must not have a reference type.
2446 if (VD->getType()->isReferenceType()) {
2447 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002448 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2449 bool IsDecl =
2450 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2451 Diag(VD->getLocation(),
2452 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2453 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002454 continue;
2455 }
2456
Samuel Antaof8b50122015-07-13 22:54:53 +00002457 // Check if this is a TLS variable. If TLS is not being supported, produce
2458 // the corresponding diagnostic.
2459 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2460 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2461 getLangOpts().OpenMPUseTLS &&
2462 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002463 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2464 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002465 Diag(ILoc, diag::err_omp_var_thread_local)
2466 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002467 bool IsDecl =
2468 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2469 Diag(VD->getLocation(),
2470 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2471 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002472 continue;
2473 }
2474
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002475 // Check if initial value of threadprivate variable reference variable with
2476 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002477 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002478 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002479 if (Checker.Visit(Init))
2480 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002481 }
2482
Alexey Bataeved09d242014-05-28 05:53:51 +00002483 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002484 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002485 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2486 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002487 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002488 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002489 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002490 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002491 if (!Vars.empty()) {
2492 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2493 Vars);
2494 D->setAccess(AS_public);
2495 }
2496 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002497}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002498
Alexey Bataev27ef9512019-03-20 20:14:22 +00002499static OMPAllocateDeclAttr::AllocatorTypeTy
2500getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2501 if (!Allocator)
2502 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2503 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2504 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002505 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002506 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002507 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002508 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002509 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2510 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2511 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002512 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002513 llvm::FoldingSetNodeID AEId, DAEId;
2514 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2515 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2516 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002517 AllocatorKindRes = AllocatorKind;
2518 break;
2519 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002520 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002521 return AllocatorKindRes;
2522}
2523
Alexey Bataeve106f252019-04-01 14:25:31 +00002524static bool checkPreviousOMPAllocateAttribute(
2525 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2526 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2527 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2528 return false;
2529 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2530 Expr *PrevAllocator = A->getAllocator();
2531 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2532 getAllocatorKind(S, Stack, PrevAllocator);
2533 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2534 if (AllocatorsMatch &&
2535 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2536 Allocator && PrevAllocator) {
2537 const Expr *AE = Allocator->IgnoreParenImpCasts();
2538 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2539 llvm::FoldingSetNodeID AEId, PAEId;
2540 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2541 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2542 AllocatorsMatch = AEId == PAEId;
2543 }
2544 if (!AllocatorsMatch) {
2545 SmallString<256> AllocatorBuffer;
2546 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2547 if (Allocator)
2548 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2549 SmallString<256> PrevAllocatorBuffer;
2550 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2551 if (PrevAllocator)
2552 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2553 S.getPrintingPolicy());
2554
2555 SourceLocation AllocatorLoc =
2556 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2557 SourceRange AllocatorRange =
2558 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2559 SourceLocation PrevAllocatorLoc =
2560 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2561 SourceRange PrevAllocatorRange =
2562 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2563 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2564 << (Allocator ? 1 : 0) << AllocatorStream.str()
2565 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2566 << AllocatorRange;
2567 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2568 << PrevAllocatorRange;
2569 return true;
2570 }
2571 return false;
2572}
2573
2574static void
2575applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2576 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2577 Expr *Allocator, SourceRange SR) {
2578 if (VD->hasAttr<OMPAllocateDeclAttr>())
2579 return;
2580 if (Allocator &&
2581 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2582 Allocator->isInstantiationDependent() ||
2583 Allocator->containsUnexpandedParameterPack()))
2584 return;
2585 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2586 Allocator, SR);
2587 VD->addAttr(A);
2588 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2589 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2590}
2591
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002592Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2593 SourceLocation Loc, ArrayRef<Expr *> VarList,
2594 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2595 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2596 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002597 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002598 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2599 // allocate directives that appear in a target region must specify an
2600 // allocator clause unless a requires directive with the dynamic_allocators
2601 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002602 if (LangOpts.OpenMPIsDevice &&
2603 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002604 targetDiag(Loc, diag::err_expected_allocator_clause);
2605 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002606 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002607 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002608 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2609 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002610 SmallVector<Expr *, 8> Vars;
2611 for (Expr *RefExpr : VarList) {
2612 auto *DE = cast<DeclRefExpr>(RefExpr);
2613 auto *VD = cast<VarDecl>(DE->getDecl());
2614
2615 // Check if this is a TLS variable or global register.
2616 if (VD->getTLSKind() != VarDecl::TLS_None ||
2617 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2618 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2619 !VD->isLocalVarDecl()))
2620 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002621
Alexey Bataev282555a2019-03-19 20:33:44 +00002622 // If the used several times in the allocate directive, the same allocator
2623 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002624 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2625 AllocatorKind, Allocator))
2626 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002627
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002628 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2629 // If a list item has a static storage type, the allocator expression in the
2630 // allocator clause must be a constant expression that evaluates to one of
2631 // the predefined memory allocator values.
2632 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002633 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002634 Diag(Allocator->getExprLoc(),
2635 diag::err_omp_expected_predefined_allocator)
2636 << Allocator->getSourceRange();
2637 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2638 VarDecl::DeclarationOnly;
2639 Diag(VD->getLocation(),
2640 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2641 << VD;
2642 continue;
2643 }
2644 }
2645
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002646 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002647 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2648 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002649 }
2650 if (Vars.empty())
2651 return nullptr;
2652 if (!Owner)
2653 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002654 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002655 D->setAccess(AS_public);
2656 Owner->addDecl(D);
2657 return DeclGroupPtrTy::make(DeclGroupRef(D));
2658}
2659
2660Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002661Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2662 ArrayRef<OMPClause *> ClauseList) {
2663 OMPRequiresDecl *D = nullptr;
2664 if (!CurContext->isFileContext()) {
2665 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2666 } else {
2667 D = CheckOMPRequiresDecl(Loc, ClauseList);
2668 if (D) {
2669 CurContext->addDecl(D);
2670 DSAStack->addRequiresDecl(D);
2671 }
2672 }
2673 return DeclGroupPtrTy::make(DeclGroupRef(D));
2674}
2675
2676OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2677 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002678 /// For target specific clauses, the requires directive cannot be
2679 /// specified after the handling of any of the target regions in the
2680 /// current compilation unit.
2681 ArrayRef<SourceLocation> TargetLocations =
2682 DSAStack->getEncounteredTargetLocs();
2683 if (!TargetLocations.empty()) {
2684 for (const OMPClause *CNew : ClauseList) {
2685 // Check if any of the requires clauses affect target regions.
2686 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2687 isa<OMPUnifiedAddressClause>(CNew) ||
2688 isa<OMPReverseOffloadClause>(CNew) ||
2689 isa<OMPDynamicAllocatorsClause>(CNew)) {
2690 Diag(Loc, diag::err_omp_target_before_requires)
2691 << getOpenMPClauseName(CNew->getClauseKind());
2692 for (SourceLocation TargetLoc : TargetLocations) {
2693 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2694 }
2695 }
2696 }
2697 }
2698
Kelvin Li1408f912018-09-26 04:28:39 +00002699 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2700 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2701 ClauseList);
2702 return nullptr;
2703}
2704
Alexey Bataeve3727102018-04-18 15:57:46 +00002705static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2706 const ValueDecl *D,
2707 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002708 bool IsLoopIterVar = false) {
2709 if (DVar.RefExpr) {
2710 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2711 << getOpenMPClauseName(DVar.CKind);
2712 return;
2713 }
2714 enum {
2715 PDSA_StaticMemberShared,
2716 PDSA_StaticLocalVarShared,
2717 PDSA_LoopIterVarPrivate,
2718 PDSA_LoopIterVarLinear,
2719 PDSA_LoopIterVarLastprivate,
2720 PDSA_ConstVarShared,
2721 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002722 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002723 PDSA_LocalVarPrivate,
2724 PDSA_Implicit
2725 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002726 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002727 auto ReportLoc = D->getLocation();
2728 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002729 if (IsLoopIterVar) {
2730 if (DVar.CKind == OMPC_private)
2731 Reason = PDSA_LoopIterVarPrivate;
2732 else if (DVar.CKind == OMPC_lastprivate)
2733 Reason = PDSA_LoopIterVarLastprivate;
2734 else
2735 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002736 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2737 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002738 Reason = PDSA_TaskVarFirstprivate;
2739 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002740 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002741 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002742 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002743 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002744 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002745 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002746 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002747 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002748 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002749 ReportHint = true;
2750 Reason = PDSA_LocalVarPrivate;
2751 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002752 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002753 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002754 << Reason << ReportHint
2755 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2756 } else if (DVar.ImplicitDSALoc.isValid()) {
2757 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2758 << getOpenMPClauseName(DVar.CKind);
2759 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002760}
2761
Alexey Bataev758e55e2013-09-06 18:03:48 +00002762namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002763class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002764 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002765 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002766 bool ErrorFound = false;
2767 CapturedStmt *CS = nullptr;
2768 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2769 llvm::SmallVector<Expr *, 4> ImplicitMap;
2770 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2771 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002772
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002773 void VisitSubCaptures(OMPExecutableDirective *S) {
2774 // Check implicitly captured variables.
2775 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2776 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002777 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002778 }
2779
Alexey Bataev758e55e2013-09-06 18:03:48 +00002780public:
2781 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002782 if (E->isTypeDependent() || E->isValueDependent() ||
2783 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2784 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002785 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002786 // Check the datasharing rules for the expressions in the clauses.
2787 if (!CS) {
2788 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2789 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2790 Visit(CED->getInit());
2791 return;
2792 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002793 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2794 // Do not analyze internal variables and do not enclose them into
2795 // implicit clauses.
2796 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002797 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002798 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002799 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002800 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002801
Alexey Bataeve3727102018-04-18 15:57:46 +00002802 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002803 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002804 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002805 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002806
Alexey Bataevafe50572017-10-06 17:00:28 +00002807 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002808 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002809 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002810 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002811 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2812 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002813 return;
2814
Alexey Bataeve3727102018-04-18 15:57:46 +00002815 SourceLocation ELoc = E->getExprLoc();
2816 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002817 // The default(none) clause requires that each variable that is referenced
2818 // in the construct, and does not have a predetermined data-sharing
2819 // attribute, must have its data-sharing attribute explicitly determined
2820 // by being listed in a data-sharing attribute clause.
2821 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002822 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002823 VarsWithInheritedDSA.count(VD) == 0) {
2824 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825 return;
2826 }
2827
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002828 if (isOpenMPTargetExecutionDirective(DKind) &&
2829 !Stack->isLoopControlVariable(VD).first) {
2830 if (!Stack->checkMappableExprComponentListsForDecl(
2831 VD, /*CurrentRegionOnly=*/true,
2832 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2833 StackComponents,
2834 OpenMPClauseKind) {
2835 // Variable is used if it has been marked as an array, array
2836 // section or the variable iself.
2837 return StackComponents.size() == 1 ||
2838 std::all_of(
2839 std::next(StackComponents.rbegin()),
2840 StackComponents.rend(),
2841 [](const OMPClauseMappableExprCommon::
2842 MappableComponent &MC) {
2843 return MC.getAssociatedDeclaration() ==
2844 nullptr &&
2845 (isa<OMPArraySectionExpr>(
2846 MC.getAssociatedExpression()) ||
2847 isa<ArraySubscriptExpr>(
2848 MC.getAssociatedExpression()));
2849 });
2850 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002851 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002852 // By default lambdas are captured as firstprivates.
2853 if (const auto *RD =
2854 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002855 IsFirstprivate = RD->isLambda();
2856 IsFirstprivate =
2857 IsFirstprivate ||
2858 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002859 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002860 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002861 ImplicitFirstprivate.emplace_back(E);
2862 else
2863 ImplicitMap.emplace_back(E);
2864 return;
2865 }
2866 }
2867
Alexey Bataev758e55e2013-09-06 18:03:48 +00002868 // OpenMP [2.9.3.6, Restrictions, p.2]
2869 // A list item that appears in a reduction clause of the innermost
2870 // enclosing worksharing or parallel construct may not be accessed in an
2871 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002872 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002873 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2874 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002875 return isOpenMPParallelDirective(K) ||
2876 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2877 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002878 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002879 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002880 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002881 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002882 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002883 return;
2884 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002885
2886 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002887 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002888 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002889 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002890 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002891 return;
2892 }
2893
2894 // Store implicitly used globals with declare target link for parent
2895 // target.
2896 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2897 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2898 Stack->addToParentTargetRegionLinkGlobals(E);
2899 return;
2900 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002901 }
2902 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002903 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002904 if (E->isTypeDependent() || E->isValueDependent() ||
2905 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2906 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002907 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002908 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002909 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002910 if (!FD)
2911 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002912 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002913 // Check if the variable has explicit DSA set and stop analysis if it
2914 // so.
2915 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2916 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002917
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002918 if (isOpenMPTargetExecutionDirective(DKind) &&
2919 !Stack->isLoopControlVariable(FD).first &&
2920 !Stack->checkMappableExprComponentListsForDecl(
2921 FD, /*CurrentRegionOnly=*/true,
2922 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2923 StackComponents,
2924 OpenMPClauseKind) {
2925 return isa<CXXThisExpr>(
2926 cast<MemberExpr>(
2927 StackComponents.back().getAssociatedExpression())
2928 ->getBase()
2929 ->IgnoreParens());
2930 })) {
2931 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2932 // A bit-field cannot appear in a map clause.
2933 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002934 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002935 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002936
2937 // Check to see if the member expression is referencing a class that
2938 // has already been explicitly mapped
2939 if (Stack->isClassPreviouslyMapped(TE->getType()))
2940 return;
2941
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002942 ImplicitMap.emplace_back(E);
2943 return;
2944 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002945
Alexey Bataeve3727102018-04-18 15:57:46 +00002946 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002947 // OpenMP [2.9.3.6, Restrictions, p.2]
2948 // A list item that appears in a reduction clause of the innermost
2949 // enclosing worksharing or parallel construct may not be accessed in
2950 // an explicit task.
2951 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002952 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2953 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002954 return isOpenMPParallelDirective(K) ||
2955 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2956 },
2957 /*FromParent=*/true);
2958 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2959 ErrorFound = true;
2960 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002961 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002962 return;
2963 }
2964
2965 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002966 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002967 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002968 !Stack->isLoopControlVariable(FD).first) {
2969 // Check if there is a captured expression for the current field in the
2970 // region. Do not mark it as firstprivate unless there is no captured
2971 // expression.
2972 // TODO: try to make it firstprivate.
2973 if (DVar.CKind != OMPC_unknown)
2974 ImplicitFirstprivate.push_back(E);
2975 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002976 return;
2977 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002978 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002979 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002980 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002981 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002982 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002983 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002984 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2985 if (!Stack->checkMappableExprComponentListsForDecl(
2986 VD, /*CurrentRegionOnly=*/true,
2987 [&CurComponents](
2988 OMPClauseMappableExprCommon::MappableExprComponentListRef
2989 StackComponents,
2990 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002991 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002992 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002993 for (const auto &SC : llvm::reverse(StackComponents)) {
2994 // Do both expressions have the same kind?
2995 if (CCI->getAssociatedExpression()->getStmtClass() !=
2996 SC.getAssociatedExpression()->getStmtClass())
2997 if (!(isa<OMPArraySectionExpr>(
2998 SC.getAssociatedExpression()) &&
2999 isa<ArraySubscriptExpr>(
3000 CCI->getAssociatedExpression())))
3001 return false;
3002
Alexey Bataeve3727102018-04-18 15:57:46 +00003003 const Decl *CCD = CCI->getAssociatedDeclaration();
3004 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003005 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3006 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3007 if (SCD != CCD)
3008 return false;
3009 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003010 if (CCI == CCE)
3011 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003012 }
3013 return true;
3014 })) {
3015 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003016 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003017 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003018 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003019 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003020 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003021 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003022 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003023 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003024 // for task|target directives.
3025 // Skip analysis of arguments of implicitly defined map clause for target
3026 // directives.
3027 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3028 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003029 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003030 if (CC)
3031 Visit(CC);
3032 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003033 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003034 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003035 // Check implicitly captured variables.
3036 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003037 }
3038 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003039 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003040 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003041 // Check implicitly captured variables in the task-based directives to
3042 // check if they must be firstprivatized.
3043 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003044 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003045 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003046 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003047
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003048 void visitSubCaptures(CapturedStmt *S) {
3049 for (const CapturedStmt::Capture &Cap : S->captures()) {
3050 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3051 continue;
3052 VarDecl *VD = Cap.getCapturedVar();
3053 // Do not try to map the variable if it or its sub-component was mapped
3054 // already.
3055 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3056 Stack->checkMappableExprComponentListsForDecl(
3057 VD, /*CurrentRegionOnly=*/true,
3058 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3059 OpenMPClauseKind) { return true; }))
3060 continue;
3061 DeclRefExpr *DRE = buildDeclRefExpr(
3062 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3063 Cap.getLocation(), /*RefersToCapture=*/true);
3064 Visit(DRE);
3065 }
3066 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003067 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003068 ArrayRef<Expr *> getImplicitFirstprivate() const {
3069 return ImplicitFirstprivate;
3070 }
3071 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00003072 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003073 return VarsWithInheritedDSA;
3074 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003075
Alexey Bataev7ff55242014-06-19 09:13:45 +00003076 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003077 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3078 // Process declare target link variables for the target directives.
3079 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3080 for (DeclRefExpr *E : Stack->getLinkGlobals())
3081 Visit(E);
3082 }
3083 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003084};
Alexey Bataeved09d242014-05-28 05:53:51 +00003085} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003086
Alexey Bataevbae9a792014-06-27 10:37:06 +00003087void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003088 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003089 case OMPD_parallel:
3090 case OMPD_parallel_for:
3091 case OMPD_parallel_for_simd:
3092 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003093 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003094 case OMPD_teams_distribute:
3095 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003096 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003097 QualType KmpInt32PtrTy =
3098 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003099 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003100 std::make_pair(".global_tid.", KmpInt32PtrTy),
3101 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3102 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003103 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003104 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3105 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003106 break;
3107 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003108 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003109 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003110 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003111 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003112 case OMPD_target_teams_distribute:
3113 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003114 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3115 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3118 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003119 FunctionProtoType::ExtProtoInfo EPI;
3120 EPI.Variadic = true;
3121 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3122 Sema::CapturedParamNameType Params[] = {
3123 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003124 std::make_pair(".part_id.", KmpInt32PtrTy),
3125 std::make_pair(".privates.", VoidPtrTy),
3126 std::make_pair(
3127 ".copy_fn.",
3128 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003129 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3130 std::make_pair(StringRef(), QualType()) // __context with shared vars
3131 };
3132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003133 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003134 // Mark this captured region as inlined, because we don't use outlined
3135 // function directly.
3136 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3137 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003138 Context, {}, AttributeCommonInfo::AS_Keyword,
3139 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003140 Sema::CapturedParamNameType ParamsTarget[] = {
3141 std::make_pair(StringRef(), QualType()) // __context with shared vars
3142 };
3143 // Start a captured region for 'target' with no implicit parameters.
3144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003145 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003146 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003147 std::make_pair(".global_tid.", KmpInt32PtrTy),
3148 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003151 // Start a captured region for 'teams' or 'parallel'. Both regions have
3152 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003153 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003154 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003155 break;
3156 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003157 case OMPD_target:
3158 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003159 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3160 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3161 QualType KmpInt32PtrTy =
3162 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3163 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003164 FunctionProtoType::ExtProtoInfo EPI;
3165 EPI.Variadic = true;
3166 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3167 Sema::CapturedParamNameType Params[] = {
3168 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003169 std::make_pair(".part_id.", KmpInt32PtrTy),
3170 std::make_pair(".privates.", VoidPtrTy),
3171 std::make_pair(
3172 ".copy_fn.",
3173 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003174 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3175 std::make_pair(StringRef(), QualType()) // __context with shared vars
3176 };
3177 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003178 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003179 // Mark this captured region as inlined, because we don't use outlined
3180 // function directly.
3181 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3182 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003183 Context, {}, AttributeCommonInfo::AS_Keyword,
3184 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003185 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003186 std::make_pair(StringRef(), QualType()),
3187 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003188 break;
3189 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003190 case OMPD_simd:
3191 case OMPD_for:
3192 case OMPD_for_simd:
3193 case OMPD_sections:
3194 case OMPD_section:
3195 case OMPD_single:
3196 case OMPD_master:
3197 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003198 case OMPD_taskgroup:
3199 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003200 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003201 case OMPD_ordered:
3202 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003203 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003204 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003205 std::make_pair(StringRef(), QualType()) // __context with shared vars
3206 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003207 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3208 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003209 break;
3210 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003211 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003212 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3213 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3214 QualType KmpInt32PtrTy =
3215 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3216 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003217 FunctionProtoType::ExtProtoInfo EPI;
3218 EPI.Variadic = true;
3219 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003220 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003221 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003222 std::make_pair(".part_id.", KmpInt32PtrTy),
3223 std::make_pair(".privates.", VoidPtrTy),
3224 std::make_pair(
3225 ".copy_fn.",
3226 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003227 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003228 std::make_pair(StringRef(), QualType()) // __context with shared vars
3229 };
3230 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3231 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003232 // Mark this captured region as inlined, because we don't use outlined
3233 // function directly.
3234 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3235 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003236 Context, {}, AttributeCommonInfo::AS_Keyword,
3237 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003238 break;
3239 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003240 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003241 case OMPD_taskloop_simd:
3242 case OMPD_master_taskloop: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003243 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003244 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3245 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003246 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003247 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3248 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003249 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003250 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3251 .withConst();
3252 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3253 QualType KmpInt32PtrTy =
3254 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3255 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003256 FunctionProtoType::ExtProtoInfo EPI;
3257 EPI.Variadic = true;
3258 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003259 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003260 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003261 std::make_pair(".part_id.", KmpInt32PtrTy),
3262 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003263 std::make_pair(
3264 ".copy_fn.",
3265 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3266 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3267 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003268 std::make_pair(".ub.", KmpUInt64Ty),
3269 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003270 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003271 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003272 std::make_pair(StringRef(), QualType()) // __context with shared vars
3273 };
3274 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3275 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003276 // Mark this captured region as inlined, because we don't use outlined
3277 // function directly.
3278 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3279 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003280 Context, {}, AttributeCommonInfo::AS_Keyword,
3281 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003282 break;
3283 }
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003284 case OMPD_parallel_master_taskloop: {
3285 QualType KmpInt32Ty =
3286 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3287 .withConst();
3288 QualType KmpUInt64Ty =
3289 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3290 .withConst();
3291 QualType KmpInt64Ty =
3292 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3293 .withConst();
3294 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3295 QualType KmpInt32PtrTy =
3296 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3297 Sema::CapturedParamNameType ParamsParallel[] = {
3298 std::make_pair(".global_tid.", KmpInt32PtrTy),
3299 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3300 std::make_pair(StringRef(), QualType()) // __context with shared vars
3301 };
3302 // Start a captured region for 'parallel'.
3303 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3304 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3305 QualType Args[] = {VoidPtrTy};
3306 FunctionProtoType::ExtProtoInfo EPI;
3307 EPI.Variadic = true;
3308 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3309 Sema::CapturedParamNameType Params[] = {
3310 std::make_pair(".global_tid.", KmpInt32Ty),
3311 std::make_pair(".part_id.", KmpInt32PtrTy),
3312 std::make_pair(".privates.", VoidPtrTy),
3313 std::make_pair(
3314 ".copy_fn.",
3315 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3316 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3317 std::make_pair(".lb.", KmpUInt64Ty),
3318 std::make_pair(".ub.", KmpUInt64Ty),
3319 std::make_pair(".st.", KmpInt64Ty),
3320 std::make_pair(".liter.", KmpInt32Ty),
3321 std::make_pair(".reductions.", VoidPtrTy),
3322 std::make_pair(StringRef(), QualType()) // __context with shared vars
3323 };
3324 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3325 Params, /*OpenMPCaptureLevel=*/2);
3326 // Mark this captured region as inlined, because we don't use outlined
3327 // function directly.
3328 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3329 AlwaysInlineAttr::CreateImplicit(
3330 Context, {}, AttributeCommonInfo::AS_Keyword,
3331 AlwaysInlineAttr::Keyword_forceinline));
3332 break;
3333 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003334 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003335 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003336 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003337 QualType KmpInt32PtrTy =
3338 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3339 Sema::CapturedParamNameType Params[] = {
3340 std::make_pair(".global_tid.", KmpInt32PtrTy),
3341 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003342 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3343 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003344 std::make_pair(StringRef(), QualType()) // __context with shared vars
3345 };
3346 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3347 Params);
3348 break;
3349 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003350 case OMPD_target_teams_distribute_parallel_for:
3351 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003352 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003353 QualType KmpInt32PtrTy =
3354 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003355 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003356
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003357 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003358 FunctionProtoType::ExtProtoInfo EPI;
3359 EPI.Variadic = true;
3360 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3361 Sema::CapturedParamNameType Params[] = {
3362 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003363 std::make_pair(".part_id.", KmpInt32PtrTy),
3364 std::make_pair(".privates.", VoidPtrTy),
3365 std::make_pair(
3366 ".copy_fn.",
3367 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003368 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3369 std::make_pair(StringRef(), QualType()) // __context with shared vars
3370 };
3371 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003372 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003373 // Mark this captured region as inlined, because we don't use outlined
3374 // function directly.
3375 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3376 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003377 Context, {}, AttributeCommonInfo::AS_Keyword,
3378 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003379 Sema::CapturedParamNameType ParamsTarget[] = {
3380 std::make_pair(StringRef(), QualType()) // __context with shared vars
3381 };
3382 // Start a captured region for 'target' with no implicit parameters.
3383 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003384 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003385
3386 Sema::CapturedParamNameType ParamsTeams[] = {
3387 std::make_pair(".global_tid.", KmpInt32PtrTy),
3388 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3389 std::make_pair(StringRef(), QualType()) // __context with shared vars
3390 };
3391 // Start a captured region for 'target' with no implicit parameters.
3392 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003393 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003394
3395 Sema::CapturedParamNameType ParamsParallel[] = {
3396 std::make_pair(".global_tid.", KmpInt32PtrTy),
3397 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003398 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3399 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003400 std::make_pair(StringRef(), QualType()) // __context with shared vars
3401 };
3402 // Start a captured region for 'teams' or 'parallel'. Both regions have
3403 // the same implicit parameters.
3404 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003405 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003406 break;
3407 }
3408
Alexey Bataev46506272017-12-05 17:41:34 +00003409 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003410 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003411 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003412 QualType KmpInt32PtrTy =
3413 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3414
3415 Sema::CapturedParamNameType ParamsTeams[] = {
3416 std::make_pair(".global_tid.", KmpInt32PtrTy),
3417 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3418 std::make_pair(StringRef(), QualType()) // __context with shared vars
3419 };
3420 // Start a captured region for 'target' with no implicit parameters.
3421 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003422 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003423
3424 Sema::CapturedParamNameType ParamsParallel[] = {
3425 std::make_pair(".global_tid.", KmpInt32PtrTy),
3426 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003427 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3428 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003429 std::make_pair(StringRef(), QualType()) // __context with shared vars
3430 };
3431 // Start a captured region for 'teams' or 'parallel'. Both regions have
3432 // the same implicit parameters.
3433 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003434 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003435 break;
3436 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003437 case OMPD_target_update:
3438 case OMPD_target_enter_data:
3439 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003440 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3441 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3442 QualType KmpInt32PtrTy =
3443 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3444 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003445 FunctionProtoType::ExtProtoInfo EPI;
3446 EPI.Variadic = true;
3447 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3448 Sema::CapturedParamNameType Params[] = {
3449 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003450 std::make_pair(".part_id.", KmpInt32PtrTy),
3451 std::make_pair(".privates.", VoidPtrTy),
3452 std::make_pair(
3453 ".copy_fn.",
3454 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003455 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3456 std::make_pair(StringRef(), QualType()) // __context with shared vars
3457 };
3458 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3459 Params);
3460 // Mark this captured region as inlined, because we don't use outlined
3461 // function directly.
3462 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3463 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003464 Context, {}, AttributeCommonInfo::AS_Keyword,
3465 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003466 break;
3467 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003468 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003469 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003470 case OMPD_taskyield:
3471 case OMPD_barrier:
3472 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003473 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003474 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003475 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003476 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003477 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003478 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003479 case OMPD_declare_target:
3480 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003481 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003482 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003483 llvm_unreachable("OpenMP Directive is not allowed");
3484 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003485 llvm_unreachable("Unknown OpenMP directive");
3486 }
3487}
3488
Alexey Bataev0e100032019-10-14 16:44:01 +00003489int Sema::getNumberOfConstructScopes(unsigned Level) const {
3490 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3491}
3492
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003493int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3494 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3495 getOpenMPCaptureRegions(CaptureRegions, DKind);
3496 return CaptureRegions.size();
3497}
3498
Alexey Bataev3392d762016-02-16 11:18:12 +00003499static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003500 Expr *CaptureExpr, bool WithInit,
3501 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003502 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003503 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003504 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003505 QualType Ty = Init->getType();
3506 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003507 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003508 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003509 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003510 Ty = C.getPointerType(Ty);
3511 ExprResult Res =
3512 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3513 if (!Res.isUsable())
3514 return nullptr;
3515 Init = Res.get();
3516 }
Alexey Bataev61205072016-03-02 04:57:40 +00003517 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003518 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003519 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003520 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003521 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003522 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003523 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003524 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003525 return CED;
3526}
3527
Alexey Bataev61205072016-03-02 04:57:40 +00003528static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3529 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003530 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003531 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003532 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003533 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003534 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3535 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003536 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003537 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003538}
3539
Alexey Bataev5a3af132016-03-29 08:58:54 +00003540static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003541 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003542 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003543 OMPCapturedExprDecl *CD = buildCaptureDecl(
3544 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3545 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003546 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3547 CaptureExpr->getExprLoc());
3548 }
3549 ExprResult Res = Ref;
3550 if (!S.getLangOpts().CPlusPlus &&
3551 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003552 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003553 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003554 if (!Res.isUsable())
3555 return ExprError();
3556 }
3557 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003558}
3559
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003560namespace {
3561// OpenMP directives parsed in this section are represented as a
3562// CapturedStatement with an associated statement. If a syntax error
3563// is detected during the parsing of the associated statement, the
3564// compiler must abort processing and close the CapturedStatement.
3565//
3566// Combined directives such as 'target parallel' have more than one
3567// nested CapturedStatements. This RAII ensures that we unwind out
3568// of all the nested CapturedStatements when an error is found.
3569class CaptureRegionUnwinderRAII {
3570private:
3571 Sema &S;
3572 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003573 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003574
3575public:
3576 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3577 OpenMPDirectiveKind DKind)
3578 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3579 ~CaptureRegionUnwinderRAII() {
3580 if (ErrorFound) {
3581 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3582 while (--ThisCaptureLevel >= 0)
3583 S.ActOnCapturedRegionError();
3584 }
3585 }
3586};
3587} // namespace
3588
Alexey Bataevb600ae32019-07-01 17:46:52 +00003589void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3590 // Capture variables captured by reference in lambdas for target-based
3591 // directives.
3592 if (!CurContext->isDependentContext() &&
3593 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3594 isOpenMPTargetDataManagementDirective(
3595 DSAStack->getCurrentDirective()))) {
3596 QualType Type = V->getType();
3597 if (const auto *RD = Type.getCanonicalType()
3598 .getNonReferenceType()
3599 ->getAsCXXRecordDecl()) {
3600 bool SavedForceCaptureByReferenceInTargetExecutable =
3601 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3602 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3603 /*V=*/true);
3604 if (RD->isLambda()) {
3605 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3606 FieldDecl *ThisCapture;
3607 RD->getCaptureFields(Captures, ThisCapture);
3608 for (const LambdaCapture &LC : RD->captures()) {
3609 if (LC.getCaptureKind() == LCK_ByRef) {
3610 VarDecl *VD = LC.getCapturedVar();
3611 DeclContext *VDC = VD->getDeclContext();
3612 if (!VDC->Encloses(CurContext))
3613 continue;
3614 MarkVariableReferenced(LC.getLocation(), VD);
3615 } else if (LC.getCaptureKind() == LCK_This) {
3616 QualType ThisTy = getCurrentThisType();
3617 if (!ThisTy.isNull() &&
3618 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3619 CheckCXXThisCapture(LC.getLocation());
3620 }
3621 }
3622 }
3623 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3624 SavedForceCaptureByReferenceInTargetExecutable);
3625 }
3626 }
3627}
3628
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003629StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3630 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003631 bool ErrorFound = false;
3632 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3633 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003634 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003635 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003636 return StmtError();
3637 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003638
Alexey Bataev2ba67042017-11-28 21:11:44 +00003639 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3640 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003641 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003642 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003643 SmallVector<const OMPLinearClause *, 4> LCs;
3644 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003645 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003646 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003647 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3648 Clause->getClauseKind() == OMPC_in_reduction) {
3649 // Capture taskgroup task_reduction descriptors inside the tasking regions
3650 // with the corresponding in_reduction items.
3651 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003652 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003653 if (E)
3654 MarkDeclarationsReferencedInExpr(E);
3655 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003656 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003657 Clause->getClauseKind() == OMPC_copyprivate ||
3658 (getLangOpts().OpenMPUseTLS &&
3659 getASTContext().getTargetInfo().isTLSSupported() &&
3660 Clause->getClauseKind() == OMPC_copyin)) {
3661 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003662 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003663 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003664 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003665 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003666 }
3667 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003668 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003669 } else if (CaptureRegions.size() > 1 ||
3670 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003671 if (auto *C = OMPClauseWithPreInit::get(Clause))
3672 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003673 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003674 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003675 MarkDeclarationsReferencedInExpr(E);
3676 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003677 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003678 if (Clause->getClauseKind() == OMPC_schedule)
3679 SC = cast<OMPScheduleClause>(Clause);
3680 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003681 OC = cast<OMPOrderedClause>(Clause);
3682 else if (Clause->getClauseKind() == OMPC_linear)
3683 LCs.push_back(cast<OMPLinearClause>(Clause));
3684 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003685 // OpenMP, 2.7.1 Loop Construct, Restrictions
3686 // The nonmonotonic modifier cannot be specified if an ordered clause is
3687 // specified.
3688 if (SC &&
3689 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3690 SC->getSecondScheduleModifier() ==
3691 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3692 OC) {
3693 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3694 ? SC->getFirstScheduleModifierLoc()
3695 : SC->getSecondScheduleModifierLoc(),
3696 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003697 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003698 ErrorFound = true;
3699 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003700 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003701 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003702 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003703 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003704 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003705 ErrorFound = true;
3706 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003707 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3708 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3709 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003710 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003711 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3712 ErrorFound = true;
3713 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003714 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003715 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003716 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003717 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003718 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003719 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003720 // Mark all variables in private list clauses as used in inner region.
3721 // Required for proper codegen of combined directives.
3722 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003723 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003724 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003725 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3726 // Find the particular capture region for the clause if the
3727 // directive is a combined one with multiple capture regions.
3728 // If the directive is not a combined one, the capture region
3729 // associated with the clause is OMPD_unknown and is generated
3730 // only once.
3731 if (CaptureRegion == ThisCaptureRegion ||
3732 CaptureRegion == OMPD_unknown) {
3733 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003734 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003735 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3736 }
3737 }
3738 }
3739 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003740 if (++CompletedRegions == CaptureRegions.size())
3741 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003742 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003743 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003744 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003745}
3746
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003747static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3748 OpenMPDirectiveKind CancelRegion,
3749 SourceLocation StartLoc) {
3750 // CancelRegion is only needed for cancel and cancellation_point.
3751 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3752 return false;
3753
3754 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3755 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3756 return false;
3757
3758 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3759 << getOpenMPDirectiveName(CancelRegion);
3760 return true;
3761}
3762
Alexey Bataeve3727102018-04-18 15:57:46 +00003763static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003764 OpenMPDirectiveKind CurrentRegion,
3765 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003766 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003767 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003768 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003769 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3770 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003771 bool NestingProhibited = false;
3772 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003773 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003774 enum {
3775 NoRecommend,
3776 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003777 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003778 ShouldBeInTargetRegion,
3779 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003780 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003781 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003782 // OpenMP [2.16, Nesting of Regions]
3783 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003784 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003785 // An ordered construct with the simd clause is the only OpenMP
3786 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003787 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003788 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3789 // message.
3790 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3791 ? diag::err_omp_prohibited_region_simd
3792 : diag::warn_omp_nesting_simd);
3793 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003794 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003795 if (ParentRegion == OMPD_atomic) {
3796 // OpenMP [2.16, Nesting of Regions]
3797 // OpenMP constructs may not be nested inside an atomic region.
3798 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3799 return true;
3800 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003801 if (CurrentRegion == OMPD_section) {
3802 // OpenMP [2.7.2, sections Construct, Restrictions]
3803 // Orphaned section directives are prohibited. That is, the section
3804 // directives must appear within the sections construct and must not be
3805 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003806 if (ParentRegion != OMPD_sections &&
3807 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003808 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3809 << (ParentRegion != OMPD_unknown)
3810 << getOpenMPDirectiveName(ParentRegion);
3811 return true;
3812 }
3813 return false;
3814 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003815 // Allow some constructs (except teams and cancellation constructs) to be
3816 // orphaned (they could be used in functions, called from OpenMP regions
3817 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003818 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003819 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3820 CurrentRegion != OMPD_cancellation_point &&
3821 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003822 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003823 if (CurrentRegion == OMPD_cancellation_point ||
3824 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003825 // OpenMP [2.16, Nesting of Regions]
3826 // A cancellation point construct for which construct-type-clause is
3827 // taskgroup must be nested inside a task construct. A cancellation
3828 // point construct for which construct-type-clause is not taskgroup must
3829 // be closely nested inside an OpenMP construct that matches the type
3830 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003831 // A cancel construct for which construct-type-clause is taskgroup must be
3832 // nested inside a task construct. A cancel construct for which
3833 // construct-type-clause is not taskgroup must be closely nested inside an
3834 // OpenMP construct that matches the type specified in
3835 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003836 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003837 !((CancelRegion == OMPD_parallel &&
3838 (ParentRegion == OMPD_parallel ||
3839 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003840 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003841 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003842 ParentRegion == OMPD_target_parallel_for ||
3843 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003844 ParentRegion == OMPD_teams_distribute_parallel_for ||
3845 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003846 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3847 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003848 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3849 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003850 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003851 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003852 // OpenMP [2.16, Nesting of Regions]
3853 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003854 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003855 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003856 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003857 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3858 // OpenMP [2.16, Nesting of Regions]
3859 // A critical region may not be nested (closely or otherwise) inside a
3860 // critical region with the same name. Note that this restriction is not
3861 // sufficient to prevent deadlock.
3862 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003863 bool DeadLock = Stack->hasDirective(
3864 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3865 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003866 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003867 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3868 PreviousCriticalLoc = Loc;
3869 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003870 }
3871 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003872 },
3873 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003874 if (DeadLock) {
3875 SemaRef.Diag(StartLoc,
3876 diag::err_omp_prohibited_region_critical_same_name)
3877 << CurrentName.getName();
3878 if (PreviousCriticalLoc.isValid())
3879 SemaRef.Diag(PreviousCriticalLoc,
3880 diag::note_omp_previous_critical_region);
3881 return true;
3882 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003883 } else if (CurrentRegion == OMPD_barrier) {
3884 // OpenMP [2.16, Nesting of Regions]
3885 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003886 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003887 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3888 isOpenMPTaskingDirective(ParentRegion) ||
3889 ParentRegion == OMPD_master ||
3890 ParentRegion == OMPD_critical ||
3891 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003892 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003893 !isOpenMPParallelDirective(CurrentRegion) &&
3894 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003895 // OpenMP [2.16, Nesting of Regions]
3896 // A worksharing region may not be closely nested inside a worksharing,
3897 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003898 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3899 isOpenMPTaskingDirective(ParentRegion) ||
3900 ParentRegion == OMPD_master ||
3901 ParentRegion == OMPD_critical ||
3902 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003903 Recommend = ShouldBeInParallelRegion;
3904 } else if (CurrentRegion == OMPD_ordered) {
3905 // OpenMP [2.16, Nesting of Regions]
3906 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003907 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003908 // An ordered region must be closely nested inside a loop region (or
3909 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003910 // OpenMP [2.8.1,simd Construct, Restrictions]
3911 // An ordered construct with the simd clause is the only OpenMP construct
3912 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003913 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003914 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003915 !(isOpenMPSimdDirective(ParentRegion) ||
3916 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003917 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003918 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003919 // OpenMP [2.16, Nesting of Regions]
3920 // If specified, a teams construct must be contained within a target
3921 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00003922 NestingProhibited =
3923 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3924 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3925 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00003926 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003927 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003928 }
Kelvin Libf594a52016-12-17 05:48:59 +00003929 if (!NestingProhibited &&
3930 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3931 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3932 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003933 // OpenMP [2.16, Nesting of Regions]
3934 // distribute, parallel, parallel sections, parallel workshare, and the
3935 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3936 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003937 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3938 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003939 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003940 }
David Majnemer9d168222016-08-05 17:44:54 +00003941 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003942 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003943 // OpenMP 4.5 [2.17 Nesting of Regions]
3944 // The region associated with the distribute construct must be strictly
3945 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003946 NestingProhibited =
3947 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003948 Recommend = ShouldBeInTeamsRegion;
3949 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003950 if (!NestingProhibited &&
3951 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3952 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3953 // OpenMP 4.5 [2.17 Nesting of Regions]
3954 // If a target, target update, target data, target enter data, or
3955 // target exit data construct is encountered during execution of a
3956 // target region, the behavior is unspecified.
3957 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003958 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003959 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003960 if (isOpenMPTargetExecutionDirective(K)) {
3961 OffendingRegion = K;
3962 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003963 }
3964 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003965 },
3966 false /* don't skip top directive */);
3967 CloseNesting = false;
3968 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003969 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003970 if (OrphanSeen) {
3971 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3972 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3973 } else {
3974 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3975 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3976 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3977 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003978 return true;
3979 }
3980 }
3981 return false;
3982}
3983
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003984static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3985 ArrayRef<OMPClause *> Clauses,
3986 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3987 bool ErrorFound = false;
3988 unsigned NamedModifiersNumber = 0;
3989 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3990 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003991 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003992 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003993 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3994 // At most one if clause without a directive-name-modifier can appear on
3995 // the directive.
3996 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3997 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003998 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003999 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4000 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4001 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004002 } else if (CurNM != OMPD_unknown) {
4003 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004004 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004005 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004006 FoundNameModifiers[CurNM] = IC;
4007 if (CurNM == OMPD_unknown)
4008 continue;
4009 // Check if the specified name modifier is allowed for the current
4010 // directive.
4011 // At most one if clause with the particular directive-name-modifier can
4012 // appear on the directive.
4013 bool MatchFound = false;
4014 for (auto NM : AllowedNameModifiers) {
4015 if (CurNM == NM) {
4016 MatchFound = true;
4017 break;
4018 }
4019 }
4020 if (!MatchFound) {
4021 S.Diag(IC->getNameModifierLoc(),
4022 diag::err_omp_wrong_if_directive_name_modifier)
4023 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4024 ErrorFound = true;
4025 }
4026 }
4027 }
4028 // If any if clause on the directive includes a directive-name-modifier then
4029 // all if clauses on the directive must include a directive-name-modifier.
4030 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4031 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004032 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004033 diag::err_omp_no_more_if_clause);
4034 } else {
4035 std::string Values;
4036 std::string Sep(", ");
4037 unsigned AllowedCnt = 0;
4038 unsigned TotalAllowedNum =
4039 AllowedNameModifiers.size() - NamedModifiersNumber;
4040 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4041 ++Cnt) {
4042 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4043 if (!FoundNameModifiers[NM]) {
4044 Values += "'";
4045 Values += getOpenMPDirectiveName(NM);
4046 Values += "'";
4047 if (AllowedCnt + 2 == TotalAllowedNum)
4048 Values += " or ";
4049 else if (AllowedCnt + 1 != TotalAllowedNum)
4050 Values += Sep;
4051 ++AllowedCnt;
4052 }
4053 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004054 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004055 diag::err_omp_unnamed_if_clause)
4056 << (TotalAllowedNum > 1) << Values;
4057 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004058 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004059 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4060 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004061 ErrorFound = true;
4062 }
4063 return ErrorFound;
4064}
4065
Alexey Bataeve106f252019-04-01 14:25:31 +00004066static std::pair<ValueDecl *, bool>
4067getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4068 SourceRange &ERange, bool AllowArraySection = false) {
4069 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4070 RefExpr->containsUnexpandedParameterPack())
4071 return std::make_pair(nullptr, true);
4072
4073 // OpenMP [3.1, C/C++]
4074 // A list item is a variable name.
4075 // OpenMP [2.9.3.3, Restrictions, p.1]
4076 // A variable that is part of another variable (as an array or
4077 // structure element) cannot appear in a private clause.
4078 RefExpr = RefExpr->IgnoreParens();
4079 enum {
4080 NoArrayExpr = -1,
4081 ArraySubscript = 0,
4082 OMPArraySection = 1
4083 } IsArrayExpr = NoArrayExpr;
4084 if (AllowArraySection) {
4085 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4086 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4087 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4088 Base = TempASE->getBase()->IgnoreParenImpCasts();
4089 RefExpr = Base;
4090 IsArrayExpr = ArraySubscript;
4091 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4092 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4093 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4094 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4095 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4096 Base = TempASE->getBase()->IgnoreParenImpCasts();
4097 RefExpr = Base;
4098 IsArrayExpr = OMPArraySection;
4099 }
4100 }
4101 ELoc = RefExpr->getExprLoc();
4102 ERange = RefExpr->getSourceRange();
4103 RefExpr = RefExpr->IgnoreParenImpCasts();
4104 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4105 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4106 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4107 (S.getCurrentThisType().isNull() || !ME ||
4108 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4109 !isa<FieldDecl>(ME->getMemberDecl()))) {
4110 if (IsArrayExpr != NoArrayExpr) {
4111 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4112 << ERange;
4113 } else {
4114 S.Diag(ELoc,
4115 AllowArraySection
4116 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4117 : diag::err_omp_expected_var_name_member_expr)
4118 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4119 }
4120 return std::make_pair(nullptr, false);
4121 }
4122 return std::make_pair(
4123 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4124}
4125
4126static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004127 ArrayRef<OMPClause *> Clauses) {
4128 assert(!S.CurContext->isDependentContext() &&
4129 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004130 auto AllocateRange =
4131 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004132 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4133 DeclToCopy;
4134 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4135 return isOpenMPPrivate(C->getClauseKind());
4136 });
4137 for (OMPClause *Cl : PrivateRange) {
4138 MutableArrayRef<Expr *>::iterator I, It, Et;
4139 if (Cl->getClauseKind() == OMPC_private) {
4140 auto *PC = cast<OMPPrivateClause>(Cl);
4141 I = PC->private_copies().begin();
4142 It = PC->varlist_begin();
4143 Et = PC->varlist_end();
4144 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4145 auto *PC = cast<OMPFirstprivateClause>(Cl);
4146 I = PC->private_copies().begin();
4147 It = PC->varlist_begin();
4148 Et = PC->varlist_end();
4149 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4150 auto *PC = cast<OMPLastprivateClause>(Cl);
4151 I = PC->private_copies().begin();
4152 It = PC->varlist_begin();
4153 Et = PC->varlist_end();
4154 } else if (Cl->getClauseKind() == OMPC_linear) {
4155 auto *PC = cast<OMPLinearClause>(Cl);
4156 I = PC->privates().begin();
4157 It = PC->varlist_begin();
4158 Et = PC->varlist_end();
4159 } else if (Cl->getClauseKind() == OMPC_reduction) {
4160 auto *PC = cast<OMPReductionClause>(Cl);
4161 I = PC->privates().begin();
4162 It = PC->varlist_begin();
4163 Et = PC->varlist_end();
4164 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4165 auto *PC = cast<OMPTaskReductionClause>(Cl);
4166 I = PC->privates().begin();
4167 It = PC->varlist_begin();
4168 Et = PC->varlist_end();
4169 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4170 auto *PC = cast<OMPInReductionClause>(Cl);
4171 I = PC->privates().begin();
4172 It = PC->varlist_begin();
4173 Et = PC->varlist_end();
4174 } else {
4175 llvm_unreachable("Expected private clause.");
4176 }
4177 for (Expr *E : llvm::make_range(It, Et)) {
4178 if (!*I) {
4179 ++I;
4180 continue;
4181 }
4182 SourceLocation ELoc;
4183 SourceRange ERange;
4184 Expr *SimpleRefExpr = E;
4185 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4186 /*AllowArraySection=*/true);
4187 DeclToCopy.try_emplace(Res.first,
4188 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4189 ++I;
4190 }
4191 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004192 for (OMPClause *C : AllocateRange) {
4193 auto *AC = cast<OMPAllocateClause>(C);
4194 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4195 getAllocatorKind(S, Stack, AC->getAllocator());
4196 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4197 // For task, taskloop or target directives, allocation requests to memory
4198 // allocators with the trait access set to thread result in unspecified
4199 // behavior.
4200 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4201 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4202 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4203 S.Diag(AC->getAllocator()->getExprLoc(),
4204 diag::warn_omp_allocate_thread_on_task_target_directive)
4205 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004206 }
4207 for (Expr *E : AC->varlists()) {
4208 SourceLocation ELoc;
4209 SourceRange ERange;
4210 Expr *SimpleRefExpr = E;
4211 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4212 ValueDecl *VD = Res.first;
4213 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4214 if (!isOpenMPPrivate(Data.CKind)) {
4215 S.Diag(E->getExprLoc(),
4216 diag::err_omp_expected_private_copy_for_allocate);
4217 continue;
4218 }
4219 VarDecl *PrivateVD = DeclToCopy[VD];
4220 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4221 AllocatorKind, AC->getAllocator()))
4222 continue;
4223 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4224 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004225 }
4226 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004227}
4228
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004229StmtResult Sema::ActOnOpenMPExecutableDirective(
4230 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4231 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4232 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004233 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004234 // First check CancelRegion which is then used in checkNestingOfRegions.
4235 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4236 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004237 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004238 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004239
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004240 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004241 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004242 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004243 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004244 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004245 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4246
4247 // Check default data sharing attributes for referenced variables.
4248 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004249 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4250 Stmt *S = AStmt;
4251 while (--ThisCaptureLevel >= 0)
4252 S = cast<CapturedStmt>(S)->getCapturedStmt();
4253 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004254 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4255 !isOpenMPTaskingDirective(Kind)) {
4256 // Visit subcaptures to generate implicit clauses for captured vars.
4257 auto *CS = cast<CapturedStmt>(AStmt);
4258 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4259 getOpenMPCaptureRegions(CaptureRegions, Kind);
4260 // Ignore outer tasking regions for target directives.
4261 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4262 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4263 DSAChecker.visitSubCaptures(CS);
4264 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004265 if (DSAChecker.isErrorFound())
4266 return StmtError();
4267 // Generate list of implicitly defined firstprivate variables.
4268 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004269
Alexey Bataev88202be2017-07-27 13:20:36 +00004270 SmallVector<Expr *, 4> ImplicitFirstprivates(
4271 DSAChecker.getImplicitFirstprivate().begin(),
4272 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004273 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4274 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004275 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004276 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004277 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004278 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004279 if (E)
4280 ImplicitFirstprivates.emplace_back(E);
4281 }
4282 }
4283 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004284 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004285 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4286 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004287 ClausesWithImplicit.push_back(Implicit);
4288 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004289 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004290 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004291 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004292 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004293 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004294 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004295 CXXScopeSpec MapperIdScopeSpec;
4296 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004297 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004298 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4299 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4300 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004301 ClausesWithImplicit.emplace_back(Implicit);
4302 ErrorFound |=
4303 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004304 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004305 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004306 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004307 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004308 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004309
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004310 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004311 switch (Kind) {
4312 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004313 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4314 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004315 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004316 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004317 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004318 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4319 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004320 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004321 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004322 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4323 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004324 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004325 case OMPD_for_simd:
4326 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4327 EndLoc, VarsWithInheritedDSA);
4328 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004329 case OMPD_sections:
4330 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4331 EndLoc);
4332 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004333 case OMPD_section:
4334 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004335 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004336 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4337 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004338 case OMPD_single:
4339 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4340 EndLoc);
4341 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004342 case OMPD_master:
4343 assert(ClausesWithImplicit.empty() &&
4344 "No clauses are allowed for 'omp master' directive");
4345 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4346 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004347 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004348 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4349 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004350 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004351 case OMPD_parallel_for:
4352 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4353 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004354 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004355 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004356 case OMPD_parallel_for_simd:
4357 Res = ActOnOpenMPParallelForSimdDirective(
4358 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004359 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004360 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004361 case OMPD_parallel_sections:
4362 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4363 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004364 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004365 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004366 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004367 Res =
4368 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004369 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004370 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004371 case OMPD_taskyield:
4372 assert(ClausesWithImplicit.empty() &&
4373 "No clauses are allowed for 'omp taskyield' directive");
4374 assert(AStmt == nullptr &&
4375 "No associated statement allowed for 'omp taskyield' directive");
4376 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4377 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004378 case OMPD_barrier:
4379 assert(ClausesWithImplicit.empty() &&
4380 "No clauses are allowed for 'omp barrier' directive");
4381 assert(AStmt == nullptr &&
4382 "No associated statement allowed for 'omp barrier' directive");
4383 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4384 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004385 case OMPD_taskwait:
4386 assert(ClausesWithImplicit.empty() &&
4387 "No clauses are allowed for 'omp taskwait' directive");
4388 assert(AStmt == nullptr &&
4389 "No associated statement allowed for 'omp taskwait' directive");
4390 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4391 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004392 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004393 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4394 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004395 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004396 case OMPD_flush:
4397 assert(AStmt == nullptr &&
4398 "No associated statement allowed for 'omp flush' directive");
4399 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4400 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004401 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004402 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4403 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004404 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004405 case OMPD_atomic:
4406 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4407 EndLoc);
4408 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004409 case OMPD_teams:
4410 Res =
4411 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4412 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004413 case OMPD_target:
4414 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4415 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004416 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004417 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004418 case OMPD_target_parallel:
4419 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4420 StartLoc, EndLoc);
4421 AllowedNameModifiers.push_back(OMPD_target);
4422 AllowedNameModifiers.push_back(OMPD_parallel);
4423 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004424 case OMPD_target_parallel_for:
4425 Res = ActOnOpenMPTargetParallelForDirective(
4426 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4427 AllowedNameModifiers.push_back(OMPD_target);
4428 AllowedNameModifiers.push_back(OMPD_parallel);
4429 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004430 case OMPD_cancellation_point:
4431 assert(ClausesWithImplicit.empty() &&
4432 "No clauses are allowed for 'omp cancellation point' directive");
4433 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4434 "cancellation point' directive");
4435 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4436 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004437 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004438 assert(AStmt == nullptr &&
4439 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004440 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4441 CancelRegion);
4442 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004443 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004444 case OMPD_target_data:
4445 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4446 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004447 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004448 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004449 case OMPD_target_enter_data:
4450 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004451 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004452 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4453 break;
Samuel Antao72590762016-01-19 20:04:50 +00004454 case OMPD_target_exit_data:
4455 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004456 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004457 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4458 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004459 case OMPD_taskloop:
4460 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4461 EndLoc, VarsWithInheritedDSA);
4462 AllowedNameModifiers.push_back(OMPD_taskloop);
4463 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004464 case OMPD_taskloop_simd:
4465 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4466 EndLoc, VarsWithInheritedDSA);
4467 AllowedNameModifiers.push_back(OMPD_taskloop);
4468 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004469 case OMPD_master_taskloop:
4470 Res = ActOnOpenMPMasterTaskLoopDirective(
4471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4472 AllowedNameModifiers.push_back(OMPD_taskloop);
4473 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004474 case OMPD_parallel_master_taskloop:
4475 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4477 AllowedNameModifiers.push_back(OMPD_taskloop);
4478 AllowedNameModifiers.push_back(OMPD_parallel);
4479 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004480 case OMPD_distribute:
4481 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4482 EndLoc, VarsWithInheritedDSA);
4483 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004484 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004485 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4486 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004487 AllowedNameModifiers.push_back(OMPD_target_update);
4488 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004489 case OMPD_distribute_parallel_for:
4490 Res = ActOnOpenMPDistributeParallelForDirective(
4491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4492 AllowedNameModifiers.push_back(OMPD_parallel);
4493 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004494 case OMPD_distribute_parallel_for_simd:
4495 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4496 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4497 AllowedNameModifiers.push_back(OMPD_parallel);
4498 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004499 case OMPD_distribute_simd:
4500 Res = ActOnOpenMPDistributeSimdDirective(
4501 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4502 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004503 case OMPD_target_parallel_for_simd:
4504 Res = ActOnOpenMPTargetParallelForSimdDirective(
4505 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4506 AllowedNameModifiers.push_back(OMPD_target);
4507 AllowedNameModifiers.push_back(OMPD_parallel);
4508 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004509 case OMPD_target_simd:
4510 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4511 EndLoc, VarsWithInheritedDSA);
4512 AllowedNameModifiers.push_back(OMPD_target);
4513 break;
Kelvin Li02532872016-08-05 14:37:37 +00004514 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004515 Res = ActOnOpenMPTeamsDistributeDirective(
4516 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004517 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004518 case OMPD_teams_distribute_simd:
4519 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4520 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4521 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004522 case OMPD_teams_distribute_parallel_for_simd:
4523 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4524 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4525 AllowedNameModifiers.push_back(OMPD_parallel);
4526 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004527 case OMPD_teams_distribute_parallel_for:
4528 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4529 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4530 AllowedNameModifiers.push_back(OMPD_parallel);
4531 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004532 case OMPD_target_teams:
4533 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4534 EndLoc);
4535 AllowedNameModifiers.push_back(OMPD_target);
4536 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004537 case OMPD_target_teams_distribute:
4538 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4539 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4540 AllowedNameModifiers.push_back(OMPD_target);
4541 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004542 case OMPD_target_teams_distribute_parallel_for:
4543 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4544 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4545 AllowedNameModifiers.push_back(OMPD_target);
4546 AllowedNameModifiers.push_back(OMPD_parallel);
4547 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004548 case OMPD_target_teams_distribute_parallel_for_simd:
4549 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4551 AllowedNameModifiers.push_back(OMPD_target);
4552 AllowedNameModifiers.push_back(OMPD_parallel);
4553 break;
Kelvin Lida681182017-01-10 18:08:18 +00004554 case OMPD_target_teams_distribute_simd:
4555 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4556 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4557 AllowedNameModifiers.push_back(OMPD_target);
4558 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004559 case OMPD_declare_target:
4560 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004561 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004562 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004563 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004564 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004565 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004566 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004567 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004568 llvm_unreachable("OpenMP Directive is not allowed");
4569 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004570 llvm_unreachable("Unknown OpenMP directive");
4571 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004572
Roman Lebedevb5700602019-03-20 16:32:36 +00004573 ErrorFound = Res.isInvalid() || ErrorFound;
4574
Alexey Bataev412254a2019-05-09 18:44:53 +00004575 // Check variables in the clauses if default(none) was specified.
4576 if (DSAStack->getDefaultDSA() == DSA_none) {
4577 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4578 for (OMPClause *C : Clauses) {
4579 switch (C->getClauseKind()) {
4580 case OMPC_num_threads:
4581 case OMPC_dist_schedule:
4582 // Do not analyse if no parent teams directive.
4583 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4584 break;
4585 continue;
4586 case OMPC_if:
4587 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4588 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4589 break;
4590 continue;
4591 case OMPC_schedule:
4592 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004593 case OMPC_grainsize:
4594 // Do not analyze if no parent parallel directive.
4595 if (isOpenMPParallelDirective(DSAStack->getCurrentDirective()))
4596 break;
4597 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004598 case OMPC_ordered:
4599 case OMPC_device:
4600 case OMPC_num_teams:
4601 case OMPC_thread_limit:
4602 case OMPC_priority:
Alexey Bataev412254a2019-05-09 18:44:53 +00004603 case OMPC_num_tasks:
4604 case OMPC_hint:
4605 case OMPC_collapse:
4606 case OMPC_safelen:
4607 case OMPC_simdlen:
4608 case OMPC_final:
4609 case OMPC_default:
4610 case OMPC_proc_bind:
4611 case OMPC_private:
4612 case OMPC_firstprivate:
4613 case OMPC_lastprivate:
4614 case OMPC_shared:
4615 case OMPC_reduction:
4616 case OMPC_task_reduction:
4617 case OMPC_in_reduction:
4618 case OMPC_linear:
4619 case OMPC_aligned:
4620 case OMPC_copyin:
4621 case OMPC_copyprivate:
4622 case OMPC_nowait:
4623 case OMPC_untied:
4624 case OMPC_mergeable:
4625 case OMPC_allocate:
4626 case OMPC_read:
4627 case OMPC_write:
4628 case OMPC_update:
4629 case OMPC_capture:
4630 case OMPC_seq_cst:
4631 case OMPC_depend:
4632 case OMPC_threads:
4633 case OMPC_simd:
4634 case OMPC_map:
4635 case OMPC_nogroup:
4636 case OMPC_defaultmap:
4637 case OMPC_to:
4638 case OMPC_from:
4639 case OMPC_use_device_ptr:
4640 case OMPC_is_device_ptr:
4641 continue;
4642 case OMPC_allocator:
4643 case OMPC_flush:
4644 case OMPC_threadprivate:
4645 case OMPC_uniform:
4646 case OMPC_unknown:
4647 case OMPC_unified_address:
4648 case OMPC_unified_shared_memory:
4649 case OMPC_reverse_offload:
4650 case OMPC_dynamic_allocators:
4651 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004652 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004653 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004654 llvm_unreachable("Unexpected clause");
4655 }
4656 for (Stmt *CC : C->children()) {
4657 if (CC)
4658 DSAChecker.Visit(CC);
4659 }
4660 }
4661 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4662 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4663 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004664 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004665 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4666 continue;
4667 ErrorFound = true;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004668 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4669 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004670 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004671 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004672
4673 if (!AllowedNameModifiers.empty())
4674 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4675 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004676
Alexey Bataeved09d242014-05-28 05:53:51 +00004677 if (ErrorFound)
4678 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004679
4680 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4681 Res.getAs<OMPExecutableDirective>()
4682 ->getStructuredBlock()
4683 ->setIsOMPStructuredBlock(true);
4684 }
4685
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004686 if (!CurContext->isDependentContext() &&
4687 isOpenMPTargetExecutionDirective(Kind) &&
4688 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4689 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4690 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4691 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4692 // Register target to DSA Stack.
4693 DSAStack->addTargetDirLocation(StartLoc);
4694 }
4695
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004696 return Res;
4697}
4698
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004699Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4700 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004701 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004702 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4703 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004704 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004705 assert(Linears.size() == LinModifiers.size());
4706 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004707 if (!DG || DG.get().isNull())
4708 return DeclGroupPtrTy();
4709
Alexey Bataevd158cf62019-09-13 20:18:17 +00004710 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004711 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004712 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4713 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004714 return DG;
4715 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004716 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004717 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4718 ADecl = FTD->getTemplatedDecl();
4719
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004720 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4721 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004722 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004723 return DeclGroupPtrTy();
4724 }
4725
Alexey Bataev2af33e32016-04-07 12:45:37 +00004726 // OpenMP [2.8.2, declare simd construct, Description]
4727 // The parameter of the simdlen clause must be a constant positive integer
4728 // expression.
4729 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004730 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004731 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004732 // OpenMP [2.8.2, declare simd construct, Description]
4733 // The special this pointer can be used as if was one of the arguments to the
4734 // function in any of the linear, aligned, or uniform clauses.
4735 // The uniform clause declares one or more arguments to have an invariant
4736 // value for all concurrent invocations of the function in the execution of a
4737 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004738 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4739 const Expr *UniformedLinearThis = nullptr;
4740 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004741 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004742 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4743 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004744 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4745 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004746 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004747 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004748 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004749 }
4750 if (isa<CXXThisExpr>(E)) {
4751 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004752 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004753 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004754 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4755 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004756 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004757 // OpenMP [2.8.2, declare simd construct, Description]
4758 // The aligned clause declares that the object to which each list item points
4759 // is aligned to the number of bytes expressed in the optional parameter of
4760 // the aligned clause.
4761 // The special this pointer can be used as if was one of the arguments to the
4762 // function in any of the linear, aligned, or uniform clauses.
4763 // The type of list items appearing in the aligned clause must be array,
4764 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004765 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4766 const Expr *AlignedThis = nullptr;
4767 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004768 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004769 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4770 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4771 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004772 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4773 FD->getParamDecl(PVD->getFunctionScopeIndex())
4774 ->getCanonicalDecl() == CanonPVD) {
4775 // OpenMP [2.8.1, simd construct, Restrictions]
4776 // A list-item cannot appear in more than one aligned clause.
4777 if (AlignedArgs.count(CanonPVD) > 0) {
4778 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4779 << 1 << E->getSourceRange();
4780 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4781 diag::note_omp_explicit_dsa)
4782 << getOpenMPClauseName(OMPC_aligned);
4783 continue;
4784 }
4785 AlignedArgs[CanonPVD] = E;
4786 QualType QTy = PVD->getType()
4787 .getNonReferenceType()
4788 .getUnqualifiedType()
4789 .getCanonicalType();
4790 const Type *Ty = QTy.getTypePtrOrNull();
4791 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4792 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4793 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4794 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4795 }
4796 continue;
4797 }
4798 }
4799 if (isa<CXXThisExpr>(E)) {
4800 if (AlignedThis) {
4801 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4802 << 2 << E->getSourceRange();
4803 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4804 << getOpenMPClauseName(OMPC_aligned);
4805 }
4806 AlignedThis = E;
4807 continue;
4808 }
4809 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4810 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4811 }
4812 // The optional parameter of the aligned clause, alignment, must be a constant
4813 // positive integer expression. If no optional parameter is specified,
4814 // implementation-defined default alignments for SIMD instructions on the
4815 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004816 SmallVector<const Expr *, 4> NewAligns;
4817 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004818 ExprResult Align;
4819 if (E)
4820 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4821 NewAligns.push_back(Align.get());
4822 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004823 // OpenMP [2.8.2, declare simd construct, Description]
4824 // The linear clause declares one or more list items to be private to a SIMD
4825 // lane and to have a linear relationship with respect to the iteration space
4826 // of a loop.
4827 // The special this pointer can be used as if was one of the arguments to the
4828 // function in any of the linear, aligned, or uniform clauses.
4829 // When a linear-step expression is specified in a linear clause it must be
4830 // either a constant integer expression or an integer-typed parameter that is
4831 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004832 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004833 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4834 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004835 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004836 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4837 ++MI;
4838 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004839 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4840 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4841 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004842 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4843 FD->getParamDecl(PVD->getFunctionScopeIndex())
4844 ->getCanonicalDecl() == CanonPVD) {
4845 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4846 // A list-item cannot appear in more than one linear clause.
4847 if (LinearArgs.count(CanonPVD) > 0) {
4848 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4849 << getOpenMPClauseName(OMPC_linear)
4850 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4851 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4852 diag::note_omp_explicit_dsa)
4853 << getOpenMPClauseName(OMPC_linear);
4854 continue;
4855 }
4856 // Each argument can appear in at most one uniform or linear clause.
4857 if (UniformedArgs.count(CanonPVD) > 0) {
4858 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4859 << getOpenMPClauseName(OMPC_linear)
4860 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4861 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4862 diag::note_omp_explicit_dsa)
4863 << getOpenMPClauseName(OMPC_uniform);
4864 continue;
4865 }
4866 LinearArgs[CanonPVD] = E;
4867 if (E->isValueDependent() || E->isTypeDependent() ||
4868 E->isInstantiationDependent() ||
4869 E->containsUnexpandedParameterPack())
4870 continue;
4871 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4872 PVD->getOriginalType());
4873 continue;
4874 }
4875 }
4876 if (isa<CXXThisExpr>(E)) {
4877 if (UniformedLinearThis) {
4878 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4879 << getOpenMPClauseName(OMPC_linear)
4880 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4881 << E->getSourceRange();
4882 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4883 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4884 : OMPC_linear);
4885 continue;
4886 }
4887 UniformedLinearThis = E;
4888 if (E->isValueDependent() || E->isTypeDependent() ||
4889 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4890 continue;
4891 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4892 E->getType());
4893 continue;
4894 }
4895 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4896 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4897 }
4898 Expr *Step = nullptr;
4899 Expr *NewStep = nullptr;
4900 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004901 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004902 // Skip the same step expression, it was checked already.
4903 if (Step == E || !E) {
4904 NewSteps.push_back(E ? NewStep : nullptr);
4905 continue;
4906 }
4907 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004908 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4909 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4910 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004911 if (UniformedArgs.count(CanonPVD) == 0) {
4912 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4913 << Step->getSourceRange();
4914 } else if (E->isValueDependent() || E->isTypeDependent() ||
4915 E->isInstantiationDependent() ||
4916 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004917 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004918 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004919 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004920 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4921 << Step->getSourceRange();
4922 }
4923 continue;
4924 }
4925 NewStep = Step;
4926 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4927 !Step->isInstantiationDependent() &&
4928 !Step->containsUnexpandedParameterPack()) {
4929 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4930 .get();
4931 if (NewStep)
4932 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4933 }
4934 NewSteps.push_back(NewStep);
4935 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004936 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4937 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004938 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004939 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4940 const_cast<Expr **>(Linears.data()), Linears.size(),
4941 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4942 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004943 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00004944 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004945}
4946
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004947Optional<std::pair<FunctionDecl *, Expr *>>
4948Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
4949 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004950 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004951 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004952
4953 const int VariantId = 1;
4954 // Must be applied only to single decl.
4955 if (!DG.get().isSingleDecl()) {
4956 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4957 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004958 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004959 }
4960 Decl *ADecl = DG.get().getSingleDecl();
4961 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4962 ADecl = FTD->getTemplatedDecl();
4963
4964 // Decl must be a function.
4965 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4966 if (!FD) {
4967 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
4968 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004969 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004970 }
4971
4972 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
4973 return FD->hasAttrs() &&
4974 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
4975 FD->hasAttr<TargetAttr>());
4976 };
4977 // OpenMP is not compatible with CPU-specific attributes.
4978 if (HasMultiVersionAttributes(FD)) {
4979 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
4980 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004981 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004982 }
4983
4984 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00004985 if (FD->isUsed(false))
4986 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00004987 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00004988
4989 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00004990 const FunctionDecl *Definition;
4991 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
4992 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00004993 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
4994 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00004995
4996 // The VariantRef must point to function.
4997 if (!VariantRef) {
4998 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004999 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005000 }
5001
5002 // Do not check templates, wait until instantiation.
5003 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5004 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005005 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5006 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005007
5008 // Convert VariantRef expression to the type of the original function to
5009 // resolve possible conflicts.
5010 ExprResult VariantRefCast;
5011 if (LangOpts.CPlusPlus) {
5012 QualType FnPtrType;
5013 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5014 if (Method && !Method->isStatic()) {
5015 const Type *ClassType =
5016 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5017 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5018 ExprResult ER;
5019 {
5020 // Build adrr_of unary op to correctly handle type checks for member
5021 // functions.
5022 Sema::TentativeAnalysisScope Trap(*this);
5023 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5024 VariantRef);
5025 }
5026 if (!ER.isUsable()) {
5027 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5028 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005029 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005030 }
5031 VariantRef = ER.get();
5032 } else {
5033 FnPtrType = Context.getPointerType(FD->getType());
5034 }
5035 ImplicitConversionSequence ICS =
5036 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5037 /*SuppressUserConversions=*/false,
5038 /*AllowExplicit=*/false,
5039 /*InOverloadResolution=*/false,
5040 /*CStyle=*/false,
5041 /*AllowObjCWritebackConversion=*/false);
5042 if (ICS.isFailure()) {
5043 Diag(VariantRef->getExprLoc(),
5044 diag::err_omp_declare_variant_incompat_types)
5045 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005046 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005047 }
5048 VariantRefCast = PerformImplicitConversion(
5049 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5050 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005051 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005052 // Drop previously built artificial addr_of unary op for member functions.
5053 if (Method && !Method->isStatic()) {
5054 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5055 if (auto *UO = dyn_cast<UnaryOperator>(
5056 PossibleAddrOfVariantRef->IgnoreImplicit()))
5057 VariantRefCast = UO->getSubExpr();
5058 }
5059 } else {
5060 VariantRefCast = VariantRef;
5061 }
5062
5063 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5064 if (!ER.isUsable() ||
5065 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5066 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5067 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005068 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005069 }
5070
5071 // The VariantRef must point to function.
5072 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5073 if (!DRE) {
5074 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5075 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005076 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005077 }
5078 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5079 if (!NewFD) {
5080 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5081 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005082 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005083 }
5084
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005085 // Check if variant function is not marked with declare variant directive.
5086 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5087 Diag(VariantRef->getExprLoc(),
5088 diag::warn_omp_declare_variant_marked_as_declare_variant)
5089 << VariantRef->getSourceRange();
5090 SourceRange SR =
5091 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5092 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005093 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005094 }
5095
Alexey Bataevd158cf62019-09-13 20:18:17 +00005096 enum DoesntSupport {
5097 VirtFuncs = 1,
5098 Constructors = 3,
5099 Destructors = 4,
5100 DeletedFuncs = 5,
5101 DefaultedFuncs = 6,
5102 ConstexprFuncs = 7,
5103 ConstevalFuncs = 8,
5104 };
5105 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5106 if (CXXFD->isVirtual()) {
5107 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5108 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005109 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005110 }
5111
5112 if (isa<CXXConstructorDecl>(FD)) {
5113 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5114 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005115 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005116 }
5117
5118 if (isa<CXXDestructorDecl>(FD)) {
5119 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5120 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005121 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005122 }
5123 }
5124
5125 if (FD->isDeleted()) {
5126 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5127 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005128 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005129 }
5130
5131 if (FD->isDefaulted()) {
5132 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5133 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005134 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005135 }
5136
5137 if (FD->isConstexpr()) {
5138 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5139 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005140 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005141 }
5142
5143 // Check general compatibility.
5144 if (areMultiversionVariantFunctionsCompatible(
5145 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5146 PartialDiagnosticAt(
5147 SR.getBegin(),
5148 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5149 PartialDiagnosticAt(
5150 VariantRef->getExprLoc(),
5151 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5152 PartialDiagnosticAt(VariantRef->getExprLoc(),
5153 PDiag(diag::err_omp_declare_variant_diff)
5154 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005155 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5156 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005157 return None;
5158 return std::make_pair(FD, cast<Expr>(DRE));
5159}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005160
Alexey Bataev9ff34742019-09-25 19:43:37 +00005161void Sema::ActOnOpenMPDeclareVariantDirective(
5162 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
5163 const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
5164 if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
5165 Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
5166 return;
Alexey Bataeva15a1412019-10-02 18:19:02 +00005167 Expr *Score = nullptr;
5168 OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
5169 if (Data.CtxScore.isUsable()) {
5170 ST = OMPDeclareVariantAttr::ScoreSpecified;
5171 Score = Data.CtxScore.get();
5172 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5173 !Score->isInstantiationDependent() &&
5174 !Score->containsUnexpandedParameterPack()) {
5175 llvm::APSInt Result;
5176 ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
5177 if (ICE.isInvalid())
5178 return;
5179 }
5180 }
Alexey Bataev9ff34742019-09-25 19:43:37 +00005181 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
Alexey Bataev303657a2019-10-08 19:44:16 +00005182 Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
5183 Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005184 FD->addAttr(NewAttr);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005185}
5186
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005187void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5188 FunctionDecl *Func,
5189 bool MightBeOdrUse) {
5190 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5191
5192 if (!Func->isDependentContext() && Func->hasAttrs()) {
5193 for (OMPDeclareVariantAttr *A :
5194 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5195 // TODO: add checks for active OpenMP context where possible.
5196 Expr *VariantRef = A->getVariantFuncRef();
5197 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5198 auto *F = cast<FunctionDecl>(DRE->getDecl());
5199 if (!F->isDefined() && F->isTemplateInstantiation())
5200 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5201 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5202 }
5203 }
5204}
5205
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005206StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5207 Stmt *AStmt,
5208 SourceLocation StartLoc,
5209 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005210 if (!AStmt)
5211 return StmtError();
5212
Alexey Bataeve3727102018-04-18 15:57:46 +00005213 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005214 // 1.2.2 OpenMP Language Terminology
5215 // Structured block - An executable statement with a single entry at the
5216 // top and a single exit at the bottom.
5217 // The point of exit cannot be a branch out of the structured block.
5218 // longjmp() and throw() must not violate the entry/exit criteria.
5219 CS->getCapturedDecl()->setNothrow();
5220
Reid Kleckner87a31802018-03-12 21:43:02 +00005221 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005222
Alexey Bataev25e5b442015-09-15 12:52:43 +00005223 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5224 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005225}
5226
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005227namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005228/// Iteration space of a single for loop.
5229struct LoopIterationSpace final {
5230 /// True if the condition operator is the strict compare operator (<, > or
5231 /// !=).
5232 bool IsStrictCompare = false;
5233 /// Condition of the loop.
5234 Expr *PreCond = nullptr;
5235 /// This expression calculates the number of iterations in the loop.
5236 /// It is always possible to calculate it before starting the loop.
5237 Expr *NumIterations = nullptr;
5238 /// The loop counter variable.
5239 Expr *CounterVar = nullptr;
5240 /// Private loop counter variable.
5241 Expr *PrivateCounterVar = nullptr;
5242 /// This is initializer for the initial value of #CounterVar.
5243 Expr *CounterInit = nullptr;
5244 /// This is step for the #CounterVar used to generate its update:
5245 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5246 Expr *CounterStep = nullptr;
5247 /// Should step be subtracted?
5248 bool Subtract = false;
5249 /// Source range of the loop init.
5250 SourceRange InitSrcRange;
5251 /// Source range of the loop condition.
5252 SourceRange CondSrcRange;
5253 /// Source range of the loop increment.
5254 SourceRange IncSrcRange;
5255 /// Minimum value that can have the loop control variable. Used to support
5256 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5257 /// since only such variables can be used in non-loop invariant expressions.
5258 Expr *MinValue = nullptr;
5259 /// Maximum value that can have the loop control variable. Used to support
5260 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5261 /// since only such variables can be used in non-loop invariant expressions.
5262 Expr *MaxValue = nullptr;
5263 /// true, if the lower bound depends on the outer loop control var.
5264 bool IsNonRectangularLB = false;
5265 /// true, if the upper bound depends on the outer loop control var.
5266 bool IsNonRectangularUB = false;
5267 /// Index of the loop this loop depends on and forms non-rectangular loop
5268 /// nest.
5269 unsigned LoopDependentIdx = 0;
5270 /// Final condition for the non-rectangular loop nest support. It is used to
5271 /// check that the number of iterations for this particular counter must be
5272 /// finished.
5273 Expr *FinalCondition = nullptr;
5274};
5275
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005276/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005277/// extracting iteration space of each loop in the loop nest, that will be used
5278/// for IR generation.
5279class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005280 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005281 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005282 /// Data-sharing stack.
5283 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005284 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005285 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005286 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005287 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005288 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005289 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005290 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005291 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005292 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005293 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005294 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005295 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005296 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005297 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005298 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005299 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005300 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005301 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005302 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005303 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005304 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005305 /// Var < UB
5306 /// Var <= UB
5307 /// UB > Var
5308 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005309 /// This will have no value when the condition is !=
5310 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005311 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005312 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005313 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005314 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005315 /// The outer loop counter this loop depends on (if any).
5316 const ValueDecl *DepDecl = nullptr;
5317 /// Contains number of loop (starts from 1) on which loop counter init
5318 /// expression of this loop depends on.
5319 Optional<unsigned> InitDependOnLC;
5320 /// Contains number of loop (starts from 1) on which loop counter condition
5321 /// expression of this loop depends on.
5322 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005323 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005324 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005325 /// Original condition required for checking of the exit condition for
5326 /// non-rectangular loop.
5327 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005328
5329public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005330 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5331 SourceLocation DefaultLoc)
5332 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5333 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005334 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005335 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005336 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005337 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005338 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005339 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005340 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005341 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005342 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005343 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005344 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005345 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005346 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005347 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005348 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005349 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005350 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005351 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005352 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005353 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005354 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005355 /// True, if the compare operator is strict (<, > or !=).
5356 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005357 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005358 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005359 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005360 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005361 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005362 Expr *
5363 buildPreCond(Scope *S, Expr *Cond,
5364 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005365 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005366 DeclRefExpr *
5367 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5368 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005369 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005370 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005371 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005372 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005373 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005374 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005375 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005376 /// Build loop data with counter value for depend clauses in ordered
5377 /// directives.
5378 Expr *
5379 buildOrderedLoopData(Scope *S, Expr *Counter,
5380 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5381 SourceLocation Loc, Expr *Inc = nullptr,
5382 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005383 /// Builds the minimum value for the loop counter.
5384 std::pair<Expr *, Expr *> buildMinMaxValues(
5385 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5386 /// Builds final condition for the non-rectangular loops.
5387 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005388 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005389 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005390 /// Returns true if the initializer forms non-rectangular loop.
5391 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5392 /// Returns true if the condition forms non-rectangular loop.
5393 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5394 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5395 unsigned getLoopDependentIdx() const {
5396 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5397 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005398
5399private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005400 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005401 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005402 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005403 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005404 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5405 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005406 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005407 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5408 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005409 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005410 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005411};
5412
Alexey Bataeve3727102018-04-18 15:57:46 +00005413bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005414 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005415 assert(!LB && !UB && !Step);
5416 return false;
5417 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005418 return LCDecl->getType()->isDependentType() ||
5419 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5420 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005421}
5422
Alexey Bataeve3727102018-04-18 15:57:46 +00005423bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005424 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005425 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005426 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005427 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005428 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005429 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005430 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005431 LCDecl = getCanonicalDecl(NewLCDecl);
5432 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005433 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5434 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005435 if ((Ctor->isCopyOrMoveConstructor() ||
5436 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5437 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005438 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005439 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005440 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005441 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005442 return false;
5443}
5444
Alexey Bataev316ccf62019-01-29 18:51:58 +00005445bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5446 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005447 bool StrictOp, SourceRange SR,
5448 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005449 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005450 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5451 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005452 if (!NewUB)
5453 return true;
5454 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005455 if (LessOp)
5456 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005457 TestIsStrictOp = StrictOp;
5458 ConditionSrcRange = SR;
5459 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005460 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005461 return false;
5462}
5463
Alexey Bataeve3727102018-04-18 15:57:46 +00005464bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005465 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005466 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005467 if (!NewStep)
5468 return true;
5469 if (!NewStep->isValueDependent()) {
5470 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005471 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005472 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5473 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005474 if (Val.isInvalid())
5475 return true;
5476 NewStep = Val.get();
5477
5478 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5479 // If test-expr is of form var relational-op b and relational-op is < or
5480 // <= then incr-expr must cause var to increase on each iteration of the
5481 // loop. If test-expr is of form var relational-op b and relational-op is
5482 // > or >= then incr-expr must cause var to decrease on each iteration of
5483 // the loop.
5484 // If test-expr is of form b relational-op var and relational-op is < or
5485 // <= then incr-expr must cause var to decrease on each iteration of the
5486 // loop. If test-expr is of form b relational-op var and relational-op is
5487 // > or >= then incr-expr must cause var to increase on each iteration of
5488 // the loop.
5489 llvm::APSInt Result;
5490 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5491 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5492 bool IsConstNeg =
5493 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005494 bool IsConstPos =
5495 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005496 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005497
5498 // != with increment is treated as <; != with decrement is treated as >
5499 if (!TestIsLessOp.hasValue())
5500 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005501 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005502 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005503 (IsConstNeg || (IsUnsigned && Subtract)) :
5504 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005505 SemaRef.Diag(NewStep->getExprLoc(),
5506 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005507 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005508 SemaRef.Diag(ConditionLoc,
5509 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005510 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005511 return true;
5512 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005513 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005514 NewStep =
5515 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5516 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005517 Subtract = !Subtract;
5518 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005519 }
5520
5521 Step = NewStep;
5522 SubtractStep = Subtract;
5523 return false;
5524}
5525
Alexey Bataev622af1d2019-04-24 19:58:30 +00005526namespace {
5527/// Checker for the non-rectangular loops. Checks if the initializer or
5528/// condition expression references loop counter variable.
5529class LoopCounterRefChecker final
5530 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5531 Sema &SemaRef;
5532 DSAStackTy &Stack;
5533 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005534 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005535 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005536 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005537 unsigned BaseLoopId = 0;
5538 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5539 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5540 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5541 << (IsInitializer ? 0 : 1);
5542 return false;
5543 }
5544 const auto &&Data = Stack.isLoopControlVariable(VD);
5545 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5546 // The type of the loop iterator on which we depend may not have a random
5547 // access iterator type.
5548 if (Data.first && VD->getType()->isRecordType()) {
5549 SmallString<128> Name;
5550 llvm::raw_svector_ostream OS(Name);
5551 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5552 /*Qualified=*/true);
5553 SemaRef.Diag(E->getExprLoc(),
5554 diag::err_omp_wrong_dependency_iterator_type)
5555 << OS.str();
5556 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5557 return false;
5558 }
5559 if (Data.first &&
5560 (DepDecl || (PrevDepDecl &&
5561 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5562 if (!DepDecl && PrevDepDecl)
5563 DepDecl = PrevDepDecl;
5564 SmallString<128> Name;
5565 llvm::raw_svector_ostream OS(Name);
5566 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5567 /*Qualified=*/true);
5568 SemaRef.Diag(E->getExprLoc(),
5569 diag::err_omp_invariant_or_linear_dependency)
5570 << OS.str();
5571 return false;
5572 }
5573 if (Data.first) {
5574 DepDecl = VD;
5575 BaseLoopId = Data.first;
5576 }
5577 return Data.first;
5578 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005579
5580public:
5581 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5582 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005583 if (isa<VarDecl>(VD))
5584 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005585 return false;
5586 }
5587 bool VisitMemberExpr(const MemberExpr *E) {
5588 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5589 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005590 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5591 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005592 }
5593 return false;
5594 }
5595 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005596 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005597 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005598 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005599 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005600 }
5601 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005602 const ValueDecl *CurLCDecl, bool IsInitializer,
5603 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005604 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005605 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5606 unsigned getBaseLoopId() const {
5607 assert(CurLCDecl && "Expected loop dependency.");
5608 return BaseLoopId;
5609 }
5610 const ValueDecl *getDepDecl() const {
5611 assert(CurLCDecl && "Expected loop dependency.");
5612 return DepDecl;
5613 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005614};
5615} // namespace
5616
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005617Optional<unsigned>
5618OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5619 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005620 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005621 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5622 DepDecl);
5623 if (LoopStmtChecker.Visit(S)) {
5624 DepDecl = LoopStmtChecker.getDepDecl();
5625 return LoopStmtChecker.getBaseLoopId();
5626 }
5627 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005628}
5629
Alexey Bataeve3727102018-04-18 15:57:46 +00005630bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005631 // Check init-expr for canonical loop form and save loop counter
5632 // variable - #Var and its initialization value - #LB.
5633 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5634 // var = lb
5635 // integer-type var = lb
5636 // random-access-iterator-type var = lb
5637 // pointer-type var = lb
5638 //
5639 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005640 if (EmitDiags) {
5641 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5642 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005643 return true;
5644 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005645 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5646 if (!ExprTemp->cleanupsHaveSideEffects())
5647 S = ExprTemp->getSubExpr();
5648
Alexander Musmana5f070a2014-10-01 06:03:56 +00005649 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005650 if (Expr *E = dyn_cast<Expr>(S))
5651 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005652 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005653 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005654 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005655 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5656 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5657 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005658 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5659 EmitDiags);
5660 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005661 }
5662 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5663 if (ME->isArrow() &&
5664 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005665 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5666 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005667 }
5668 }
David Majnemer9d168222016-08-05 17:44:54 +00005669 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005670 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005671 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005672 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005673 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005674 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005675 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005676 diag::ext_omp_loop_not_canonical_init)
5677 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005678 return setLCDeclAndLB(
5679 Var,
5680 buildDeclRefExpr(SemaRef, Var,
5681 Var->getType().getNonReferenceType(),
5682 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005683 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005684 }
5685 }
5686 }
David Majnemer9d168222016-08-05 17:44:54 +00005687 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005688 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005689 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005690 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005691 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5692 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005693 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5694 EmitDiags);
5695 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005696 }
5697 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5698 if (ME->isArrow() &&
5699 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005700 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5701 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005702 }
5703 }
5704 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005705
Alexey Bataeve3727102018-04-18 15:57:46 +00005706 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005707 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005708 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005709 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005710 << S->getSourceRange();
5711 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005712 return true;
5713}
5714
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005715/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005716/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005717static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005718 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005719 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005720 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005721 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005722 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005723 if ((Ctor->isCopyOrMoveConstructor() ||
5724 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5725 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005726 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005727 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5728 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005729 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005730 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005731 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005732 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5733 return getCanonicalDecl(ME->getMemberDecl());
5734 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005735}
5736
Alexey Bataeve3727102018-04-18 15:57:46 +00005737bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005738 // Check test-expr for canonical form, save upper-bound UB, flags for
5739 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005740 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005741 // var relational-op b
5742 // b relational-op var
5743 //
Alexey Bataev1be63402019-09-11 15:44:06 +00005744 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005745 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00005746 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
5747 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005748 return true;
5749 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00005750 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005751 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005752 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005753 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005754 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005755 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5756 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005757 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5758 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5759 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005760 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5761 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005762 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5763 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5764 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00005765 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
5766 return setUB(
5767 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
5768 /*LessOp=*/llvm::None,
5769 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005770 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005771 if (CE->getNumArgs() == 2) {
5772 auto Op = CE->getOperator();
5773 switch (Op) {
5774 case OO_Greater:
5775 case OO_GreaterEqual:
5776 case OO_Less:
5777 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005778 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5779 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005780 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5781 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005782 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5783 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005784 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5785 CE->getOperatorLoc());
5786 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005787 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00005788 if (IneqCondIsCanonical)
5789 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
5790 : CE->getArg(0),
5791 /*LessOp=*/llvm::None,
5792 /*StrictOp=*/true, CE->getSourceRange(),
5793 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005794 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005795 default:
5796 break;
5797 }
5798 }
5799 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005800 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005801 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005802 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00005803 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005804 return true;
5805}
5806
Alexey Bataeve3727102018-04-18 15:57:46 +00005807bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005808 // RHS of canonical loop form increment can be:
5809 // var + incr
5810 // incr + var
5811 // var - incr
5812 //
5813 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005814 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005815 if (BO->isAdditiveOp()) {
5816 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005817 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5818 return setStep(BO->getRHS(), !IsAdd);
5819 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5820 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005821 }
David Majnemer9d168222016-08-05 17:44:54 +00005822 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005823 bool IsAdd = CE->getOperator() == OO_Plus;
5824 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005825 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5826 return setStep(CE->getArg(1), !IsAdd);
5827 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5828 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005829 }
5830 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005831 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005832 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005833 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005834 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005835 return true;
5836}
5837
Alexey Bataeve3727102018-04-18 15:57:46 +00005838bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005839 // Check incr-expr for canonical loop form and return true if it
5840 // does not conform.
5841 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5842 // ++var
5843 // var++
5844 // --var
5845 // var--
5846 // var += incr
5847 // var -= incr
5848 // var = var + incr
5849 // var = incr + var
5850 // var = var - incr
5851 //
5852 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005853 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005854 return true;
5855 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005856 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5857 if (!ExprTemp->cleanupsHaveSideEffects())
5858 S = ExprTemp->getSubExpr();
5859
Alexander Musmana5f070a2014-10-01 06:03:56 +00005860 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005861 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005862 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005863 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005864 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5865 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005866 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005867 (UO->isDecrementOp() ? -1 : 1))
5868 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005869 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005870 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005871 switch (BO->getOpcode()) {
5872 case BO_AddAssign:
5873 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005874 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5875 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005876 break;
5877 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005878 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5879 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005880 break;
5881 default:
5882 break;
5883 }
David Majnemer9d168222016-08-05 17:44:54 +00005884 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005885 switch (CE->getOperator()) {
5886 case OO_PlusPlus:
5887 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005888 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5889 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005890 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005891 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005892 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5893 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005894 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005895 break;
5896 case OO_PlusEqual:
5897 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005898 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5899 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005900 break;
5901 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005902 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5903 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005904 break;
5905 default:
5906 break;
5907 }
5908 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005909 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005910 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005911 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005912 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005913 return true;
5914}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005915
Alexey Bataev5a3af132016-03-29 08:58:54 +00005916static ExprResult
5917tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005918 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005919 if (SemaRef.CurContext->isDependentContext())
5920 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005921 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5922 return SemaRef.PerformImplicitConversion(
5923 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5924 /*AllowExplicit=*/true);
5925 auto I = Captures.find(Capture);
5926 if (I != Captures.end())
5927 return buildCapture(SemaRef, Capture, I->second);
5928 DeclRefExpr *Ref = nullptr;
5929 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5930 Captures[Capture] = Ref;
5931 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005932}
5933
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005934/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005935Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005936 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005937 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005938 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005939 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005940 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005941 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005942 Expr *LBVal = LB;
5943 Expr *UBVal = UB;
5944 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
5945 // max(LB(MinVal), LB(MaxVal))
5946 if (InitDependOnLC) {
5947 const LoopIterationSpace &IS =
5948 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5949 InitDependOnLC.getValueOr(
5950 CondDependOnLC.getValueOr(0))];
5951 if (!IS.MinValue || !IS.MaxValue)
5952 return nullptr;
5953 // OuterVar = Min
5954 ExprResult MinValue =
5955 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5956 if (!MinValue.isUsable())
5957 return nullptr;
5958
5959 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5960 IS.CounterVar, MinValue.get());
5961 if (!LBMinVal.isUsable())
5962 return nullptr;
5963 // OuterVar = Min, LBVal
5964 LBMinVal =
5965 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
5966 if (!LBMinVal.isUsable())
5967 return nullptr;
5968 // (OuterVar = Min, LBVal)
5969 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
5970 if (!LBMinVal.isUsable())
5971 return nullptr;
5972
5973 // OuterVar = Max
5974 ExprResult MaxValue =
5975 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5976 if (!MaxValue.isUsable())
5977 return nullptr;
5978
5979 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5980 IS.CounterVar, MaxValue.get());
5981 if (!LBMaxVal.isUsable())
5982 return nullptr;
5983 // OuterVar = Max, LBVal
5984 LBMaxVal =
5985 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
5986 if (!LBMaxVal.isUsable())
5987 return nullptr;
5988 // (OuterVar = Max, LBVal)
5989 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
5990 if (!LBMaxVal.isUsable())
5991 return nullptr;
5992
5993 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
5994 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
5995 if (!LBMin || !LBMax)
5996 return nullptr;
5997 // LB(MinVal) < LB(MaxVal)
5998 ExprResult MinLessMaxRes =
5999 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6000 if (!MinLessMaxRes.isUsable())
6001 return nullptr;
6002 Expr *MinLessMax =
6003 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6004 if (!MinLessMax)
6005 return nullptr;
6006 if (TestIsLessOp.getValue()) {
6007 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6008 // LB(MaxVal))
6009 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6010 MinLessMax, LBMin, LBMax);
6011 if (!MinLB.isUsable())
6012 return nullptr;
6013 LBVal = MinLB.get();
6014 } else {
6015 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6016 // LB(MaxVal))
6017 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6018 MinLessMax, LBMax, LBMin);
6019 if (!MaxLB.isUsable())
6020 return nullptr;
6021 LBVal = MaxLB.get();
6022 }
6023 }
6024 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6025 // min(UB(MinVal), UB(MaxVal))
6026 if (CondDependOnLC) {
6027 const LoopIterationSpace &IS =
6028 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6029 InitDependOnLC.getValueOr(
6030 CondDependOnLC.getValueOr(0))];
6031 if (!IS.MinValue || !IS.MaxValue)
6032 return nullptr;
6033 // OuterVar = Min
6034 ExprResult MinValue =
6035 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6036 if (!MinValue.isUsable())
6037 return nullptr;
6038
6039 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6040 IS.CounterVar, MinValue.get());
6041 if (!UBMinVal.isUsable())
6042 return nullptr;
6043 // OuterVar = Min, UBVal
6044 UBMinVal =
6045 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6046 if (!UBMinVal.isUsable())
6047 return nullptr;
6048 // (OuterVar = Min, UBVal)
6049 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6050 if (!UBMinVal.isUsable())
6051 return nullptr;
6052
6053 // OuterVar = Max
6054 ExprResult MaxValue =
6055 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6056 if (!MaxValue.isUsable())
6057 return nullptr;
6058
6059 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6060 IS.CounterVar, MaxValue.get());
6061 if (!UBMaxVal.isUsable())
6062 return nullptr;
6063 // OuterVar = Max, UBVal
6064 UBMaxVal =
6065 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6066 if (!UBMaxVal.isUsable())
6067 return nullptr;
6068 // (OuterVar = Max, UBVal)
6069 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6070 if (!UBMaxVal.isUsable())
6071 return nullptr;
6072
6073 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6074 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6075 if (!UBMin || !UBMax)
6076 return nullptr;
6077 // UB(MinVal) > UB(MaxVal)
6078 ExprResult MinGreaterMaxRes =
6079 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6080 if (!MinGreaterMaxRes.isUsable())
6081 return nullptr;
6082 Expr *MinGreaterMax =
6083 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6084 if (!MinGreaterMax)
6085 return nullptr;
6086 if (TestIsLessOp.getValue()) {
6087 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6088 // UB(MaxVal))
6089 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6090 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6091 if (!MaxUB.isUsable())
6092 return nullptr;
6093 UBVal = MaxUB.get();
6094 } else {
6095 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6096 // UB(MaxVal))
6097 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6098 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6099 if (!MinUB.isUsable())
6100 return nullptr;
6101 UBVal = MinUB.get();
6102 }
6103 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006104 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006105 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6106 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006107 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6108 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006109 if (!Upper || !Lower)
6110 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006111
6112 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6113
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006114 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006115 // BuildBinOp already emitted error, this one is to point user to upper
6116 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006117 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006118 << Upper->getSourceRange() << Lower->getSourceRange();
6119 return nullptr;
6120 }
6121 }
6122
6123 if (!Diff.isUsable())
6124 return nullptr;
6125
6126 // Upper - Lower [- 1]
6127 if (TestIsStrictOp)
6128 Diff = SemaRef.BuildBinOp(
6129 S, DefaultLoc, BO_Sub, Diff.get(),
6130 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6131 if (!Diff.isUsable())
6132 return nullptr;
6133
6134 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006135 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006136 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006137 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006138 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006139 if (!Diff.isUsable())
6140 return nullptr;
6141
6142 // Parentheses (for dumping/debugging purposes only).
6143 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6144 if (!Diff.isUsable())
6145 return nullptr;
6146
6147 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006148 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006149 if (!Diff.isUsable())
6150 return nullptr;
6151
Alexander Musman174b3ca2014-10-06 11:16:29 +00006152 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006153 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006154 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006155 bool UseVarType = VarType->hasIntegerRepresentation() &&
6156 C.getTypeSize(Type) > C.getTypeSize(VarType);
6157 if (!Type->isIntegerType() || UseVarType) {
6158 unsigned NewSize =
6159 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6160 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6161 : Type->hasSignedIntegerRepresentation();
6162 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006163 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6164 Diff = SemaRef.PerformImplicitConversion(
6165 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6166 if (!Diff.isUsable())
6167 return nullptr;
6168 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006169 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006170 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006171 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6172 if (NewSize != C.getTypeSize(Type)) {
6173 if (NewSize < C.getTypeSize(Type)) {
6174 assert(NewSize == 64 && "incorrect loop var size");
6175 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6176 << InitSrcRange << ConditionSrcRange;
6177 }
6178 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006179 NewSize, Type->hasSignedIntegerRepresentation() ||
6180 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006181 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6182 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6183 Sema::AA_Converting, true);
6184 if (!Diff.isUsable())
6185 return nullptr;
6186 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006187 }
6188 }
6189
Alexander Musmana5f070a2014-10-01 06:03:56 +00006190 return Diff.get();
6191}
6192
Alexey Bataevf8be4762019-08-14 19:30:06 +00006193std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6194 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6195 // Do not build for iterators, they cannot be used in non-rectangular loop
6196 // nests.
6197 if (LCDecl->getType()->isRecordType())
6198 return std::make_pair(nullptr, nullptr);
6199 // If we subtract, the min is in the condition, otherwise the min is in the
6200 // init value.
6201 Expr *MinExpr = nullptr;
6202 Expr *MaxExpr = nullptr;
6203 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6204 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6205 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6206 : CondDependOnLC.hasValue();
6207 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6208 : InitDependOnLC.hasValue();
6209 Expr *Lower =
6210 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6211 Expr *Upper =
6212 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6213 if (!Upper || !Lower)
6214 return std::make_pair(nullptr, nullptr);
6215
6216 if (TestIsLessOp.getValue())
6217 MinExpr = Lower;
6218 else
6219 MaxExpr = Upper;
6220
6221 // Build minimum/maximum value based on number of iterations.
6222 ExprResult Diff;
6223 QualType VarType = LCDecl->getType().getNonReferenceType();
6224
6225 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6226 if (!Diff.isUsable())
6227 return std::make_pair(nullptr, nullptr);
6228
6229 // Upper - Lower [- 1]
6230 if (TestIsStrictOp)
6231 Diff = SemaRef.BuildBinOp(
6232 S, DefaultLoc, BO_Sub, Diff.get(),
6233 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6234 if (!Diff.isUsable())
6235 return std::make_pair(nullptr, nullptr);
6236
6237 // Upper - Lower [- 1] + Step
6238 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6239 if (!NewStep.isUsable())
6240 return std::make_pair(nullptr, nullptr);
6241
6242 // Parentheses (for dumping/debugging purposes only).
6243 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6244 if (!Diff.isUsable())
6245 return std::make_pair(nullptr, nullptr);
6246
6247 // (Upper - Lower [- 1]) / Step
6248 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6249 if (!Diff.isUsable())
6250 return std::make_pair(nullptr, nullptr);
6251
6252 // ((Upper - Lower [- 1]) / Step) * Step
6253 // Parentheses (for dumping/debugging purposes only).
6254 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6255 if (!Diff.isUsable())
6256 return std::make_pair(nullptr, nullptr);
6257
6258 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6259 if (!Diff.isUsable())
6260 return std::make_pair(nullptr, nullptr);
6261
6262 // Convert to the original type or ptrdiff_t, if original type is pointer.
6263 if (!VarType->isAnyPointerType() &&
6264 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6265 Diff = SemaRef.PerformImplicitConversion(
6266 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6267 } else if (VarType->isAnyPointerType() &&
6268 !SemaRef.Context.hasSameType(
6269 Diff.get()->getType(),
6270 SemaRef.Context.getUnsignedPointerDiffType())) {
6271 Diff = SemaRef.PerformImplicitConversion(
6272 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6273 Sema::AA_Converting, /*AllowExplicit=*/true);
6274 }
6275 if (!Diff.isUsable())
6276 return std::make_pair(nullptr, nullptr);
6277
6278 // Parentheses (for dumping/debugging purposes only).
6279 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6280 if (!Diff.isUsable())
6281 return std::make_pair(nullptr, nullptr);
6282
6283 if (TestIsLessOp.getValue()) {
6284 // MinExpr = Lower;
6285 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6286 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6287 if (!Diff.isUsable())
6288 return std::make_pair(nullptr, nullptr);
6289 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6290 if (!Diff.isUsable())
6291 return std::make_pair(nullptr, nullptr);
6292 MaxExpr = Diff.get();
6293 } else {
6294 // MaxExpr = Upper;
6295 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6296 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6297 if (!Diff.isUsable())
6298 return std::make_pair(nullptr, nullptr);
6299 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6300 if (!Diff.isUsable())
6301 return std::make_pair(nullptr, nullptr);
6302 MinExpr = Diff.get();
6303 }
6304
6305 return std::make_pair(MinExpr, MaxExpr);
6306}
6307
6308Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6309 if (InitDependOnLC || CondDependOnLC)
6310 return Condition;
6311 return nullptr;
6312}
6313
Alexey Bataeve3727102018-04-18 15:57:46 +00006314Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006315 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006316 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006317 // Do not build a precondition when the condition/initialization is dependent
6318 // to prevent pessimistic early loop exit.
6319 // TODO: this can be improved by calculating min/max values but not sure that
6320 // it will be very effective.
6321 if (CondDependOnLC || InitDependOnLC)
6322 return SemaRef.PerformImplicitConversion(
6323 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6324 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6325 /*AllowExplicit=*/true).get();
6326
Alexey Bataev62dbb972015-04-22 11:59:37 +00006327 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006328 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006329
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006330 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6331 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006332 if (!NewLB.isUsable() || !NewUB.isUsable())
6333 return nullptr;
6334
Alexey Bataeve3727102018-04-18 15:57:46 +00006335 ExprResult CondExpr =
6336 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006337 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006338 (TestIsStrictOp ? BO_LT : BO_LE) :
6339 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006340 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006341 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006342 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6343 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006344 CondExpr = SemaRef.PerformImplicitConversion(
6345 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6346 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006347 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006348
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006349 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006350 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6351}
6352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006353/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006354DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006355 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6356 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006357 auto *VD = dyn_cast<VarDecl>(LCDecl);
6358 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006359 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6360 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006361 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006362 const DSAStackTy::DSAVarData Data =
6363 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006364 // If the loop control decl is explicitly marked as private, do not mark it
6365 // as captured again.
6366 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6367 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006368 return Ref;
6369 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006370 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006371}
6372
Alexey Bataeve3727102018-04-18 15:57:46 +00006373Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006374 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006375 QualType Type = LCDecl->getType().getNonReferenceType();
6376 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006377 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6378 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6379 isa<VarDecl>(LCDecl)
6380 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6381 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006382 if (PrivateVar->isInvalidDecl())
6383 return nullptr;
6384 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6385 }
6386 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006387}
6388
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006389/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006390Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006391
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006392/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006393Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006394
Alexey Bataevf138fda2018-08-13 19:04:24 +00006395Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6396 Scope *S, Expr *Counter,
6397 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6398 Expr *Inc, OverloadedOperatorKind OOK) {
6399 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6400 if (!Cnt)
6401 return nullptr;
6402 if (Inc) {
6403 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6404 "Expected only + or - operations for depend clauses.");
6405 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6406 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6407 if (!Cnt)
6408 return nullptr;
6409 }
6410 ExprResult Diff;
6411 QualType VarType = LCDecl->getType().getNonReferenceType();
6412 if (VarType->isIntegerType() || VarType->isPointerType() ||
6413 SemaRef.getLangOpts().CPlusPlus) {
6414 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006415 Expr *Upper = TestIsLessOp.getValue()
6416 ? Cnt
6417 : tryBuildCapture(SemaRef, UB, Captures).get();
6418 Expr *Lower = TestIsLessOp.getValue()
6419 ? tryBuildCapture(SemaRef, LB, Captures).get()
6420 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006421 if (!Upper || !Lower)
6422 return nullptr;
6423
6424 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6425
6426 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6427 // BuildBinOp already emitted error, this one is to point user to upper
6428 // and lower bound, and to tell what is passed to 'operator-'.
6429 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6430 << Upper->getSourceRange() << Lower->getSourceRange();
6431 return nullptr;
6432 }
6433 }
6434
6435 if (!Diff.isUsable())
6436 return nullptr;
6437
6438 // Parentheses (for dumping/debugging purposes only).
6439 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6440 if (!Diff.isUsable())
6441 return nullptr;
6442
6443 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6444 if (!NewStep.isUsable())
6445 return nullptr;
6446 // (Upper - Lower) / Step
6447 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6448 if (!Diff.isUsable())
6449 return nullptr;
6450
6451 return Diff.get();
6452}
Alexey Bataev23b69422014-06-18 07:08:49 +00006453} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006454
Alexey Bataev9c821032015-04-30 04:23:23 +00006455void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6456 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6457 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006458 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6459 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006460 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006461 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006462 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006463 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6464 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006465 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006466 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006467 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006468 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006469 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006470 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006471 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6472 /*WithInit=*/false);
6473 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006474 }
6475 }
6476 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006477 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6478 if (LD != D->getCanonicalDecl()) {
6479 DSAStack->resetPossibleLoopCounter();
6480 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6481 MarkDeclarationsReferencedInExpr(
6482 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6483 Var->getType().getNonLValueExprType(Context),
6484 ForLoc, /*RefersToCapture=*/true));
6485 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006486 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6487 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6488 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6489 // associated for-loop of a simd construct with just one associated
6490 // for-loop may be listed in a linear clause with a constant-linear-step
6491 // that is the increment of the associated for-loop. The loop iteration
6492 // variable(s) in the associated for-loop(s) of a for or parallel for
6493 // construct may be listed in a private or lastprivate clause.
6494 DSAStackTy::DSAVarData DVar =
6495 DSAStack->getTopDSA(D, /*FromParent=*/false);
6496 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6497 // is declared in the loop and it is predetermined as a private.
6498 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6499 OpenMPClauseKind PredeterminedCKind =
6500 isOpenMPSimdDirective(DKind)
6501 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6502 : OMPC_private;
6503 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6504 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6505 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6506 DVar.CKind != OMPC_private))) ||
6507 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006508 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006509 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006510 isOpenMPDistributeDirective(DKind)) &&
6511 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6512 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6513 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6514 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6515 << getOpenMPClauseName(DVar.CKind)
6516 << getOpenMPDirectiveName(DKind)
6517 << getOpenMPClauseName(PredeterminedCKind);
6518 if (DVar.RefExpr == nullptr)
6519 DVar.CKind = PredeterminedCKind;
6520 reportOriginalDsa(*this, DSAStack, D, DVar,
6521 /*IsLoopIterVar=*/true);
6522 } else if (LoopDeclRefExpr) {
6523 // Make the loop iteration variable private (for worksharing
6524 // constructs), linear (for simd directives with the only one
6525 // associated loop) or lastprivate (for simd directives with several
6526 // collapsed or ordered loops).
6527 if (DVar.CKind == OMPC_unknown)
6528 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6529 PrivateRef);
6530 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006531 }
6532 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006533 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006534 }
6535}
6536
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006537/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006538/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006539static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006540 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6541 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006542 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6543 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006544 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006545 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006546 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006547 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006548 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006549 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006550 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006551 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6552 // Ranged for is supported only in OpenMP 5.0.
6553 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006554 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006555 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006556 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006557 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006558 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006559 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6560 SemaRef.Diag(DSA.getConstructLoc(),
6561 diag::note_omp_collapse_ordered_expr)
6562 << 2 << CollapseLoopCountExpr->getSourceRange()
6563 << OrderedLoopCountExpr->getSourceRange();
6564 else if (CollapseLoopCountExpr)
6565 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6566 diag::note_omp_collapse_ordered_expr)
6567 << 0 << CollapseLoopCountExpr->getSourceRange();
6568 else
6569 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6570 diag::note_omp_collapse_ordered_expr)
6571 << 1 << OrderedLoopCountExpr->getSourceRange();
6572 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006573 return true;
6574 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006575 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6576 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006577
Alexey Bataevbef93a92019-10-07 18:54:57 +00006578 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6579 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006580
6581 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006582 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006583 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006584 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006585
6586 bool HasErrors = false;
6587
6588 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006589 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006590 // OpenMP [2.6, Canonical Loop Form]
6591 // Var is one of the following:
6592 // A variable of signed or unsigned integer type.
6593 // For C++, a variable of a random access iterator type.
6594 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006595 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006596 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6597 !VarType->isPointerType() &&
6598 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006599 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006600 << SemaRef.getLangOpts().CPlusPlus;
6601 HasErrors = true;
6602 }
6603
6604 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6605 // a Construct
6606 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6607 // parallel for construct is (are) private.
6608 // The loop iteration variable in the associated for-loop of a simd
6609 // construct with just one associated for-loop is linear with a
6610 // constant-linear-step that is the increment of the associated for-loop.
6611 // Exclude loop var from the list of variables with implicitly defined data
6612 // sharing attributes.
6613 VarsWithImplicitDSA.erase(LCDecl);
6614
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006615 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6616
6617 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006618 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006619
6620 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006621 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006622 }
6623
Alexey Bataeve3727102018-04-18 15:57:46 +00006624 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006625 return HasErrors;
6626
Alexander Musmana5f070a2014-10-01 06:03:56 +00006627 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006628 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6629 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006630 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6631 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6632 (isOpenMPWorksharingDirective(DKind) ||
6633 isOpenMPTaskLoopDirective(DKind) ||
6634 isOpenMPDistributeDirective(DKind)),
6635 Captures);
6636 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6637 ISC.buildCounterVar(Captures, DSA);
6638 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6639 ISC.buildPrivateCounterVar();
6640 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6641 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6642 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6643 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6644 ISC.getConditionSrcRange();
6645 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6646 ISC.getIncrementSrcRange();
6647 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6648 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6649 ISC.isStrictTestOp();
6650 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6651 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6652 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6653 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6654 ISC.buildFinalCondition(DSA.getCurScope());
6655 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6656 ISC.doesInitDependOnLC();
6657 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6658 ISC.doesCondDependOnLC();
6659 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6660 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006661
Alexey Bataevf8be4762019-08-14 19:30:06 +00006662 HasErrors |=
6663 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6664 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6665 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6666 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6667 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6668 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006669 if (!HasErrors && DSA.isOrderedRegion()) {
6670 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6671 if (CurrentNestedLoopCount <
6672 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6673 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006674 CurrentNestedLoopCount,
6675 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006676 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006677 CurrentNestedLoopCount,
6678 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006679 }
6680 }
6681 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6682 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6683 // Erroneous case - clause has some problems.
6684 continue;
6685 }
6686 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6687 Pair.second.size() <= CurrentNestedLoopCount) {
6688 // Erroneous case - clause has some problems.
6689 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6690 continue;
6691 }
6692 Expr *CntValue;
6693 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6694 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006695 DSA.getCurScope(),
6696 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006697 Pair.first->getDependencyLoc());
6698 else
6699 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006700 DSA.getCurScope(),
6701 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006702 Pair.first->getDependencyLoc(),
6703 Pair.second[CurrentNestedLoopCount].first,
6704 Pair.second[CurrentNestedLoopCount].second);
6705 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6706 }
6707 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006708
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006709 return HasErrors;
6710}
6711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006712/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006713static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006714buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006715 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006716 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006717 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006718 ExprResult NewStart = IsNonRectangularLB
6719 ? Start.get()
6720 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006721 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006722 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006723 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006724 VarRef.get()->getType())) {
6725 NewStart = SemaRef.PerformImplicitConversion(
6726 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6727 /*AllowExplicit=*/true);
6728 if (!NewStart.isUsable())
6729 return ExprError();
6730 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006731
Alexey Bataeve3727102018-04-18 15:57:46 +00006732 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006733 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6734 return Init;
6735}
6736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006737/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006738static ExprResult buildCounterUpdate(
6739 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6740 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006741 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006742 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006743 // Add parentheses (for debugging purposes only).
6744 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
6745 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
6746 !Step.isUsable())
6747 return ExprError();
6748
Alexey Bataev5a3af132016-03-29 08:58:54 +00006749 ExprResult NewStep = Step;
6750 if (Captures)
6751 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006752 if (NewStep.isInvalid())
6753 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006754 ExprResult Update =
6755 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006756 if (!Update.isUsable())
6757 return ExprError();
6758
Alexey Bataevc0214e02016-02-16 12:13:49 +00006759 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
6760 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006761 if (!Start.isUsable())
6762 return ExprError();
6763 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
6764 if (!NewStart.isUsable())
6765 return ExprError();
6766 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006767 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006768 if (NewStart.isInvalid())
6769 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006770
Alexey Bataevc0214e02016-02-16 12:13:49 +00006771 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
6772 ExprResult SavedUpdate = Update;
6773 ExprResult UpdateVal;
6774 if (VarRef.get()->getType()->isOverloadableType() ||
6775 NewStart.get()->getType()->isOverloadableType() ||
6776 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006777 Sema::TentativeAnalysisScope Trap(SemaRef);
6778
Alexey Bataevc0214e02016-02-16 12:13:49 +00006779 Update =
6780 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6781 if (Update.isUsable()) {
6782 UpdateVal =
6783 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
6784 VarRef.get(), SavedUpdate.get());
6785 if (UpdateVal.isUsable()) {
6786 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
6787 UpdateVal.get());
6788 }
6789 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006790 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006791
Alexey Bataevc0214e02016-02-16 12:13:49 +00006792 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
6793 if (!Update.isUsable() || !UpdateVal.isUsable()) {
6794 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
6795 NewStart.get(), SavedUpdate.get());
6796 if (!Update.isUsable())
6797 return ExprError();
6798
Alexey Bataev11481f52016-02-17 10:29:05 +00006799 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
6800 VarRef.get()->getType())) {
6801 Update = SemaRef.PerformImplicitConversion(
6802 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
6803 if (!Update.isUsable())
6804 return ExprError();
6805 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006806
6807 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
6808 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006809 return Update;
6810}
6811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006812/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006813/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006814static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006815 if (E == nullptr)
6816 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006817 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006818 QualType OldType = E->getType();
6819 unsigned HasBits = C.getTypeSize(OldType);
6820 if (HasBits >= Bits)
6821 return ExprResult(E);
6822 // OK to convert to signed, because new type has more bits than old.
6823 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
6824 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
6825 true);
6826}
6827
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006828/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006829/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006830static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006831 if (E == nullptr)
6832 return false;
6833 llvm::APSInt Result;
6834 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
6835 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
6836 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006837}
6838
Alexey Bataev5a3af132016-03-29 08:58:54 +00006839/// Build preinits statement for the given declarations.
6840static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00006841 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006842 if (!PreInits.empty()) {
6843 return new (Context) DeclStmt(
6844 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
6845 SourceLocation(), SourceLocation());
6846 }
6847 return nullptr;
6848}
6849
6850/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00006851static Stmt *
6852buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00006853 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006854 if (!Captures.empty()) {
6855 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00006856 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006857 PreInits.push_back(Pair.second->getDecl());
6858 return buildPreInits(Context, PreInits);
6859 }
6860 return nullptr;
6861}
6862
6863/// Build postupdate expression for the given list of postupdates expressions.
6864static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
6865 Expr *PostUpdate = nullptr;
6866 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006867 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006868 Expr *ConvE = S.BuildCStyleCastExpr(
6869 E->getExprLoc(),
6870 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
6871 E->getExprLoc(), E)
6872 .get();
6873 PostUpdate = PostUpdate
6874 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
6875 PostUpdate, ConvE)
6876 .get()
6877 : ConvE;
6878 }
6879 }
6880 return PostUpdate;
6881}
6882
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006883/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00006884/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6885/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006886static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00006887checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00006888 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6889 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00006890 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00006891 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006892 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006893 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006894 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006895 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006896 if (!CollapseLoopCountExpr->isValueDependent() &&
6897 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006898 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006899 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006900 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006901 return 1;
6902 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00006903 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006904 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006905 if (OrderedLoopCountExpr) {
6906 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006907 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006908 if (!OrderedLoopCountExpr->isValueDependent() &&
6909 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6910 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006911 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006912 if (Result.getLimitedValue() < NestedLoopCount) {
6913 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6914 diag::err_omp_wrong_ordered_loop_count)
6915 << OrderedLoopCountExpr->getSourceRange();
6916 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6917 diag::note_collapse_loop_count)
6918 << CollapseLoopCountExpr->getSourceRange();
6919 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006920 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006921 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006922 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006923 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006924 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006925 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006926 // This is helper routine for loop directives (e.g., 'for', 'simd',
6927 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006928 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006929 SmallVector<LoopIterationSpace, 4> IterSpaces(
6930 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006931 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006932 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006933 if (checkOpenMPIterationSpace(
6934 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6935 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006936 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006937 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006938 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006939 // OpenMP [2.8.1, simd construct, Restrictions]
6940 // All loops associated with the construct must be perfectly nested; that
6941 // is, there must be no intervening code nor any OpenMP directive between
6942 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006943 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
6944 CurStmt = For->getBody();
6945 } else {
6946 assert(isa<CXXForRangeStmt>(CurStmt) &&
6947 "Expected canonical for or range-based for loops.");
6948 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
6949 }
6950 CurStmt = CurStmt->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006951 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006952 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6953 if (checkOpenMPIterationSpace(
6954 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6955 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006956 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00006957 return 0;
6958 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6959 // Handle initialization of captured loop iterator variables.
6960 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6961 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6962 Captures[DRE] = DRE;
6963 }
6964 }
6965 // Move on to the next nested for loop, or to the loop body.
6966 // OpenMP [2.8.1, simd construct, Restrictions]
6967 // All loops associated with the construct must be perfectly nested; that
6968 // is, there must be no intervening code nor any OpenMP directive between
6969 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006970 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
6971 CurStmt = For->getBody();
6972 } else {
6973 assert(isa<CXXForRangeStmt>(CurStmt) &&
6974 "Expected canonical for or range-based for loops.");
6975 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
6976 }
6977 CurStmt = CurStmt->IgnoreContainers();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006978 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006979
Alexander Musmana5f070a2014-10-01 06:03:56 +00006980 Built.clear(/* size */ NestedLoopCount);
6981
6982 if (SemaRef.CurContext->isDependentContext())
6983 return NestedLoopCount;
6984
6985 // An example of what is generated for the following code:
6986 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006987 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006988 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006989 // for (k = 0; k < NK; ++k)
6990 // for (j = J0; j < NJ; j+=2) {
6991 // <loop body>
6992 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006993 //
6994 // We generate the code below.
6995 // Note: the loop body may be outlined in CodeGen.
6996 // Note: some counters may be C++ classes, operator- is used to find number of
6997 // iterations and operator+= to calculate counter value.
6998 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
6999 // or i64 is currently supported).
7000 //
7001 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7002 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7003 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7004 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7005 // // similar updates for vars in clauses (e.g. 'linear')
7006 // <loop body (using local i and j)>
7007 // }
7008 // i = NI; // assign final values of counters
7009 // j = NJ;
7010 //
7011
7012 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7013 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007014 // Precondition tests if there is at least one iteration (all conditions are
7015 // true).
7016 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007017 Expr *N0 = IterSpaces[0].NumIterations;
7018 ExprResult LastIteration32 =
7019 widenIterationCount(/*Bits=*/32,
7020 SemaRef
7021 .PerformImplicitConversion(
7022 N0->IgnoreImpCasts(), N0->getType(),
7023 Sema::AA_Converting, /*AllowExplicit=*/true)
7024 .get(),
7025 SemaRef);
7026 ExprResult LastIteration64 = widenIterationCount(
7027 /*Bits=*/64,
7028 SemaRef
7029 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7030 Sema::AA_Converting,
7031 /*AllowExplicit=*/true)
7032 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007033 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007034
7035 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7036 return NestedLoopCount;
7037
Alexey Bataeve3727102018-04-18 15:57:46 +00007038 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007039 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7040
7041 Scope *CurScope = DSA.getCurScope();
7042 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007043 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007044 PreCond =
7045 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7046 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007047 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007048 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007049 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007050 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7051 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007052 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007053 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007054 SemaRef
7055 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7056 Sema::AA_Converting,
7057 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007058 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007059 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007060 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007061 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007062 SemaRef
7063 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7064 Sema::AA_Converting,
7065 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007066 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007067 }
7068
7069 // Choose either the 32-bit or 64-bit version.
7070 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007071 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7072 (LastIteration32.isUsable() &&
7073 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7074 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7075 fitsInto(
7076 /*Bits=*/32,
7077 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7078 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007079 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007080 QualType VType = LastIteration.get()->getType();
7081 QualType RealVType = VType;
7082 QualType StrideVType = VType;
7083 if (isOpenMPTaskLoopDirective(DKind)) {
7084 VType =
7085 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7086 StrideVType =
7087 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7088 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007089
7090 if (!LastIteration.isUsable())
7091 return 0;
7092
7093 // Save the number of iterations.
7094 ExprResult NumIterations = LastIteration;
7095 {
7096 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007097 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7098 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007099 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7100 if (!LastIteration.isUsable())
7101 return 0;
7102 }
7103
7104 // Calculate the last iteration number beforehand instead of doing this on
7105 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7106 llvm::APSInt Result;
7107 bool IsConstant =
7108 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7109 ExprResult CalcLastIteration;
7110 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007111 ExprResult SaveRef =
7112 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007113 LastIteration = SaveRef;
7114
7115 // Prepare SaveRef + 1.
7116 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007117 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007118 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7119 if (!NumIterations.isUsable())
7120 return 0;
7121 }
7122
7123 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7124
David Majnemer9d168222016-08-05 17:44:54 +00007125 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007126 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007127 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7128 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007129 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007130 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7131 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007132 SemaRef.AddInitializerToDecl(LBDecl,
7133 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7134 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007135
7136 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007137 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7138 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007139 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007140 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007141
7142 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7143 // This will be used to implement clause 'lastprivate'.
7144 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007145 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7146 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007147 SemaRef.AddInitializerToDecl(ILDecl,
7148 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7149 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007150
7151 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007152 VarDecl *STDecl =
7153 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7154 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007155 SemaRef.AddInitializerToDecl(STDecl,
7156 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7157 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007158
7159 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007160 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007161 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7162 UB.get(), LastIteration.get());
7163 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007164 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7165 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007166 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7167 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007168 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007169
7170 // If we have a combined directive that combines 'distribute', 'for' or
7171 // 'simd' we need to be able to access the bounds of the schedule of the
7172 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7173 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7174 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007175 // Lower bound variable, initialized with zero.
7176 VarDecl *CombLBDecl =
7177 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7178 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7179 SemaRef.AddInitializerToDecl(
7180 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7181 /*DirectInit*/ false);
7182
7183 // Upper bound variable, initialized with last iteration number.
7184 VarDecl *CombUBDecl =
7185 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7186 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7187 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7188 /*DirectInit*/ false);
7189
7190 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7191 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7192 ExprResult CombCondOp =
7193 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7194 LastIteration.get(), CombUB.get());
7195 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7196 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007197 CombEUB =
7198 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007199
Alexey Bataeve3727102018-04-18 15:57:46 +00007200 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007201 // We expect to have at least 2 more parameters than the 'parallel'
7202 // directive does - the lower and upper bounds of the previous schedule.
7203 assert(CD->getNumParams() >= 4 &&
7204 "Unexpected number of parameters in loop combined directive");
7205
7206 // Set the proper type for the bounds given what we learned from the
7207 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007208 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7209 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007210
7211 // Previous lower and upper bounds are obtained from the region
7212 // parameters.
7213 PrevLB =
7214 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7215 PrevUB =
7216 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7217 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007218 }
7219
7220 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007221 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007222 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007223 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007224 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7225 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007226 Expr *RHS =
7227 (isOpenMPWorksharingDirective(DKind) ||
7228 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7229 ? LB.get()
7230 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007231 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007232 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007233
7234 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7235 Expr *CombRHS =
7236 (isOpenMPWorksharingDirective(DKind) ||
7237 isOpenMPTaskLoopDirective(DKind) ||
7238 isOpenMPDistributeDirective(DKind))
7239 ? CombLB.get()
7240 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7241 CombInit =
7242 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007243 CombInit =
7244 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007245 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007246 }
7247
Alexey Bataev316ccf62019-01-29 18:51:58 +00007248 bool UseStrictCompare =
7249 RealVType->hasUnsignedIntegerRepresentation() &&
7250 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7251 return LIS.IsStrictCompare;
7252 });
7253 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7254 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007255 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007256 Expr *BoundUB = UB.get();
7257 if (UseStrictCompare) {
7258 BoundUB =
7259 SemaRef
7260 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7261 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7262 .get();
7263 BoundUB =
7264 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7265 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007266 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007267 (isOpenMPWorksharingDirective(DKind) ||
7268 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007269 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7270 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7271 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007272 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7273 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007274 ExprResult CombDistCond;
7275 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007276 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7277 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007278 }
7279
Carlo Bertolliffafe102017-04-20 00:39:39 +00007280 ExprResult CombCond;
7281 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007282 Expr *BoundCombUB = CombUB.get();
7283 if (UseStrictCompare) {
7284 BoundCombUB =
7285 SemaRef
7286 .BuildBinOp(
7287 CurScope, CondLoc, BO_Add, BoundCombUB,
7288 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7289 .get();
7290 BoundCombUB =
7291 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7292 .get();
7293 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007294 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007295 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7296 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007297 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007298 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007299 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007300 ExprResult Inc =
7301 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7302 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7303 if (!Inc.isUsable())
7304 return 0;
7305 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007306 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007307 if (!Inc.isUsable())
7308 return 0;
7309
7310 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7311 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007312 // In combined construct, add combined version that use CombLB and CombUB
7313 // base variables for the update
7314 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007315 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7316 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007317 // LB + ST
7318 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7319 if (!NextLB.isUsable())
7320 return 0;
7321 // LB = LB + ST
7322 NextLB =
7323 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007324 NextLB =
7325 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007326 if (!NextLB.isUsable())
7327 return 0;
7328 // UB + ST
7329 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7330 if (!NextUB.isUsable())
7331 return 0;
7332 // UB = UB + ST
7333 NextUB =
7334 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007335 NextUB =
7336 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007337 if (!NextUB.isUsable())
7338 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007339 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7340 CombNextLB =
7341 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7342 if (!NextLB.isUsable())
7343 return 0;
7344 // LB = LB + ST
7345 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7346 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007347 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7348 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007349 if (!CombNextLB.isUsable())
7350 return 0;
7351 // UB + ST
7352 CombNextUB =
7353 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7354 if (!CombNextUB.isUsable())
7355 return 0;
7356 // UB = UB + ST
7357 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7358 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007359 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7360 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007361 if (!CombNextUB.isUsable())
7362 return 0;
7363 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007364 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007365
Carlo Bertolliffafe102017-04-20 00:39:39 +00007366 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007367 // directive with for as IV = IV + ST; ensure upper bound expression based
7368 // on PrevUB instead of NumIterations - used to implement 'for' when found
7369 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007370 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007371 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007372 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007373 DistCond = SemaRef.BuildBinOp(
7374 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007375 assert(DistCond.isUsable() && "distribute cond expr was not built");
7376
7377 DistInc =
7378 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7379 assert(DistInc.isUsable() && "distribute inc expr was not built");
7380 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7381 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007382 DistInc =
7383 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007384 assert(DistInc.isUsable() && "distribute inc expr was not built");
7385
7386 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7387 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007388 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007389 ExprResult IsUBGreater =
7390 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7391 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7392 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7393 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7394 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007395 PrevEUB =
7396 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007397
Alexey Bataev316ccf62019-01-29 18:51:58 +00007398 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7399 // parallel for is in combination with a distribute directive with
7400 // schedule(static, 1)
7401 Expr *BoundPrevUB = PrevUB.get();
7402 if (UseStrictCompare) {
7403 BoundPrevUB =
7404 SemaRef
7405 .BuildBinOp(
7406 CurScope, CondLoc, BO_Add, BoundPrevUB,
7407 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7408 .get();
7409 BoundPrevUB =
7410 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7411 .get();
7412 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007413 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007414 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7415 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007416 }
7417
Alexander Musmana5f070a2014-10-01 06:03:56 +00007418 // Build updates and final values of the loop counters.
7419 bool HasErrors = false;
7420 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007421 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007422 Built.Updates.resize(NestedLoopCount);
7423 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007424 Built.DependentCounters.resize(NestedLoopCount);
7425 Built.DependentInits.resize(NestedLoopCount);
7426 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007427 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007428 // We implement the following algorithm for obtaining the
7429 // original loop iteration variable values based on the
7430 // value of the collapsed loop iteration variable IV.
7431 //
7432 // Let n+1 be the number of collapsed loops in the nest.
7433 // Iteration variables (I0, I1, .... In)
7434 // Iteration counts (N0, N1, ... Nn)
7435 //
7436 // Acc = IV;
7437 //
7438 // To compute Ik for loop k, 0 <= k <= n, generate:
7439 // Prod = N(k+1) * N(k+2) * ... * Nn;
7440 // Ik = Acc / Prod;
7441 // Acc -= Ik * Prod;
7442 //
7443 ExprResult Acc = IV;
7444 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007445 LoopIterationSpace &IS = IterSpaces[Cnt];
7446 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007447 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007448
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007449 // Compute prod
7450 ExprResult Prod =
7451 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7452 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7453 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7454 IterSpaces[K].NumIterations);
7455
7456 // Iter = Acc / Prod
7457 // If there is at least one more inner loop to avoid
7458 // multiplication by 1.
7459 if (Cnt + 1 < NestedLoopCount)
7460 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7461 Acc.get(), Prod.get());
7462 else
7463 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007464 if (!Iter.isUsable()) {
7465 HasErrors = true;
7466 break;
7467 }
7468
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007469 // Update Acc:
7470 // Acc -= Iter * Prod
7471 // Check if there is at least one more inner loop to avoid
7472 // multiplication by 1.
7473 if (Cnt + 1 < NestedLoopCount)
7474 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7475 Iter.get(), Prod.get());
7476 else
7477 Prod = Iter;
7478 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7479 Acc.get(), Prod.get());
7480
Alexey Bataev39f915b82015-05-08 10:41:21 +00007481 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007482 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007483 DeclRefExpr *CounterVar = buildDeclRefExpr(
7484 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7485 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007486 ExprResult Init =
7487 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7488 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007489 if (!Init.isUsable()) {
7490 HasErrors = true;
7491 break;
7492 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007493 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007494 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007495 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007496 if (!Update.isUsable()) {
7497 HasErrors = true;
7498 break;
7499 }
7500
7501 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007502 ExprResult Final =
7503 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7504 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7505 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007506 if (!Final.isUsable()) {
7507 HasErrors = true;
7508 break;
7509 }
7510
Alexander Musmana5f070a2014-10-01 06:03:56 +00007511 if (!Update.isUsable() || !Final.isUsable()) {
7512 HasErrors = true;
7513 break;
7514 }
7515 // Save results
7516 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007517 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007518 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007519 Built.Updates[Cnt] = Update.get();
7520 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007521 Built.DependentCounters[Cnt] = nullptr;
7522 Built.DependentInits[Cnt] = nullptr;
7523 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007524 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007525 Built.DependentCounters[Cnt] =
7526 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7527 Built.DependentInits[Cnt] =
7528 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7529 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7530 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007531 }
7532 }
7533
7534 if (HasErrors)
7535 return 0;
7536
7537 // Save results
7538 Built.IterationVarRef = IV.get();
7539 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007540 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007541 Built.CalcLastIteration = SemaRef
7542 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007543 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007544 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007545 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007546 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007547 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007548 Built.Init = Init.get();
7549 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007550 Built.LB = LB.get();
7551 Built.UB = UB.get();
7552 Built.IL = IL.get();
7553 Built.ST = ST.get();
7554 Built.EUB = EUB.get();
7555 Built.NLB = NextLB.get();
7556 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007557 Built.PrevLB = PrevLB.get();
7558 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007559 Built.DistInc = DistInc.get();
7560 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007561 Built.DistCombinedFields.LB = CombLB.get();
7562 Built.DistCombinedFields.UB = CombUB.get();
7563 Built.DistCombinedFields.EUB = CombEUB.get();
7564 Built.DistCombinedFields.Init = CombInit.get();
7565 Built.DistCombinedFields.Cond = CombCond.get();
7566 Built.DistCombinedFields.NLB = CombNextLB.get();
7567 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007568 Built.DistCombinedFields.DistCond = CombDistCond.get();
7569 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007570
Alexey Bataevabfc0692014-06-25 06:52:00 +00007571 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007572}
7573
Alexey Bataev10e775f2015-07-30 11:36:16 +00007574static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007575 auto CollapseClauses =
7576 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7577 if (CollapseClauses.begin() != CollapseClauses.end())
7578 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007579 return nullptr;
7580}
7581
Alexey Bataev10e775f2015-07-30 11:36:16 +00007582static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007583 auto OrderedClauses =
7584 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7585 if (OrderedClauses.begin() != OrderedClauses.end())
7586 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007587 return nullptr;
7588}
7589
Kelvin Lic5609492016-07-15 04:39:07 +00007590static bool checkSimdlenSafelenSpecified(Sema &S,
7591 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007592 const OMPSafelenClause *Safelen = nullptr;
7593 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007594
Alexey Bataeve3727102018-04-18 15:57:46 +00007595 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007596 if (Clause->getClauseKind() == OMPC_safelen)
7597 Safelen = cast<OMPSafelenClause>(Clause);
7598 else if (Clause->getClauseKind() == OMPC_simdlen)
7599 Simdlen = cast<OMPSimdlenClause>(Clause);
7600 if (Safelen && Simdlen)
7601 break;
7602 }
7603
7604 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007605 const Expr *SimdlenLength = Simdlen->getSimdlen();
7606 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007607 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7608 SimdlenLength->isInstantiationDependent() ||
7609 SimdlenLength->containsUnexpandedParameterPack())
7610 return false;
7611 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7612 SafelenLength->isInstantiationDependent() ||
7613 SafelenLength->containsUnexpandedParameterPack())
7614 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007615 Expr::EvalResult SimdlenResult, SafelenResult;
7616 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7617 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7618 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7619 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007620 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7621 // If both simdlen and safelen clauses are specified, the value of the
7622 // simdlen parameter must be less than or equal to the value of the safelen
7623 // parameter.
7624 if (SimdlenRes > SafelenRes) {
7625 S.Diag(SimdlenLength->getExprLoc(),
7626 diag::err_omp_wrong_simdlen_safelen_values)
7627 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7628 return true;
7629 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007630 }
7631 return false;
7632}
7633
Alexey Bataeve3727102018-04-18 15:57:46 +00007634StmtResult
7635Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7636 SourceLocation StartLoc, SourceLocation EndLoc,
7637 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007638 if (!AStmt)
7639 return StmtError();
7640
7641 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007642 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007643 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7644 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007645 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007646 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7647 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007648 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007649 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007650
Alexander Musmana5f070a2014-10-01 06:03:56 +00007651 assert((CurContext->isDependentContext() || B.builtAll()) &&
7652 "omp simd loop exprs were not built");
7653
Alexander Musman3276a272015-03-21 10:12:56 +00007654 if (!CurContext->isDependentContext()) {
7655 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007656 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007657 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007658 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007659 B.NumIterations, *this, CurScope,
7660 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007661 return StmtError();
7662 }
7663 }
7664
Kelvin Lic5609492016-07-15 04:39:07 +00007665 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007666 return StmtError();
7667
Reid Kleckner87a31802018-03-12 21:43:02 +00007668 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007669 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7670 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007671}
7672
Alexey Bataeve3727102018-04-18 15:57:46 +00007673StmtResult
7674Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7675 SourceLocation StartLoc, SourceLocation EndLoc,
7676 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007677 if (!AStmt)
7678 return StmtError();
7679
7680 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007681 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007682 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7683 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007684 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007685 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7686 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007687 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007688 return StmtError();
7689
Alexander Musmana5f070a2014-10-01 06:03:56 +00007690 assert((CurContext->isDependentContext() || B.builtAll()) &&
7691 "omp for loop exprs were not built");
7692
Alexey Bataev54acd402015-08-04 11:18:19 +00007693 if (!CurContext->isDependentContext()) {
7694 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007695 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007696 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007697 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007698 B.NumIterations, *this, CurScope,
7699 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007700 return StmtError();
7701 }
7702 }
7703
Reid Kleckner87a31802018-03-12 21:43:02 +00007704 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007705 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007706 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007707}
7708
Alexander Musmanf82886e2014-09-18 05:12:34 +00007709StmtResult Sema::ActOnOpenMPForSimdDirective(
7710 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007711 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007712 if (!AStmt)
7713 return StmtError();
7714
7715 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007716 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007717 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7718 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007719 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007720 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007721 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7722 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007723 if (NestedLoopCount == 0)
7724 return StmtError();
7725
Alexander Musmanc6388682014-12-15 07:07:06 +00007726 assert((CurContext->isDependentContext() || B.builtAll()) &&
7727 "omp for simd loop exprs were not built");
7728
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007729 if (!CurContext->isDependentContext()) {
7730 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007731 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007732 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007733 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007734 B.NumIterations, *this, CurScope,
7735 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007736 return StmtError();
7737 }
7738 }
7739
Kelvin Lic5609492016-07-15 04:39:07 +00007740 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007741 return StmtError();
7742
Reid Kleckner87a31802018-03-12 21:43:02 +00007743 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007744 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7745 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007746}
7747
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007748StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7749 Stmt *AStmt,
7750 SourceLocation StartLoc,
7751 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007752 if (!AStmt)
7753 return StmtError();
7754
7755 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007756 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007757 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007758 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007759 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007760 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007761 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007762 return StmtError();
7763 // All associated statements must be '#pragma omp section' except for
7764 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007765 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007766 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7767 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007768 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007769 diag::err_omp_sections_substmt_not_section);
7770 return StmtError();
7771 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007772 cast<OMPSectionDirective>(SectionStmt)
7773 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007774 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007775 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007776 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007777 return StmtError();
7778 }
7779
Reid Kleckner87a31802018-03-12 21:43:02 +00007780 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007781
Alexey Bataev25e5b442015-09-15 12:52:43 +00007782 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7783 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007784}
7785
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007786StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
7787 SourceLocation StartLoc,
7788 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007789 if (!AStmt)
7790 return StmtError();
7791
7792 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007793
Reid Kleckner87a31802018-03-12 21:43:02 +00007794 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00007795 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007796
Alexey Bataev25e5b442015-09-15 12:52:43 +00007797 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
7798 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007799}
7800
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007801StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7802 Stmt *AStmt,
7803 SourceLocation StartLoc,
7804 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007805 if (!AStmt)
7806 return StmtError();
7807
7808 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00007809
Reid Kleckner87a31802018-03-12 21:43:02 +00007810 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00007811
Alexey Bataev3255bf32015-01-19 05:20:46 +00007812 // OpenMP [2.7.3, single Construct, Restrictions]
7813 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00007814 const OMPClause *Nowait = nullptr;
7815 const OMPClause *Copyprivate = nullptr;
7816 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00007817 if (Clause->getClauseKind() == OMPC_nowait)
7818 Nowait = Clause;
7819 else if (Clause->getClauseKind() == OMPC_copyprivate)
7820 Copyprivate = Clause;
7821 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007822 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00007823 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007824 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00007825 return StmtError();
7826 }
7827 }
7828
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007829 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7830}
7831
Alexander Musman80c22892014-07-17 08:54:58 +00007832StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
7833 SourceLocation StartLoc,
7834 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007835 if (!AStmt)
7836 return StmtError();
7837
7838 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00007839
Reid Kleckner87a31802018-03-12 21:43:02 +00007840 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00007841
7842 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
7843}
7844
Alexey Bataev28c75412015-12-15 08:19:24 +00007845StmtResult Sema::ActOnOpenMPCriticalDirective(
7846 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
7847 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007848 if (!AStmt)
7849 return StmtError();
7850
7851 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007852
Alexey Bataev28c75412015-12-15 08:19:24 +00007853 bool ErrorFound = false;
7854 llvm::APSInt Hint;
7855 SourceLocation HintLoc;
7856 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007857 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007858 if (C->getClauseKind() == OMPC_hint) {
7859 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007860 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00007861 ErrorFound = true;
7862 }
7863 Expr *E = cast<OMPHintClause>(C)->getHint();
7864 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00007865 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007866 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007867 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00007868 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007869 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00007870 }
7871 }
7872 }
7873 if (ErrorFound)
7874 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007875 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00007876 if (Pair.first && DirName.getName() && !DependentHint) {
7877 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
7878 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00007879 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00007880 Diag(HintLoc, diag::note_omp_critical_hint_here)
7881 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007882 else
Alexey Bataev28c75412015-12-15 08:19:24 +00007883 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00007884 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007885 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00007886 << 1
7887 << C->getHint()->EvaluateKnownConstInt(Context).toString(
7888 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007889 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007890 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00007891 }
Alexey Bataev28c75412015-12-15 08:19:24 +00007892 }
7893 }
7894
Reid Kleckner87a31802018-03-12 21:43:02 +00007895 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007896
Alexey Bataev28c75412015-12-15 08:19:24 +00007897 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
7898 Clauses, AStmt);
7899 if (!Pair.first && DirName.getName() && !DependentHint)
7900 DSAStack->addCriticalWithHint(Dir, Hint);
7901 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007902}
7903
Alexey Bataev4acb8592014-07-07 13:01:15 +00007904StmtResult Sema::ActOnOpenMPParallelForDirective(
7905 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007906 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007907 if (!AStmt)
7908 return StmtError();
7909
Alexey Bataeve3727102018-04-18 15:57:46 +00007910 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007911 // 1.2.2 OpenMP Language Terminology
7912 // Structured block - An executable statement with a single entry at the
7913 // top and a single exit at the bottom.
7914 // The point of exit cannot be a branch out of the structured block.
7915 // longjmp() and throw() must not violate the entry/exit criteria.
7916 CS->getCapturedDecl()->setNothrow();
7917
Alexander Musmanc6388682014-12-15 07:07:06 +00007918 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007919 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7920 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007921 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007922 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007923 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7924 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007925 if (NestedLoopCount == 0)
7926 return StmtError();
7927
Alexander Musmana5f070a2014-10-01 06:03:56 +00007928 assert((CurContext->isDependentContext() || B.builtAll()) &&
7929 "omp parallel for loop exprs were not built");
7930
Alexey Bataev54acd402015-08-04 11:18:19 +00007931 if (!CurContext->isDependentContext()) {
7932 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007933 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007934 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007935 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007936 B.NumIterations, *this, CurScope,
7937 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007938 return StmtError();
7939 }
7940 }
7941
Reid Kleckner87a31802018-03-12 21:43:02 +00007942 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007943 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007944 NestedLoopCount, Clauses, AStmt, B,
7945 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00007946}
7947
Alexander Musmane4e893b2014-09-23 09:33:00 +00007948StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
7949 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007950 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007951 if (!AStmt)
7952 return StmtError();
7953
Alexey Bataeve3727102018-04-18 15:57:46 +00007954 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007955 // 1.2.2 OpenMP Language Terminology
7956 // Structured block - An executable statement with a single entry at the
7957 // top and a single exit at the bottom.
7958 // The point of exit cannot be a branch out of the structured block.
7959 // longjmp() and throw() must not violate the entry/exit criteria.
7960 CS->getCapturedDecl()->setNothrow();
7961
Alexander Musmanc6388682014-12-15 07:07:06 +00007962 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007963 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7964 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007965 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007966 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007967 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7968 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007969 if (NestedLoopCount == 0)
7970 return StmtError();
7971
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007972 if (!CurContext->isDependentContext()) {
7973 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007974 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007975 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007976 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007977 B.NumIterations, *this, CurScope,
7978 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007979 return StmtError();
7980 }
7981 }
7982
Kelvin Lic5609492016-07-15 04:39:07 +00007983 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007984 return StmtError();
7985
Reid Kleckner87a31802018-03-12 21:43:02 +00007986 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007987 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007988 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007989}
7990
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007991StmtResult
7992Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7993 Stmt *AStmt, SourceLocation StartLoc,
7994 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007995 if (!AStmt)
7996 return StmtError();
7997
7998 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007999 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008000 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008001 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008002 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008003 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008004 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008005 return StmtError();
8006 // All associated statements must be '#pragma omp section' except for
8007 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008008 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008009 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8010 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008011 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008012 diag::err_omp_parallel_sections_substmt_not_section);
8013 return StmtError();
8014 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008015 cast<OMPSectionDirective>(SectionStmt)
8016 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008017 }
8018 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008019 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008020 diag::err_omp_parallel_sections_not_compound_stmt);
8021 return StmtError();
8022 }
8023
Reid Kleckner87a31802018-03-12 21:43:02 +00008024 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008025
Alexey Bataev25e5b442015-09-15 12:52:43 +00008026 return OMPParallelSectionsDirective::Create(
8027 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008028}
8029
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008030StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8031 Stmt *AStmt, SourceLocation StartLoc,
8032 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008033 if (!AStmt)
8034 return StmtError();
8035
David Majnemer9d168222016-08-05 17:44:54 +00008036 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008037 // 1.2.2 OpenMP Language Terminology
8038 // Structured block - An executable statement with a single entry at the
8039 // top and a single exit at the bottom.
8040 // The point of exit cannot be a branch out of the structured block.
8041 // longjmp() and throw() must not violate the entry/exit criteria.
8042 CS->getCapturedDecl()->setNothrow();
8043
Reid Kleckner87a31802018-03-12 21:43:02 +00008044 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008045
Alexey Bataev25e5b442015-09-15 12:52:43 +00008046 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8047 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008048}
8049
Alexey Bataev68446b72014-07-18 07:47:19 +00008050StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8051 SourceLocation EndLoc) {
8052 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8053}
8054
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008055StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8056 SourceLocation EndLoc) {
8057 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8058}
8059
Alexey Bataev2df347a2014-07-18 10:17:07 +00008060StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8061 SourceLocation EndLoc) {
8062 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8063}
8064
Alexey Bataev169d96a2017-07-18 20:17:46 +00008065StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8066 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008067 SourceLocation StartLoc,
8068 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008069 if (!AStmt)
8070 return StmtError();
8071
8072 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008073
Reid Kleckner87a31802018-03-12 21:43:02 +00008074 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008075
Alexey Bataev169d96a2017-07-18 20:17:46 +00008076 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008077 AStmt,
8078 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008079}
8080
Alexey Bataev6125da92014-07-21 11:26:11 +00008081StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8082 SourceLocation StartLoc,
8083 SourceLocation EndLoc) {
8084 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8085 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8086}
8087
Alexey Bataev346265e2015-09-25 10:37:12 +00008088StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8089 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008090 SourceLocation StartLoc,
8091 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008092 const OMPClause *DependFound = nullptr;
8093 const OMPClause *DependSourceClause = nullptr;
8094 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008095 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008096 const OMPThreadsClause *TC = nullptr;
8097 const OMPSIMDClause *SC = nullptr;
8098 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008099 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8100 DependFound = C;
8101 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8102 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008103 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008104 << getOpenMPDirectiveName(OMPD_ordered)
8105 << getOpenMPClauseName(OMPC_depend) << 2;
8106 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008107 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008108 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008109 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008110 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008111 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008112 << 0;
8113 ErrorFound = true;
8114 }
8115 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8116 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008117 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008118 << 1;
8119 ErrorFound = true;
8120 }
8121 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008122 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008123 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008124 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008125 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008126 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008127 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008128 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008129 if (!ErrorFound && !SC &&
8130 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008131 // OpenMP [2.8.1,simd Construct, Restrictions]
8132 // An ordered construct with the simd clause is the only OpenMP construct
8133 // that can appear in the simd region.
8134 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00008135 ErrorFound = true;
8136 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008137 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008138 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8139 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008140 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008141 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008142 diag::err_omp_ordered_directive_without_param);
8143 ErrorFound = true;
8144 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008145 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008146 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008147 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8148 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008149 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008150 ErrorFound = true;
8151 }
8152 }
8153 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008154 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008155
8156 if (AStmt) {
8157 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8158
Reid Kleckner87a31802018-03-12 21:43:02 +00008159 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008160 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008161
8162 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008163}
8164
Alexey Bataev1d160b12015-03-13 12:27:31 +00008165namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008166/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008167/// construct.
8168class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008169 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008170 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008171 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008172 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008173 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008174 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008175 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008176 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008177 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008178 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008179 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008180 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008181 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008182 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008183 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008184 /// expression.
8185 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008186 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008187 /// part.
8188 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008189 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008190 NoError
8191 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008192 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008193 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008194 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008195 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008196 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008197 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008198 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008199 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008200 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008201 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8202 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8203 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008204 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008205 /// important for non-associative operations.
8206 bool IsXLHSInRHSPart;
8207 BinaryOperatorKind Op;
8208 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008209 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008210 /// if it is a prefix unary operation.
8211 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008212
8213public:
8214 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008215 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008216 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008217 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008218 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008219 /// expression. If DiagId and NoteId == 0, then only check is performed
8220 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008221 /// \param DiagId Diagnostic which should be emitted if error is found.
8222 /// \param NoteId Diagnostic note for the main error message.
8223 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008224 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008225 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008226 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008227 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008228 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008229 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008230 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8231 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8232 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008233 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008234 /// false otherwise.
8235 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8236
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008237 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008238 /// if it is a prefix unary operation.
8239 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8240
Alexey Bataev1d160b12015-03-13 12:27:31 +00008241private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008242 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8243 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008244};
8245} // namespace
8246
8247bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8248 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8249 ExprAnalysisErrorCode ErrorFound = NoError;
8250 SourceLocation ErrorLoc, NoteLoc;
8251 SourceRange ErrorRange, NoteRange;
8252 // Allowed constructs are:
8253 // x = x binop expr;
8254 // x = expr binop x;
8255 if (AtomicBinOp->getOpcode() == BO_Assign) {
8256 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008257 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008258 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8259 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8260 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8261 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008262 Op = AtomicInnerBinOp->getOpcode();
8263 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008264 Expr *LHS = AtomicInnerBinOp->getLHS();
8265 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008266 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8267 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8268 /*Canonical=*/true);
8269 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8270 /*Canonical=*/true);
8271 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8272 /*Canonical=*/true);
8273 if (XId == LHSId) {
8274 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008275 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008276 } else if (XId == RHSId) {
8277 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008278 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008279 } else {
8280 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8281 ErrorRange = AtomicInnerBinOp->getSourceRange();
8282 NoteLoc = X->getExprLoc();
8283 NoteRange = X->getSourceRange();
8284 ErrorFound = NotAnUpdateExpression;
8285 }
8286 } else {
8287 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8288 ErrorRange = AtomicInnerBinOp->getSourceRange();
8289 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8290 NoteRange = SourceRange(NoteLoc, NoteLoc);
8291 ErrorFound = NotABinaryOperator;
8292 }
8293 } else {
8294 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8295 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8296 ErrorFound = NotABinaryExpression;
8297 }
8298 } else {
8299 ErrorLoc = AtomicBinOp->getExprLoc();
8300 ErrorRange = AtomicBinOp->getSourceRange();
8301 NoteLoc = AtomicBinOp->getOperatorLoc();
8302 NoteRange = SourceRange(NoteLoc, NoteLoc);
8303 ErrorFound = NotAnAssignmentOp;
8304 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008305 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008306 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8307 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8308 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008309 }
8310 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008311 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008312 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008313}
8314
8315bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8316 unsigned NoteId) {
8317 ExprAnalysisErrorCode ErrorFound = NoError;
8318 SourceLocation ErrorLoc, NoteLoc;
8319 SourceRange ErrorRange, NoteRange;
8320 // Allowed constructs are:
8321 // x++;
8322 // x--;
8323 // ++x;
8324 // --x;
8325 // x binop= expr;
8326 // x = x binop expr;
8327 // x = expr binop x;
8328 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8329 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8330 if (AtomicBody->getType()->isScalarType() ||
8331 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008332 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008333 AtomicBody->IgnoreParenImpCasts())) {
8334 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008335 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008336 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008337 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008338 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008339 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008340 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008341 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8342 AtomicBody->IgnoreParenImpCasts())) {
8343 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008344 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008345 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008346 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008347 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008348 // Check for Unary Operation
8349 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008350 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008351 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8352 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008353 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008354 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8355 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008356 } else {
8357 ErrorFound = NotAnUnaryIncDecExpression;
8358 ErrorLoc = AtomicUnaryOp->getExprLoc();
8359 ErrorRange = AtomicUnaryOp->getSourceRange();
8360 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8361 NoteRange = SourceRange(NoteLoc, NoteLoc);
8362 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008363 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008364 ErrorFound = NotABinaryOrUnaryExpression;
8365 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8366 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8367 }
8368 } else {
8369 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008370 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008371 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8372 }
8373 } else {
8374 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008375 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008376 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8377 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008378 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008379 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8380 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8381 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008382 }
8383 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008384 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008385 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008386 // Build an update expression of form 'OpaqueValueExpr(x) binop
8387 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8388 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8389 auto *OVEX = new (SemaRef.getASTContext())
8390 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8391 auto *OVEExpr = new (SemaRef.getASTContext())
8392 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008393 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008394 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8395 IsXLHSInRHSPart ? OVEExpr : OVEX);
8396 if (Update.isInvalid())
8397 return true;
8398 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8399 Sema::AA_Casting);
8400 if (Update.isInvalid())
8401 return true;
8402 UpdateExpr = Update.get();
8403 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008404 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008405}
8406
Alexey Bataev0162e452014-07-22 10:10:35 +00008407StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8408 Stmt *AStmt,
8409 SourceLocation StartLoc,
8410 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008411 if (!AStmt)
8412 return StmtError();
8413
David Majnemer9d168222016-08-05 17:44:54 +00008414 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008415 // 1.2.2 OpenMP Language Terminology
8416 // Structured block - An executable statement with a single entry at the
8417 // top and a single exit at the bottom.
8418 // The point of exit cannot be a branch out of the structured block.
8419 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008420 OpenMPClauseKind AtomicKind = OMPC_unknown;
8421 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008422 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008423 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008424 C->getClauseKind() == OMPC_update ||
8425 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008426 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008427 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008428 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008429 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8430 << getOpenMPClauseName(AtomicKind);
8431 } else {
8432 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008433 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008434 }
8435 }
8436 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008437
Alexey Bataeve3727102018-04-18 15:57:46 +00008438 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008439 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8440 Body = EWC->getSubExpr();
8441
Alexey Bataev62cec442014-11-18 10:14:22 +00008442 Expr *X = nullptr;
8443 Expr *V = nullptr;
8444 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008445 Expr *UE = nullptr;
8446 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008447 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008448 // OpenMP [2.12.6, atomic Construct]
8449 // In the next expressions:
8450 // * x and v (as applicable) are both l-value expressions with scalar type.
8451 // * During the execution of an atomic region, multiple syntactic
8452 // occurrences of x must designate the same storage location.
8453 // * Neither of v and expr (as applicable) may access the storage location
8454 // designated by x.
8455 // * Neither of x and expr (as applicable) may access the storage location
8456 // designated by v.
8457 // * expr is an expression with scalar type.
8458 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8459 // * binop, binop=, ++, and -- are not overloaded operators.
8460 // * The expression x binop expr must be numerically equivalent to x binop
8461 // (expr). This requirement is satisfied if the operators in expr have
8462 // precedence greater than binop, or by using parentheses around expr or
8463 // subexpressions of expr.
8464 // * The expression expr binop x must be numerically equivalent to (expr)
8465 // binop x. This requirement is satisfied if the operators in expr have
8466 // precedence equal to or greater than binop, or by using parentheses around
8467 // expr or subexpressions of expr.
8468 // * For forms that allow multiple occurrences of x, the number of times
8469 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008470 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008471 enum {
8472 NotAnExpression,
8473 NotAnAssignmentOp,
8474 NotAScalarType,
8475 NotAnLValue,
8476 NoError
8477 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008478 SourceLocation ErrorLoc, NoteLoc;
8479 SourceRange ErrorRange, NoteRange;
8480 // If clause is read:
8481 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008482 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8483 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008484 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8485 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8486 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8487 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8488 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8489 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8490 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008491 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008492 ErrorFound = NotAnLValue;
8493 ErrorLoc = AtomicBinOp->getExprLoc();
8494 ErrorRange = AtomicBinOp->getSourceRange();
8495 NoteLoc = NotLValueExpr->getExprLoc();
8496 NoteRange = NotLValueExpr->getSourceRange();
8497 }
8498 } else if (!X->isInstantiationDependent() ||
8499 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008500 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008501 (X->isInstantiationDependent() || X->getType()->isScalarType())
8502 ? V
8503 : X;
8504 ErrorFound = NotAScalarType;
8505 ErrorLoc = AtomicBinOp->getExprLoc();
8506 ErrorRange = AtomicBinOp->getSourceRange();
8507 NoteLoc = NotScalarExpr->getExprLoc();
8508 NoteRange = NotScalarExpr->getSourceRange();
8509 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008510 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008511 ErrorFound = NotAnAssignmentOp;
8512 ErrorLoc = AtomicBody->getExprLoc();
8513 ErrorRange = AtomicBody->getSourceRange();
8514 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8515 : AtomicBody->getExprLoc();
8516 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8517 : AtomicBody->getSourceRange();
8518 }
8519 } else {
8520 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008521 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008522 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008523 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008524 if (ErrorFound != NoError) {
8525 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8526 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008527 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8528 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008529 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008530 }
8531 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008532 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008533 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008534 enum {
8535 NotAnExpression,
8536 NotAnAssignmentOp,
8537 NotAScalarType,
8538 NotAnLValue,
8539 NoError
8540 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008541 SourceLocation ErrorLoc, NoteLoc;
8542 SourceRange ErrorRange, NoteRange;
8543 // If clause is write:
8544 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008545 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8546 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008547 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8548 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008549 X = AtomicBinOp->getLHS();
8550 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008551 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8552 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8553 if (!X->isLValue()) {
8554 ErrorFound = NotAnLValue;
8555 ErrorLoc = AtomicBinOp->getExprLoc();
8556 ErrorRange = AtomicBinOp->getSourceRange();
8557 NoteLoc = X->getExprLoc();
8558 NoteRange = X->getSourceRange();
8559 }
8560 } else if (!X->isInstantiationDependent() ||
8561 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008562 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008563 (X->isInstantiationDependent() || X->getType()->isScalarType())
8564 ? E
8565 : X;
8566 ErrorFound = NotAScalarType;
8567 ErrorLoc = AtomicBinOp->getExprLoc();
8568 ErrorRange = AtomicBinOp->getSourceRange();
8569 NoteLoc = NotScalarExpr->getExprLoc();
8570 NoteRange = NotScalarExpr->getSourceRange();
8571 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008572 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008573 ErrorFound = NotAnAssignmentOp;
8574 ErrorLoc = AtomicBody->getExprLoc();
8575 ErrorRange = AtomicBody->getSourceRange();
8576 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8577 : AtomicBody->getExprLoc();
8578 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8579 : AtomicBody->getSourceRange();
8580 }
8581 } else {
8582 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008583 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008584 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008585 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008586 if (ErrorFound != NoError) {
8587 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8588 << ErrorRange;
8589 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8590 << NoteRange;
8591 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008592 }
8593 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008594 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008595 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008596 // If clause is update:
8597 // x++;
8598 // x--;
8599 // ++x;
8600 // --x;
8601 // x binop= expr;
8602 // x = x binop expr;
8603 // x = expr binop x;
8604 OpenMPAtomicUpdateChecker Checker(*this);
8605 if (Checker.checkStatement(
8606 Body, (AtomicKind == OMPC_update)
8607 ? diag::err_omp_atomic_update_not_expression_statement
8608 : diag::err_omp_atomic_not_expression_statement,
8609 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008610 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008611 if (!CurContext->isDependentContext()) {
8612 E = Checker.getExpr();
8613 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008614 UE = Checker.getUpdateExpr();
8615 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008616 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008617 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008618 enum {
8619 NotAnAssignmentOp,
8620 NotACompoundStatement,
8621 NotTwoSubstatements,
8622 NotASpecificExpression,
8623 NoError
8624 } ErrorFound = NoError;
8625 SourceLocation ErrorLoc, NoteLoc;
8626 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008627 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008628 // If clause is a capture:
8629 // v = x++;
8630 // v = x--;
8631 // v = ++x;
8632 // v = --x;
8633 // v = x binop= expr;
8634 // v = x = x binop expr;
8635 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008636 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008637 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8638 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8639 V = AtomicBinOp->getLHS();
8640 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8641 OpenMPAtomicUpdateChecker Checker(*this);
8642 if (Checker.checkStatement(
8643 Body, diag::err_omp_atomic_capture_not_expression_statement,
8644 diag::note_omp_atomic_update))
8645 return StmtError();
8646 E = Checker.getExpr();
8647 X = Checker.getX();
8648 UE = Checker.getUpdateExpr();
8649 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8650 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008651 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008652 ErrorLoc = AtomicBody->getExprLoc();
8653 ErrorRange = AtomicBody->getSourceRange();
8654 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8655 : AtomicBody->getExprLoc();
8656 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8657 : AtomicBody->getSourceRange();
8658 ErrorFound = NotAnAssignmentOp;
8659 }
8660 if (ErrorFound != NoError) {
8661 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8662 << ErrorRange;
8663 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8664 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008665 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008666 if (CurContext->isDependentContext())
8667 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008668 } else {
8669 // If clause is a capture:
8670 // { v = x; x = expr; }
8671 // { v = x; x++; }
8672 // { v = x; x--; }
8673 // { v = x; ++x; }
8674 // { v = x; --x; }
8675 // { v = x; x binop= expr; }
8676 // { v = x; x = x binop expr; }
8677 // { v = x; x = expr binop x; }
8678 // { x++; v = x; }
8679 // { x--; v = x; }
8680 // { ++x; v = x; }
8681 // { --x; v = x; }
8682 // { x binop= expr; v = x; }
8683 // { x = x binop expr; v = x; }
8684 // { x = expr binop x; v = x; }
8685 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8686 // Check that this is { expr1; expr2; }
8687 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008688 Stmt *First = CS->body_front();
8689 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008690 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8691 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8692 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8693 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8694 // Need to find what subexpression is 'v' and what is 'x'.
8695 OpenMPAtomicUpdateChecker Checker(*this);
8696 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8697 BinaryOperator *BinOp = nullptr;
8698 if (IsUpdateExprFound) {
8699 BinOp = dyn_cast<BinaryOperator>(First);
8700 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8701 }
8702 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8703 // { v = x; x++; }
8704 // { v = x; x--; }
8705 // { v = x; ++x; }
8706 // { v = x; --x; }
8707 // { v = x; x binop= expr; }
8708 // { v = x; x = x binop expr; }
8709 // { v = x; x = expr binop x; }
8710 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008711 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008712 llvm::FoldingSetNodeID XId, PossibleXId;
8713 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8714 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8715 IsUpdateExprFound = XId == PossibleXId;
8716 if (IsUpdateExprFound) {
8717 V = BinOp->getLHS();
8718 X = Checker.getX();
8719 E = Checker.getExpr();
8720 UE = Checker.getUpdateExpr();
8721 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008722 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008723 }
8724 }
8725 if (!IsUpdateExprFound) {
8726 IsUpdateExprFound = !Checker.checkStatement(First);
8727 BinOp = nullptr;
8728 if (IsUpdateExprFound) {
8729 BinOp = dyn_cast<BinaryOperator>(Second);
8730 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8731 }
8732 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8733 // { x++; v = x; }
8734 // { x--; v = x; }
8735 // { ++x; v = x; }
8736 // { --x; v = x; }
8737 // { x binop= expr; v = x; }
8738 // { x = x binop expr; v = x; }
8739 // { x = expr binop x; v = x; }
8740 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008741 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008742 llvm::FoldingSetNodeID XId, PossibleXId;
8743 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8744 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8745 IsUpdateExprFound = XId == PossibleXId;
8746 if (IsUpdateExprFound) {
8747 V = BinOp->getLHS();
8748 X = Checker.getX();
8749 E = Checker.getExpr();
8750 UE = Checker.getUpdateExpr();
8751 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008752 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008753 }
8754 }
8755 }
8756 if (!IsUpdateExprFound) {
8757 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00008758 auto *FirstExpr = dyn_cast<Expr>(First);
8759 auto *SecondExpr = dyn_cast<Expr>(Second);
8760 if (!FirstExpr || !SecondExpr ||
8761 !(FirstExpr->isInstantiationDependent() ||
8762 SecondExpr->isInstantiationDependent())) {
8763 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
8764 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008765 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00008766 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008767 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008768 NoteRange = ErrorRange = FirstBinOp
8769 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00008770 : SourceRange(ErrorLoc, ErrorLoc);
8771 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00008772 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
8773 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
8774 ErrorFound = NotAnAssignmentOp;
8775 NoteLoc = ErrorLoc = SecondBinOp
8776 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008777 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008778 NoteRange = ErrorRange =
8779 SecondBinOp ? SecondBinOp->getSourceRange()
8780 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00008781 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008782 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00008783 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00008784 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00008785 SecondBinOp->getLHS()->IgnoreParenImpCasts();
8786 llvm::FoldingSetNodeID X1Id, X2Id;
8787 PossibleXRHSInFirst->Profile(X1Id, Context,
8788 /*Canonical=*/true);
8789 PossibleXLHSInSecond->Profile(X2Id, Context,
8790 /*Canonical=*/true);
8791 IsUpdateExprFound = X1Id == X2Id;
8792 if (IsUpdateExprFound) {
8793 V = FirstBinOp->getLHS();
8794 X = SecondBinOp->getLHS();
8795 E = SecondBinOp->getRHS();
8796 UE = nullptr;
8797 IsXLHSInRHSPart = false;
8798 IsPostfixUpdate = true;
8799 } else {
8800 ErrorFound = NotASpecificExpression;
8801 ErrorLoc = FirstBinOp->getExprLoc();
8802 ErrorRange = FirstBinOp->getSourceRange();
8803 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
8804 NoteRange = SecondBinOp->getRHS()->getSourceRange();
8805 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008806 }
8807 }
8808 }
8809 }
8810 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008811 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008812 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008813 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008814 ErrorFound = NotTwoSubstatements;
8815 }
8816 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008817 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008818 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008819 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008820 ErrorFound = NotACompoundStatement;
8821 }
8822 if (ErrorFound != NoError) {
8823 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
8824 << ErrorRange;
8825 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8826 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008827 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008828 if (CurContext->isDependentContext())
8829 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00008830 }
Alexey Bataevdea47612014-07-23 07:46:59 +00008831 }
Alexey Bataev0162e452014-07-22 10:10:35 +00008832
Reid Kleckner87a31802018-03-12 21:43:02 +00008833 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00008834
Alexey Bataev62cec442014-11-18 10:14:22 +00008835 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00008836 X, V, E, UE, IsXLHSInRHSPart,
8837 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00008838}
8839
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008840StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8841 Stmt *AStmt,
8842 SourceLocation StartLoc,
8843 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008844 if (!AStmt)
8845 return StmtError();
8846
Alexey Bataeve3727102018-04-18 15:57:46 +00008847 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00008848 // 1.2.2 OpenMP Language Terminology
8849 // Structured block - An executable statement with a single entry at the
8850 // top and a single exit at the bottom.
8851 // The point of exit cannot be a branch out of the structured block.
8852 // longjmp() and throw() must not violate the entry/exit criteria.
8853 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008854 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
8855 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8856 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8857 // 1.2.2 OpenMP Language Terminology
8858 // Structured block - An executable statement with a single entry at the
8859 // top and a single exit at the bottom.
8860 // The point of exit cannot be a branch out of the structured block.
8861 // longjmp() and throw() must not violate the entry/exit criteria.
8862 CS->getCapturedDecl()->setNothrow();
8863 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008864
Alexey Bataev13314bf2014-10-09 04:18:56 +00008865 // OpenMP [2.16, Nesting of Regions]
8866 // If specified, a teams construct must be contained within a target
8867 // construct. That target construct must contain no statements or directives
8868 // outside of the teams construct.
8869 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008870 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008871 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008872 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00008873 auto I = CS->body_begin();
8874 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008875 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00008876 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
8877 OMPTeamsFound) {
8878
Alexey Bataev13314bf2014-10-09 04:18:56 +00008879 OMPTeamsFound = false;
8880 break;
8881 }
8882 ++I;
8883 }
8884 assert(I != CS->body_end() && "Not found statement");
8885 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00008886 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008887 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00008888 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00008889 }
8890 if (!OMPTeamsFound) {
8891 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
8892 Diag(DSAStack->getInnerTeamsRegionLoc(),
8893 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008894 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00008895 << isa<OMPExecutableDirective>(S);
8896 return StmtError();
8897 }
8898 }
8899
Reid Kleckner87a31802018-03-12 21:43:02 +00008900 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008901
8902 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8903}
8904
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008905StmtResult
8906Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8907 Stmt *AStmt, SourceLocation StartLoc,
8908 SourceLocation EndLoc) {
8909 if (!AStmt)
8910 return StmtError();
8911
Alexey Bataeve3727102018-04-18 15:57:46 +00008912 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008913 // 1.2.2 OpenMP Language Terminology
8914 // Structured block - An executable statement with a single entry at the
8915 // top and a single exit at the bottom.
8916 // The point of exit cannot be a branch out of the structured block.
8917 // longjmp() and throw() must not violate the entry/exit criteria.
8918 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008919 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8920 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8921 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8922 // 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();
8928 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008929
Reid Kleckner87a31802018-03-12 21:43:02 +00008930 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008931
8932 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8933 AStmt);
8934}
8935
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008936StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
8937 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008938 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008939 if (!AStmt)
8940 return StmtError();
8941
Alexey Bataeve3727102018-04-18 15:57:46 +00008942 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008943 // 1.2.2 OpenMP Language Terminology
8944 // Structured block - An executable statement with a single entry at the
8945 // top and a single exit at the bottom.
8946 // The point of exit cannot be a branch out of the structured block.
8947 // longjmp() and throw() must not violate the entry/exit criteria.
8948 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008949 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8950 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8951 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8952 // 1.2.2 OpenMP Language Terminology
8953 // Structured block - An executable statement with a single entry at the
8954 // top and a single exit at the bottom.
8955 // The point of exit cannot be a branch out of the structured block.
8956 // longjmp() and throw() must not violate the entry/exit criteria.
8957 CS->getCapturedDecl()->setNothrow();
8958 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008959
8960 OMPLoopDirective::HelperExprs B;
8961 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8962 // define the nested loops number.
8963 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008964 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008965 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008966 VarsWithImplicitDSA, B);
8967 if (NestedLoopCount == 0)
8968 return StmtError();
8969
8970 assert((CurContext->isDependentContext() || B.builtAll()) &&
8971 "omp target parallel for loop exprs were not built");
8972
8973 if (!CurContext->isDependentContext()) {
8974 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008975 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008976 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008977 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008978 B.NumIterations, *this, CurScope,
8979 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008980 return StmtError();
8981 }
8982 }
8983
Reid Kleckner87a31802018-03-12 21:43:02 +00008984 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008985 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8986 NestedLoopCount, Clauses, AStmt,
8987 B, DSAStack->isCancelRegion());
8988}
8989
Alexey Bataev95b64a92017-05-30 16:00:04 +00008990/// Check for existence of a map clause in the list of clauses.
8991static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8992 const OpenMPClauseKind K) {
8993 return llvm::any_of(
8994 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8995}
Samuel Antaodf67fc42016-01-19 19:15:56 +00008996
Alexey Bataev95b64a92017-05-30 16:00:04 +00008997template <typename... Params>
8998static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
8999 const Params... ClauseTypes) {
9000 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009001}
9002
Michael Wong65f367f2015-07-21 13:44:28 +00009003StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9004 Stmt *AStmt,
9005 SourceLocation StartLoc,
9006 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009007 if (!AStmt)
9008 return StmtError();
9009
9010 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9011
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009012 // OpenMP [2.10.1, Restrictions, p. 97]
9013 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009014 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9015 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9016 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009017 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009018 return StmtError();
9019 }
9020
Reid Kleckner87a31802018-03-12 21:43:02 +00009021 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009022
9023 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9024 AStmt);
9025}
9026
Samuel Antaodf67fc42016-01-19 19:15:56 +00009027StmtResult
9028Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9029 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009030 SourceLocation EndLoc, Stmt *AStmt) {
9031 if (!AStmt)
9032 return StmtError();
9033
Alexey Bataeve3727102018-04-18 15:57:46 +00009034 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009035 // 1.2.2 OpenMP Language Terminology
9036 // Structured block - An executable statement with a single entry at the
9037 // top and a single exit at the bottom.
9038 // The point of exit cannot be a branch out of the structured block.
9039 // longjmp() and throw() must not violate the entry/exit criteria.
9040 CS->getCapturedDecl()->setNothrow();
9041 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9042 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9043 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9044 // 1.2.2 OpenMP Language Terminology
9045 // Structured block - An executable statement with a single entry at the
9046 // top and a single exit at the bottom.
9047 // The point of exit cannot be a branch out of the structured block.
9048 // longjmp() and throw() must not violate the entry/exit criteria.
9049 CS->getCapturedDecl()->setNothrow();
9050 }
9051
Samuel Antaodf67fc42016-01-19 19:15:56 +00009052 // OpenMP [2.10.2, Restrictions, p. 99]
9053 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009054 if (!hasClauses(Clauses, OMPC_map)) {
9055 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9056 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009057 return StmtError();
9058 }
9059
Alexey Bataev7828b252017-11-21 17:08:48 +00009060 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9061 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009062}
9063
Samuel Antao72590762016-01-19 20:04:50 +00009064StmtResult
9065Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9066 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009067 SourceLocation EndLoc, Stmt *AStmt) {
9068 if (!AStmt)
9069 return StmtError();
9070
Alexey Bataeve3727102018-04-18 15:57:46 +00009071 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009072 // 1.2.2 OpenMP Language Terminology
9073 // Structured block - An executable statement with a single entry at the
9074 // top and a single exit at the bottom.
9075 // The point of exit cannot be a branch out of the structured block.
9076 // longjmp() and throw() must not violate the entry/exit criteria.
9077 CS->getCapturedDecl()->setNothrow();
9078 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9079 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9080 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9081 // 1.2.2 OpenMP Language Terminology
9082 // Structured block - An executable statement with a single entry at the
9083 // top and a single exit at the bottom.
9084 // The point of exit cannot be a branch out of the structured block.
9085 // longjmp() and throw() must not violate the entry/exit criteria.
9086 CS->getCapturedDecl()->setNothrow();
9087 }
9088
Samuel Antao72590762016-01-19 20:04:50 +00009089 // OpenMP [2.10.3, Restrictions, p. 102]
9090 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009091 if (!hasClauses(Clauses, OMPC_map)) {
9092 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9093 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009094 return StmtError();
9095 }
9096
Alexey Bataev7828b252017-11-21 17:08:48 +00009097 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9098 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009099}
9100
Samuel Antao686c70c2016-05-26 17:30:50 +00009101StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9102 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009103 SourceLocation EndLoc,
9104 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_update);
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
Alexey Bataev95b64a92017-05-30 16:00:04 +00009126 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009127 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9128 return StmtError();
9129 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009130 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9131 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009132}
9133
Alexey Bataev13314bf2014-10-09 04:18:56 +00009134StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9135 Stmt *AStmt, SourceLocation StartLoc,
9136 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009137 if (!AStmt)
9138 return StmtError();
9139
Alexey Bataeve3727102018-04-18 15:57:46 +00009140 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009141 // 1.2.2 OpenMP Language Terminology
9142 // Structured block - An executable statement with a single entry at the
9143 // top and a single exit at the bottom.
9144 // The point of exit cannot be a branch out of the structured block.
9145 // longjmp() and throw() must not violate the entry/exit criteria.
9146 CS->getCapturedDecl()->setNothrow();
9147
Reid Kleckner87a31802018-03-12 21:43:02 +00009148 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009149
Alexey Bataevceabd412017-11-30 18:01:54 +00009150 DSAStack->setParentTeamsRegionLoc(StartLoc);
9151
Alexey Bataev13314bf2014-10-09 04:18:56 +00009152 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9153}
9154
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009155StmtResult
9156Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9157 SourceLocation EndLoc,
9158 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009159 if (DSAStack->isParentNowaitRegion()) {
9160 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9161 return StmtError();
9162 }
9163 if (DSAStack->isParentOrderedRegion()) {
9164 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9165 return StmtError();
9166 }
9167 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9168 CancelRegion);
9169}
9170
Alexey Bataev87933c72015-09-18 08:07:34 +00009171StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9172 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009173 SourceLocation EndLoc,
9174 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009175 if (DSAStack->isParentNowaitRegion()) {
9176 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9177 return StmtError();
9178 }
9179 if (DSAStack->isParentOrderedRegion()) {
9180 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9181 return StmtError();
9182 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009183 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009184 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9185 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009186}
9187
Alexey Bataev382967a2015-12-08 12:06:20 +00009188static bool checkGrainsizeNumTasksClauses(Sema &S,
9189 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009190 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009191 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009192 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009193 if (C->getClauseKind() == OMPC_grainsize ||
9194 C->getClauseKind() == OMPC_num_tasks) {
9195 if (!PrevClause)
9196 PrevClause = C;
9197 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009198 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009199 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9200 << getOpenMPClauseName(C->getClauseKind())
9201 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009202 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009203 diag::note_omp_previous_grainsize_num_tasks)
9204 << getOpenMPClauseName(PrevClause->getClauseKind());
9205 ErrorFound = true;
9206 }
9207 }
9208 }
9209 return ErrorFound;
9210}
9211
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009212static bool checkReductionClauseWithNogroup(Sema &S,
9213 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009214 const OMPClause *ReductionClause = nullptr;
9215 const OMPClause *NogroupClause = nullptr;
9216 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009217 if (C->getClauseKind() == OMPC_reduction) {
9218 ReductionClause = C;
9219 if (NogroupClause)
9220 break;
9221 continue;
9222 }
9223 if (C->getClauseKind() == OMPC_nogroup) {
9224 NogroupClause = C;
9225 if (ReductionClause)
9226 break;
9227 continue;
9228 }
9229 }
9230 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009231 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9232 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009233 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009234 return true;
9235 }
9236 return false;
9237}
9238
Alexey Bataev49f6e782015-12-01 04:18:41 +00009239StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9240 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009241 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009242 if (!AStmt)
9243 return StmtError();
9244
9245 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9246 OMPLoopDirective::HelperExprs B;
9247 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9248 // define the nested loops number.
9249 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009250 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009251 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009252 VarsWithImplicitDSA, B);
9253 if (NestedLoopCount == 0)
9254 return StmtError();
9255
9256 assert((CurContext->isDependentContext() || B.builtAll()) &&
9257 "omp for loop exprs were not built");
9258
Alexey Bataev382967a2015-12-08 12:06:20 +00009259 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9260 // The grainsize clause and num_tasks clause are mutually exclusive and may
9261 // not appear on the same taskloop directive.
9262 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9263 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009264 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9265 // If a reduction clause is present on the taskloop directive, the nogroup
9266 // clause must not be specified.
9267 if (checkReductionClauseWithNogroup(*this, Clauses))
9268 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009269
Reid Kleckner87a31802018-03-12 21:43:02 +00009270 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009271 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9272 NestedLoopCount, Clauses, AStmt, B);
9273}
9274
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009275StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9276 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009277 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009278 if (!AStmt)
9279 return StmtError();
9280
9281 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9282 OMPLoopDirective::HelperExprs B;
9283 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9284 // define the nested loops number.
9285 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009286 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009287 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9288 VarsWithImplicitDSA, B);
9289 if (NestedLoopCount == 0)
9290 return StmtError();
9291
9292 assert((CurContext->isDependentContext() || B.builtAll()) &&
9293 "omp for loop exprs were not built");
9294
Alexey Bataev5a3af132016-03-29 08:58:54 +00009295 if (!CurContext->isDependentContext()) {
9296 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009297 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009298 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009299 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009300 B.NumIterations, *this, CurScope,
9301 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009302 return StmtError();
9303 }
9304 }
9305
Alexey Bataev382967a2015-12-08 12:06:20 +00009306 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9307 // The grainsize clause and num_tasks clause are mutually exclusive and may
9308 // not appear on the same taskloop directive.
9309 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9310 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009311 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9312 // If a reduction clause is present on the taskloop directive, the nogroup
9313 // clause must not be specified.
9314 if (checkReductionClauseWithNogroup(*this, Clauses))
9315 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009316 if (checkSimdlenSafelenSpecified(*this, Clauses))
9317 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009318
Reid Kleckner87a31802018-03-12 21:43:02 +00009319 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009320 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9321 NestedLoopCount, Clauses, AStmt, B);
9322}
9323
Alexey Bataev60e51c42019-10-10 20:13:02 +00009324StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9325 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9326 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9327 if (!AStmt)
9328 return StmtError();
9329
9330 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9331 OMPLoopDirective::HelperExprs B;
9332 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9333 // define the nested loops number.
9334 unsigned NestedLoopCount =
9335 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9336 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9337 VarsWithImplicitDSA, B);
9338 if (NestedLoopCount == 0)
9339 return StmtError();
9340
9341 assert((CurContext->isDependentContext() || B.builtAll()) &&
9342 "omp for loop exprs were not built");
9343
9344 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9345 // The grainsize clause and num_tasks clause are mutually exclusive and may
9346 // not appear on the same taskloop directive.
9347 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9348 return StmtError();
9349 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9350 // If a reduction clause is present on the taskloop directive, the nogroup
9351 // clause must not be specified.
9352 if (checkReductionClauseWithNogroup(*this, Clauses))
9353 return StmtError();
9354
9355 setFunctionHasBranchProtectedScope();
9356 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9357 NestedLoopCount, Clauses, AStmt, B);
9358}
9359
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009360StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9361 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9362 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9363 if (!AStmt)
9364 return StmtError();
9365
9366 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9367 auto *CS = cast<CapturedStmt>(AStmt);
9368 // 1.2.2 OpenMP Language Terminology
9369 // Structured block - An executable statement with a single entry at the
9370 // top and a single exit at the bottom.
9371 // The point of exit cannot be a branch out of the structured block.
9372 // longjmp() and throw() must not violate the entry/exit criteria.
9373 CS->getCapturedDecl()->setNothrow();
9374 for (int ThisCaptureLevel =
9375 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9376 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9377 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9378 // 1.2.2 OpenMP Language Terminology
9379 // Structured block - An executable statement with a single entry at the
9380 // top and a single exit at the bottom.
9381 // The point of exit cannot be a branch out of the structured block.
9382 // longjmp() and throw() must not violate the entry/exit criteria.
9383 CS->getCapturedDecl()->setNothrow();
9384 }
9385
9386 OMPLoopDirective::HelperExprs B;
9387 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9388 // define the nested loops number.
9389 unsigned NestedLoopCount = checkOpenMPLoop(
9390 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9391 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9392 VarsWithImplicitDSA, B);
9393 if (NestedLoopCount == 0)
9394 return StmtError();
9395
9396 assert((CurContext->isDependentContext() || B.builtAll()) &&
9397 "omp for loop exprs were not built");
9398
9399 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9400 // The grainsize clause and num_tasks clause are mutually exclusive and may
9401 // not appear on the same taskloop directive.
9402 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9403 return StmtError();
9404 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9405 // If a reduction clause is present on the taskloop directive, the nogroup
9406 // clause must not be specified.
9407 if (checkReductionClauseWithNogroup(*this, Clauses))
9408 return StmtError();
9409
9410 setFunctionHasBranchProtectedScope();
9411 return OMPParallelMasterTaskLoopDirective::Create(
9412 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9413}
9414
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009415StmtResult Sema::ActOnOpenMPDistributeDirective(
9416 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009417 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009418 if (!AStmt)
9419 return StmtError();
9420
9421 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9422 OMPLoopDirective::HelperExprs B;
9423 // In presence of clause 'collapse' with number of loops, it will
9424 // define the nested loops number.
9425 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009426 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009427 nullptr /*ordered not a clause on distribute*/, AStmt,
9428 *this, *DSAStack, VarsWithImplicitDSA, B);
9429 if (NestedLoopCount == 0)
9430 return StmtError();
9431
9432 assert((CurContext->isDependentContext() || B.builtAll()) &&
9433 "omp for loop exprs were not built");
9434
Reid Kleckner87a31802018-03-12 21:43:02 +00009435 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009436 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9437 NestedLoopCount, Clauses, AStmt, B);
9438}
9439
Carlo Bertolli9925f152016-06-27 14:55:37 +00009440StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9441 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009442 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009443 if (!AStmt)
9444 return StmtError();
9445
Alexey Bataeve3727102018-04-18 15:57:46 +00009446 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009447 // 1.2.2 OpenMP Language Terminology
9448 // Structured block - An executable statement with a single entry at the
9449 // top and a single exit at the bottom.
9450 // The point of exit cannot be a branch out of the structured block.
9451 // longjmp() and throw() must not violate the entry/exit criteria.
9452 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009453 for (int ThisCaptureLevel =
9454 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9455 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9456 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9457 // 1.2.2 OpenMP Language Terminology
9458 // Structured block - An executable statement with a single entry at the
9459 // top and a single exit at the bottom.
9460 // The point of exit cannot be a branch out of the structured block.
9461 // longjmp() and throw() must not violate the entry/exit criteria.
9462 CS->getCapturedDecl()->setNothrow();
9463 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009464
9465 OMPLoopDirective::HelperExprs B;
9466 // In presence of clause 'collapse' with number of loops, it will
9467 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009468 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009469 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009470 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009471 VarsWithImplicitDSA, B);
9472 if (NestedLoopCount == 0)
9473 return StmtError();
9474
9475 assert((CurContext->isDependentContext() || B.builtAll()) &&
9476 "omp for loop exprs were not built");
9477
Reid Kleckner87a31802018-03-12 21:43:02 +00009478 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009479 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009480 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9481 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009482}
9483
Kelvin Li4a39add2016-07-05 05:00:15 +00009484StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009486 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009487 if (!AStmt)
9488 return StmtError();
9489
Alexey Bataeve3727102018-04-18 15:57:46 +00009490 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009491 // 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();
Alexey Bataev974acd62017-11-27 19:38:52 +00009497 for (int ThisCaptureLevel =
9498 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
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 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009508
9509 OMPLoopDirective::HelperExprs B;
9510 // In presence of clause 'collapse' with number of loops, it will
9511 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009512 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009513 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009514 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009515 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
Alexey Bataev438388c2017-11-22 18:34:02 +00009522 if (!CurContext->isDependentContext()) {
9523 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009524 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009525 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9526 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9527 B.NumIterations, *this, CurScope,
9528 DSAStack))
9529 return StmtError();
9530 }
9531 }
9532
Kelvin Lic5609492016-07-15 04:39:07 +00009533 if (checkSimdlenSafelenSpecified(*this, Clauses))
9534 return StmtError();
9535
Reid Kleckner87a31802018-03-12 21:43:02 +00009536 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009537 return OMPDistributeParallelForSimdDirective::Create(
9538 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9539}
9540
Kelvin Li787f3fc2016-07-06 04:45:38 +00009541StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9542 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009543 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009544 if (!AStmt)
9545 return StmtError();
9546
Alexey Bataeve3727102018-04-18 15:57:46 +00009547 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009548 // 1.2.2 OpenMP Language Terminology
9549 // Structured block - An executable statement with a single entry at the
9550 // top and a single exit at the bottom.
9551 // The point of exit cannot be a branch out of the structured block.
9552 // longjmp() and throw() must not violate the entry/exit criteria.
9553 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009554 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9555 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9556 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9557 // 1.2.2 OpenMP Language Terminology
9558 // Structured block - An executable statement with a single entry at the
9559 // top and a single exit at the bottom.
9560 // The point of exit cannot be a branch out of the structured block.
9561 // longjmp() and throw() must not violate the entry/exit criteria.
9562 CS->getCapturedDecl()->setNothrow();
9563 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009564
9565 OMPLoopDirective::HelperExprs B;
9566 // In presence of clause 'collapse' with number of loops, it will
9567 // define the nested loops number.
9568 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009569 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009570 nullptr /*ordered not a clause on distribute*/, CS, *this,
9571 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009572 if (NestedLoopCount == 0)
9573 return StmtError();
9574
9575 assert((CurContext->isDependentContext() || B.builtAll()) &&
9576 "omp for loop exprs were not built");
9577
Alexey Bataev438388c2017-11-22 18:34:02 +00009578 if (!CurContext->isDependentContext()) {
9579 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009580 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009581 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9582 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9583 B.NumIterations, *this, CurScope,
9584 DSAStack))
9585 return StmtError();
9586 }
9587 }
9588
Kelvin Lic5609492016-07-15 04:39:07 +00009589 if (checkSimdlenSafelenSpecified(*this, Clauses))
9590 return StmtError();
9591
Reid Kleckner87a31802018-03-12 21:43:02 +00009592 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009593 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9594 NestedLoopCount, Clauses, AStmt, B);
9595}
9596
Kelvin Lia579b912016-07-14 02:54:56 +00009597StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9598 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009599 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009600 if (!AStmt)
9601 return StmtError();
9602
Alexey Bataeve3727102018-04-18 15:57:46 +00009603 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009604 // 1.2.2 OpenMP Language Terminology
9605 // Structured block - An executable statement with a single entry at the
9606 // top and a single exit at the bottom.
9607 // The point of exit cannot be a branch out of the structured block.
9608 // longjmp() and throw() must not violate the entry/exit criteria.
9609 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009610 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9611 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9612 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9613 // 1.2.2 OpenMP Language Terminology
9614 // Structured block - An executable statement with a single entry at the
9615 // top and a single exit at the bottom.
9616 // The point of exit cannot be a branch out of the structured block.
9617 // longjmp() and throw() must not violate the entry/exit criteria.
9618 CS->getCapturedDecl()->setNothrow();
9619 }
Kelvin Lia579b912016-07-14 02:54:56 +00009620
9621 OMPLoopDirective::HelperExprs B;
9622 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9623 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009624 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00009625 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009626 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00009627 VarsWithImplicitDSA, B);
9628 if (NestedLoopCount == 0)
9629 return StmtError();
9630
9631 assert((CurContext->isDependentContext() || B.builtAll()) &&
9632 "omp target parallel for simd loop exprs were not built");
9633
9634 if (!CurContext->isDependentContext()) {
9635 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009636 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009637 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00009638 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9639 B.NumIterations, *this, CurScope,
9640 DSAStack))
9641 return StmtError();
9642 }
9643 }
Kelvin Lic5609492016-07-15 04:39:07 +00009644 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00009645 return StmtError();
9646
Reid Kleckner87a31802018-03-12 21:43:02 +00009647 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00009648 return OMPTargetParallelForSimdDirective::Create(
9649 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9650}
9651
Kelvin Li986330c2016-07-20 22:57:10 +00009652StmtResult Sema::ActOnOpenMPTargetSimdDirective(
9653 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009654 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00009655 if (!AStmt)
9656 return StmtError();
9657
Alexey Bataeve3727102018-04-18 15:57:46 +00009658 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00009659 // 1.2.2 OpenMP Language Terminology
9660 // Structured block - An executable statement with a single entry at the
9661 // top and a single exit at the bottom.
9662 // The point of exit cannot be a branch out of the structured block.
9663 // longjmp() and throw() must not violate the entry/exit criteria.
9664 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00009665 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
9666 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9667 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9668 // 1.2.2 OpenMP Language Terminology
9669 // Structured block - An executable statement with a single entry at the
9670 // top and a single exit at the bottom.
9671 // The point of exit cannot be a branch out of the structured block.
9672 // longjmp() and throw() must not violate the entry/exit criteria.
9673 CS->getCapturedDecl()->setNothrow();
9674 }
9675
Kelvin Li986330c2016-07-20 22:57:10 +00009676 OMPLoopDirective::HelperExprs B;
9677 // In presence of clause 'collapse' with number of loops, it will define the
9678 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00009679 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009680 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00009681 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00009682 VarsWithImplicitDSA, B);
9683 if (NestedLoopCount == 0)
9684 return StmtError();
9685
9686 assert((CurContext->isDependentContext() || B.builtAll()) &&
9687 "omp target simd loop exprs were not built");
9688
9689 if (!CurContext->isDependentContext()) {
9690 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009691 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009692 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00009693 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9694 B.NumIterations, *this, CurScope,
9695 DSAStack))
9696 return StmtError();
9697 }
9698 }
9699
9700 if (checkSimdlenSafelenSpecified(*this, Clauses))
9701 return StmtError();
9702
Reid Kleckner87a31802018-03-12 21:43:02 +00009703 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00009704 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
9705 NestedLoopCount, Clauses, AStmt, B);
9706}
9707
Kelvin Li02532872016-08-05 14:37:37 +00009708StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
9709 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009710 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00009711 if (!AStmt)
9712 return StmtError();
9713
Alexey Bataeve3727102018-04-18 15:57:46 +00009714 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00009715 // 1.2.2 OpenMP Language Terminology
9716 // Structured block - An executable statement with a single entry at the
9717 // top and a single exit at the bottom.
9718 // The point of exit cannot be a branch out of the structured block.
9719 // longjmp() and throw() must not violate the entry/exit criteria.
9720 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009721 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
9722 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9723 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9724 // 1.2.2 OpenMP Language Terminology
9725 // Structured block - An executable statement with a single entry at the
9726 // top and a single exit at the bottom.
9727 // The point of exit cannot be a branch out of the structured block.
9728 // longjmp() and throw() must not violate the entry/exit criteria.
9729 CS->getCapturedDecl()->setNothrow();
9730 }
Kelvin Li02532872016-08-05 14:37:37 +00009731
9732 OMPLoopDirective::HelperExprs B;
9733 // In presence of clause 'collapse' with number of loops, it will
9734 // define the nested loops number.
9735 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009736 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009737 nullptr /*ordered not a clause on distribute*/, CS, *this,
9738 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00009739 if (NestedLoopCount == 0)
9740 return StmtError();
9741
9742 assert((CurContext->isDependentContext() || B.builtAll()) &&
9743 "omp teams distribute loop exprs were not built");
9744
Reid Kleckner87a31802018-03-12 21:43:02 +00009745 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009746
9747 DSAStack->setParentTeamsRegionLoc(StartLoc);
9748
David Majnemer9d168222016-08-05 17:44:54 +00009749 return OMPTeamsDistributeDirective::Create(
9750 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00009751}
9752
Kelvin Li4e325f72016-10-25 12:50:55 +00009753StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
9754 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009755 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009756 if (!AStmt)
9757 return StmtError();
9758
Alexey Bataeve3727102018-04-18 15:57:46 +00009759 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00009760 // 1.2.2 OpenMP Language Terminology
9761 // Structured block - An executable statement with a single entry at the
9762 // top and a single exit at the bottom.
9763 // The point of exit cannot be a branch out of the structured block.
9764 // longjmp() and throw() must not violate the entry/exit criteria.
9765 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00009766 for (int ThisCaptureLevel =
9767 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
9768 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9769 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9770 // 1.2.2 OpenMP Language Terminology
9771 // Structured block - An executable statement with a single entry at the
9772 // top and a single exit at the bottom.
9773 // The point of exit cannot be a branch out of the structured block.
9774 // longjmp() and throw() must not violate the entry/exit criteria.
9775 CS->getCapturedDecl()->setNothrow();
9776 }
9777
Kelvin Li4e325f72016-10-25 12:50:55 +00009778
9779 OMPLoopDirective::HelperExprs B;
9780 // In presence of clause 'collapse' with number of loops, it will
9781 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009782 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00009783 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00009784 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00009785 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00009786
9787 if (NestedLoopCount == 0)
9788 return StmtError();
9789
9790 assert((CurContext->isDependentContext() || B.builtAll()) &&
9791 "omp teams distribute simd loop exprs were not built");
9792
9793 if (!CurContext->isDependentContext()) {
9794 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009795 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009796 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9797 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9798 B.NumIterations, *this, CurScope,
9799 DSAStack))
9800 return StmtError();
9801 }
9802 }
9803
9804 if (checkSimdlenSafelenSpecified(*this, Clauses))
9805 return StmtError();
9806
Reid Kleckner87a31802018-03-12 21:43:02 +00009807 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009808
9809 DSAStack->setParentTeamsRegionLoc(StartLoc);
9810
Kelvin Li4e325f72016-10-25 12:50:55 +00009811 return OMPTeamsDistributeSimdDirective::Create(
9812 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9813}
9814
Kelvin Li579e41c2016-11-30 23:51:03 +00009815StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9816 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009817 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009818 if (!AStmt)
9819 return StmtError();
9820
Alexey Bataeve3727102018-04-18 15:57:46 +00009821 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00009822 // 1.2.2 OpenMP Language Terminology
9823 // Structured block - An executable statement with a single entry at the
9824 // top and a single exit at the bottom.
9825 // The point of exit cannot be a branch out of the structured block.
9826 // longjmp() and throw() must not violate the entry/exit criteria.
9827 CS->getCapturedDecl()->setNothrow();
9828
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009829 for (int ThisCaptureLevel =
9830 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
9831 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9832 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9833 // 1.2.2 OpenMP Language Terminology
9834 // Structured block - An executable statement with a single entry at the
9835 // top and a single exit at the bottom.
9836 // The point of exit cannot be a branch out of the structured block.
9837 // longjmp() and throw() must not violate the entry/exit criteria.
9838 CS->getCapturedDecl()->setNothrow();
9839 }
9840
Kelvin Li579e41c2016-11-30 23:51:03 +00009841 OMPLoopDirective::HelperExprs B;
9842 // In presence of clause 'collapse' with number of loops, it will
9843 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009844 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00009845 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009846 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00009847 VarsWithImplicitDSA, B);
9848
9849 if (NestedLoopCount == 0)
9850 return StmtError();
9851
9852 assert((CurContext->isDependentContext() || B.builtAll()) &&
9853 "omp for loop exprs were not built");
9854
9855 if (!CurContext->isDependentContext()) {
9856 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009857 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009858 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9859 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9860 B.NumIterations, *this, CurScope,
9861 DSAStack))
9862 return StmtError();
9863 }
9864 }
9865
9866 if (checkSimdlenSafelenSpecified(*this, Clauses))
9867 return StmtError();
9868
Reid Kleckner87a31802018-03-12 21:43:02 +00009869 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009870
9871 DSAStack->setParentTeamsRegionLoc(StartLoc);
9872
Kelvin Li579e41c2016-11-30 23:51:03 +00009873 return OMPTeamsDistributeParallelForSimdDirective::Create(
9874 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9875}
9876
Kelvin Li7ade93f2016-12-09 03:24:30 +00009877StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
9878 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009879 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00009880 if (!AStmt)
9881 return StmtError();
9882
Alexey Bataeve3727102018-04-18 15:57:46 +00009883 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00009884 // 1.2.2 OpenMP Language Terminology
9885 // Structured block - An executable statement with a single entry at the
9886 // top and a single exit at the bottom.
9887 // The point of exit cannot be a branch out of the structured block.
9888 // longjmp() and throw() must not violate the entry/exit criteria.
9889 CS->getCapturedDecl()->setNothrow();
9890
Carlo Bertolli62fae152017-11-20 20:46:39 +00009891 for (int ThisCaptureLevel =
9892 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
9893 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9894 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9895 // 1.2.2 OpenMP Language Terminology
9896 // Structured block - An executable statement with a single entry at the
9897 // top and a single exit at the bottom.
9898 // The point of exit cannot be a branch out of the structured block.
9899 // longjmp() and throw() must not violate the entry/exit criteria.
9900 CS->getCapturedDecl()->setNothrow();
9901 }
9902
Kelvin Li7ade93f2016-12-09 03:24:30 +00009903 OMPLoopDirective::HelperExprs B;
9904 // In presence of clause 'collapse' with number of loops, it will
9905 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009906 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00009907 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00009908 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00009909 VarsWithImplicitDSA, B);
9910
9911 if (NestedLoopCount == 0)
9912 return StmtError();
9913
9914 assert((CurContext->isDependentContext() || B.builtAll()) &&
9915 "omp for loop exprs were not built");
9916
Reid Kleckner87a31802018-03-12 21:43:02 +00009917 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009918
9919 DSAStack->setParentTeamsRegionLoc(StartLoc);
9920
Kelvin Li7ade93f2016-12-09 03:24:30 +00009921 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009922 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9923 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00009924}
9925
Kelvin Libf594a52016-12-17 05:48:59 +00009926StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9927 Stmt *AStmt,
9928 SourceLocation StartLoc,
9929 SourceLocation EndLoc) {
9930 if (!AStmt)
9931 return StmtError();
9932
Alexey Bataeve3727102018-04-18 15:57:46 +00009933 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00009934 // 1.2.2 OpenMP Language Terminology
9935 // Structured block - An executable statement with a single entry at the
9936 // top and a single exit at the bottom.
9937 // The point of exit cannot be a branch out of the structured block.
9938 // longjmp() and throw() must not violate the entry/exit criteria.
9939 CS->getCapturedDecl()->setNothrow();
9940
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00009941 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
9942 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9943 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9944 // 1.2.2 OpenMP Language Terminology
9945 // Structured block - An executable statement with a single entry at the
9946 // top and a single exit at the bottom.
9947 // The point of exit cannot be a branch out of the structured block.
9948 // longjmp() and throw() must not violate the entry/exit criteria.
9949 CS->getCapturedDecl()->setNothrow();
9950 }
Reid Kleckner87a31802018-03-12 21:43:02 +00009951 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00009952
9953 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
9954 AStmt);
9955}
9956
Kelvin Li83c451e2016-12-25 04:52:54 +00009957StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
9958 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009959 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00009960 if (!AStmt)
9961 return StmtError();
9962
Alexey Bataeve3727102018-04-18 15:57:46 +00009963 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00009964 // 1.2.2 OpenMP Language Terminology
9965 // Structured block - An executable statement with a single entry at the
9966 // top and a single exit at the bottom.
9967 // The point of exit cannot be a branch out of the structured block.
9968 // longjmp() and throw() must not violate the entry/exit criteria.
9969 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00009970 for (int ThisCaptureLevel =
9971 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
9972 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9973 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9974 // 1.2.2 OpenMP Language Terminology
9975 // Structured block - An executable statement with a single entry at the
9976 // top and a single exit at the bottom.
9977 // The point of exit cannot be a branch out of the structured block.
9978 // longjmp() and throw() must not violate the entry/exit criteria.
9979 CS->getCapturedDecl()->setNothrow();
9980 }
Kelvin Li83c451e2016-12-25 04:52:54 +00009981
9982 OMPLoopDirective::HelperExprs B;
9983 // In presence of clause 'collapse' with number of loops, it will
9984 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009985 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00009986 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
9987 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00009988 VarsWithImplicitDSA, B);
9989 if (NestedLoopCount == 0)
9990 return StmtError();
9991
9992 assert((CurContext->isDependentContext() || B.builtAll()) &&
9993 "omp target teams distribute loop exprs were not built");
9994
Reid Kleckner87a31802018-03-12 21:43:02 +00009995 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00009996 return OMPTargetTeamsDistributeDirective::Create(
9997 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9998}
9999
Kelvin Li80e8f562016-12-29 22:16:30 +000010000StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10001 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010002 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010003 if (!AStmt)
10004 return StmtError();
10005
Alexey Bataeve3727102018-04-18 15:57:46 +000010006 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010007 // 1.2.2 OpenMP Language Terminology
10008 // Structured block - An executable statement with a single entry at the
10009 // top and a single exit at the bottom.
10010 // The point of exit cannot be a branch out of the structured block.
10011 // longjmp() and throw() must not violate the entry/exit criteria.
10012 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010013 for (int ThisCaptureLevel =
10014 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10015 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10016 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10017 // 1.2.2 OpenMP Language Terminology
10018 // Structured block - An executable statement with a single entry at the
10019 // top and a single exit at the bottom.
10020 // The point of exit cannot be a branch out of the structured block.
10021 // longjmp() and throw() must not violate the entry/exit criteria.
10022 CS->getCapturedDecl()->setNothrow();
10023 }
10024
Kelvin Li80e8f562016-12-29 22:16:30 +000010025 OMPLoopDirective::HelperExprs B;
10026 // In presence of clause 'collapse' with number of loops, it will
10027 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010028 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010029 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10030 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010031 VarsWithImplicitDSA, B);
10032 if (NestedLoopCount == 0)
10033 return StmtError();
10034
10035 assert((CurContext->isDependentContext() || B.builtAll()) &&
10036 "omp target teams distribute parallel for loop exprs were not built");
10037
Alexey Bataev647dd842018-01-15 20:59:40 +000010038 if (!CurContext->isDependentContext()) {
10039 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010040 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010041 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10042 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10043 B.NumIterations, *this, CurScope,
10044 DSAStack))
10045 return StmtError();
10046 }
10047 }
10048
Reid Kleckner87a31802018-03-12 21:43:02 +000010049 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010050 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010051 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10052 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010053}
10054
Kelvin Li1851df52017-01-03 05:23:48 +000010055StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10056 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010057 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010058 if (!AStmt)
10059 return StmtError();
10060
Alexey Bataeve3727102018-04-18 15:57:46 +000010061 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010062 // 1.2.2 OpenMP Language Terminology
10063 // Structured block - An executable statement with a single entry at the
10064 // top and a single exit at the bottom.
10065 // The point of exit cannot be a branch out of the structured block.
10066 // longjmp() and throw() must not violate the entry/exit criteria.
10067 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010068 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10069 OMPD_target_teams_distribute_parallel_for_simd);
10070 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10071 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10072 // 1.2.2 OpenMP Language Terminology
10073 // Structured block - An executable statement with a single entry at the
10074 // top and a single exit at the bottom.
10075 // The point of exit cannot be a branch out of the structured block.
10076 // longjmp() and throw() must not violate the entry/exit criteria.
10077 CS->getCapturedDecl()->setNothrow();
10078 }
Kelvin Li1851df52017-01-03 05:23:48 +000010079
10080 OMPLoopDirective::HelperExprs B;
10081 // In presence of clause 'collapse' with number of loops, it will
10082 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010083 unsigned NestedLoopCount =
10084 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010085 getCollapseNumberExpr(Clauses),
10086 nullptr /*ordered not a clause on distribute*/, CS, *this,
10087 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010088 if (NestedLoopCount == 0)
10089 return StmtError();
10090
10091 assert((CurContext->isDependentContext() || B.builtAll()) &&
10092 "omp target teams distribute parallel for simd loop exprs were not "
10093 "built");
10094
10095 if (!CurContext->isDependentContext()) {
10096 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010097 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010098 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10099 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10100 B.NumIterations, *this, CurScope,
10101 DSAStack))
10102 return StmtError();
10103 }
10104 }
10105
Alexey Bataev438388c2017-11-22 18:34:02 +000010106 if (checkSimdlenSafelenSpecified(*this, Clauses))
10107 return StmtError();
10108
Reid Kleckner87a31802018-03-12 21:43:02 +000010109 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010110 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10111 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10112}
10113
Kelvin Lida681182017-01-10 18:08:18 +000010114StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10115 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010116 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010117 if (!AStmt)
10118 return StmtError();
10119
10120 auto *CS = cast<CapturedStmt>(AStmt);
10121 // 1.2.2 OpenMP Language Terminology
10122 // Structured block - An executable statement with a single entry at the
10123 // top and a single exit at the bottom.
10124 // The point of exit cannot be a branch out of the structured block.
10125 // longjmp() and throw() must not violate the entry/exit criteria.
10126 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010127 for (int ThisCaptureLevel =
10128 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10129 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10130 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10131 // 1.2.2 OpenMP Language Terminology
10132 // Structured block - An executable statement with a single entry at the
10133 // top and a single exit at the bottom.
10134 // The point of exit cannot be a branch out of the structured block.
10135 // longjmp() and throw() must not violate the entry/exit criteria.
10136 CS->getCapturedDecl()->setNothrow();
10137 }
Kelvin Lida681182017-01-10 18:08:18 +000010138
10139 OMPLoopDirective::HelperExprs B;
10140 // In presence of clause 'collapse' with number of loops, it will
10141 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010142 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010143 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010144 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010145 VarsWithImplicitDSA, B);
10146 if (NestedLoopCount == 0)
10147 return StmtError();
10148
10149 assert((CurContext->isDependentContext() || B.builtAll()) &&
10150 "omp target teams distribute simd loop exprs were not built");
10151
Alexey Bataev438388c2017-11-22 18:34:02 +000010152 if (!CurContext->isDependentContext()) {
10153 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010154 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010155 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10156 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10157 B.NumIterations, *this, CurScope,
10158 DSAStack))
10159 return StmtError();
10160 }
10161 }
10162
10163 if (checkSimdlenSafelenSpecified(*this, Clauses))
10164 return StmtError();
10165
Reid Kleckner87a31802018-03-12 21:43:02 +000010166 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010167 return OMPTargetTeamsDistributeSimdDirective::Create(
10168 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10169}
10170
Alexey Bataeved09d242014-05-28 05:53:51 +000010171OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010172 SourceLocation StartLoc,
10173 SourceLocation LParenLoc,
10174 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010175 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010176 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010177 case OMPC_final:
10178 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10179 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010180 case OMPC_num_threads:
10181 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10182 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010183 case OMPC_safelen:
10184 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10185 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010186 case OMPC_simdlen:
10187 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10188 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010189 case OMPC_allocator:
10190 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10191 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010192 case OMPC_collapse:
10193 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10194 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010195 case OMPC_ordered:
10196 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10197 break;
Michael Wonge710d542015-08-07 16:16:36 +000010198 case OMPC_device:
10199 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10200 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010201 case OMPC_num_teams:
10202 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10203 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010204 case OMPC_thread_limit:
10205 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10206 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010207 case OMPC_priority:
10208 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10209 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010210 case OMPC_grainsize:
10211 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10212 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010213 case OMPC_num_tasks:
10214 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10215 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010216 case OMPC_hint:
10217 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10218 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010219 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010220 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010221 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010222 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010223 case OMPC_private:
10224 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010225 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010226 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010227 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010228 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010229 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010230 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010231 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010232 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010233 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010234 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010235 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010236 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010237 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010238 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010239 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010240 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010241 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010242 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010243 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010244 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010245 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010246 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010247 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010248 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010249 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010250 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010251 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010252 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010253 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010254 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010255 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010256 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010257 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010258 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010259 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010260 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010261 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010262 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010263 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010264 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010265 llvm_unreachable("Clause is not allowed.");
10266 }
10267 return Res;
10268}
10269
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010270// An OpenMP directive such as 'target parallel' has two captured regions:
10271// for the 'target' and 'parallel' respectively. This function returns
10272// the region in which to capture expressions associated with a clause.
10273// A return value of OMPD_unknown signifies that the expression should not
10274// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010275static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10276 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10277 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010278 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010279 switch (CKind) {
10280 case OMPC_if:
10281 switch (DKind) {
10282 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010283 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010284 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010285 // If this clause applies to the nested 'parallel' region, capture within
10286 // the 'target' region, otherwise do not capture.
10287 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10288 CaptureRegion = OMPD_target;
10289 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010290 case OMPD_target_teams_distribute_parallel_for:
10291 case OMPD_target_teams_distribute_parallel_for_simd:
10292 // If this clause applies to the nested 'parallel' region, capture within
10293 // the 'teams' region, otherwise do not capture.
10294 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10295 CaptureRegion = OMPD_teams;
10296 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010297 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010298 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010299 CaptureRegion = OMPD_teams;
10300 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010301 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010302 case OMPD_target_enter_data:
10303 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010304 CaptureRegion = OMPD_task;
10305 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010306 case OMPD_parallel_master_taskloop:
10307 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10308 CaptureRegion = OMPD_parallel;
10309 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010310 case OMPD_cancel:
10311 case OMPD_parallel:
10312 case OMPD_parallel_sections:
10313 case OMPD_parallel_for:
10314 case OMPD_parallel_for_simd:
10315 case OMPD_target:
10316 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010317 case OMPD_target_teams:
10318 case OMPD_target_teams_distribute:
10319 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010320 case OMPD_distribute_parallel_for:
10321 case OMPD_distribute_parallel_for_simd:
10322 case OMPD_task:
10323 case OMPD_taskloop:
10324 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010325 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010326 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010327 // Do not capture if-clause expressions.
10328 break;
10329 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010330 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010331 case OMPD_taskyield:
10332 case OMPD_barrier:
10333 case OMPD_taskwait:
10334 case OMPD_cancellation_point:
10335 case OMPD_flush:
10336 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010337 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010338 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010339 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010340 case OMPD_declare_target:
10341 case OMPD_end_declare_target:
10342 case OMPD_teams:
10343 case OMPD_simd:
10344 case OMPD_for:
10345 case OMPD_for_simd:
10346 case OMPD_sections:
10347 case OMPD_section:
10348 case OMPD_single:
10349 case OMPD_master:
10350 case OMPD_critical:
10351 case OMPD_taskgroup:
10352 case OMPD_distribute:
10353 case OMPD_ordered:
10354 case OMPD_atomic:
10355 case OMPD_distribute_simd:
10356 case OMPD_teams_distribute:
10357 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010358 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010359 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10360 case OMPD_unknown:
10361 llvm_unreachable("Unknown OpenMP directive");
10362 }
10363 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010364 case OMPC_num_threads:
10365 switch (DKind) {
10366 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010367 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010368 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010369 CaptureRegion = OMPD_target;
10370 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010371 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010372 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010373 case OMPD_target_teams_distribute_parallel_for:
10374 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010375 CaptureRegion = OMPD_teams;
10376 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010377 case OMPD_parallel:
10378 case OMPD_parallel_sections:
10379 case OMPD_parallel_for:
10380 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010381 case OMPD_distribute_parallel_for:
10382 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010383 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010384 // Do not capture num_threads-clause expressions.
10385 break;
10386 case OMPD_target_data:
10387 case OMPD_target_enter_data:
10388 case OMPD_target_exit_data:
10389 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010390 case OMPD_target:
10391 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010392 case OMPD_target_teams:
10393 case OMPD_target_teams_distribute:
10394 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010395 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010396 case OMPD_task:
10397 case OMPD_taskloop:
10398 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010399 case OMPD_master_taskloop:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010400 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010401 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010402 case OMPD_taskyield:
10403 case OMPD_barrier:
10404 case OMPD_taskwait:
10405 case OMPD_cancellation_point:
10406 case OMPD_flush:
10407 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010408 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010409 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010410 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010411 case OMPD_declare_target:
10412 case OMPD_end_declare_target:
10413 case OMPD_teams:
10414 case OMPD_simd:
10415 case OMPD_for:
10416 case OMPD_for_simd:
10417 case OMPD_sections:
10418 case OMPD_section:
10419 case OMPD_single:
10420 case OMPD_master:
10421 case OMPD_critical:
10422 case OMPD_taskgroup:
10423 case OMPD_distribute:
10424 case OMPD_ordered:
10425 case OMPD_atomic:
10426 case OMPD_distribute_simd:
10427 case OMPD_teams_distribute:
10428 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010429 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010430 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10431 case OMPD_unknown:
10432 llvm_unreachable("Unknown OpenMP directive");
10433 }
10434 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010435 case OMPC_num_teams:
10436 switch (DKind) {
10437 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010438 case OMPD_target_teams_distribute:
10439 case OMPD_target_teams_distribute_simd:
10440 case OMPD_target_teams_distribute_parallel_for:
10441 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010442 CaptureRegion = OMPD_target;
10443 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010444 case OMPD_teams_distribute_parallel_for:
10445 case OMPD_teams_distribute_parallel_for_simd:
10446 case OMPD_teams:
10447 case OMPD_teams_distribute:
10448 case OMPD_teams_distribute_simd:
10449 // Do not capture num_teams-clause expressions.
10450 break;
10451 case OMPD_distribute_parallel_for:
10452 case OMPD_distribute_parallel_for_simd:
10453 case OMPD_task:
10454 case OMPD_taskloop:
10455 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010456 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010457 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010458 case OMPD_target_data:
10459 case OMPD_target_enter_data:
10460 case OMPD_target_exit_data:
10461 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010462 case OMPD_cancel:
10463 case OMPD_parallel:
10464 case OMPD_parallel_sections:
10465 case OMPD_parallel_for:
10466 case OMPD_parallel_for_simd:
10467 case OMPD_target:
10468 case OMPD_target_simd:
10469 case OMPD_target_parallel:
10470 case OMPD_target_parallel_for:
10471 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010472 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010473 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010474 case OMPD_taskyield:
10475 case OMPD_barrier:
10476 case OMPD_taskwait:
10477 case OMPD_cancellation_point:
10478 case OMPD_flush:
10479 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010480 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010481 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010482 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010483 case OMPD_declare_target:
10484 case OMPD_end_declare_target:
10485 case OMPD_simd:
10486 case OMPD_for:
10487 case OMPD_for_simd:
10488 case OMPD_sections:
10489 case OMPD_section:
10490 case OMPD_single:
10491 case OMPD_master:
10492 case OMPD_critical:
10493 case OMPD_taskgroup:
10494 case OMPD_distribute:
10495 case OMPD_ordered:
10496 case OMPD_atomic:
10497 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010498 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010499 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10500 case OMPD_unknown:
10501 llvm_unreachable("Unknown OpenMP directive");
10502 }
10503 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010504 case OMPC_thread_limit:
10505 switch (DKind) {
10506 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010507 case OMPD_target_teams_distribute:
10508 case OMPD_target_teams_distribute_simd:
10509 case OMPD_target_teams_distribute_parallel_for:
10510 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010511 CaptureRegion = OMPD_target;
10512 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010513 case OMPD_teams_distribute_parallel_for:
10514 case OMPD_teams_distribute_parallel_for_simd:
10515 case OMPD_teams:
10516 case OMPD_teams_distribute:
10517 case OMPD_teams_distribute_simd:
10518 // Do not capture thread_limit-clause expressions.
10519 break;
10520 case OMPD_distribute_parallel_for:
10521 case OMPD_distribute_parallel_for_simd:
10522 case OMPD_task:
10523 case OMPD_taskloop:
10524 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010525 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010526 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010527 case OMPD_target_data:
10528 case OMPD_target_enter_data:
10529 case OMPD_target_exit_data:
10530 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010531 case OMPD_cancel:
10532 case OMPD_parallel:
10533 case OMPD_parallel_sections:
10534 case OMPD_parallel_for:
10535 case OMPD_parallel_for_simd:
10536 case OMPD_target:
10537 case OMPD_target_simd:
10538 case OMPD_target_parallel:
10539 case OMPD_target_parallel_for:
10540 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010541 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010542 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010543 case OMPD_taskyield:
10544 case OMPD_barrier:
10545 case OMPD_taskwait:
10546 case OMPD_cancellation_point:
10547 case OMPD_flush:
10548 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010549 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010550 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010551 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010552 case OMPD_declare_target:
10553 case OMPD_end_declare_target:
10554 case OMPD_simd:
10555 case OMPD_for:
10556 case OMPD_for_simd:
10557 case OMPD_sections:
10558 case OMPD_section:
10559 case OMPD_single:
10560 case OMPD_master:
10561 case OMPD_critical:
10562 case OMPD_taskgroup:
10563 case OMPD_distribute:
10564 case OMPD_ordered:
10565 case OMPD_atomic:
10566 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010567 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010568 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10569 case OMPD_unknown:
10570 llvm_unreachable("Unknown OpenMP directive");
10571 }
10572 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010573 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010574 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010575 case OMPD_parallel_for:
10576 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010577 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010578 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010579 case OMPD_teams_distribute_parallel_for:
10580 case OMPD_teams_distribute_parallel_for_simd:
10581 case OMPD_target_parallel_for:
10582 case OMPD_target_parallel_for_simd:
10583 case OMPD_target_teams_distribute_parallel_for:
10584 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010585 CaptureRegion = OMPD_parallel;
10586 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010587 case OMPD_for:
10588 case OMPD_for_simd:
10589 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010590 break;
10591 case OMPD_task:
10592 case OMPD_taskloop:
10593 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010594 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010595 case OMPD_parallel_master_taskloop:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010596 case OMPD_target_data:
10597 case OMPD_target_enter_data:
10598 case OMPD_target_exit_data:
10599 case OMPD_target_update:
10600 case OMPD_teams:
10601 case OMPD_teams_distribute:
10602 case OMPD_teams_distribute_simd:
10603 case OMPD_target_teams_distribute:
10604 case OMPD_target_teams_distribute_simd:
10605 case OMPD_target:
10606 case OMPD_target_simd:
10607 case OMPD_target_parallel:
10608 case OMPD_cancel:
10609 case OMPD_parallel:
10610 case OMPD_parallel_sections:
10611 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010612 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010613 case OMPD_taskyield:
10614 case OMPD_barrier:
10615 case OMPD_taskwait:
10616 case OMPD_cancellation_point:
10617 case OMPD_flush:
10618 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010619 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010620 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010621 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010622 case OMPD_declare_target:
10623 case OMPD_end_declare_target:
10624 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010625 case OMPD_sections:
10626 case OMPD_section:
10627 case OMPD_single:
10628 case OMPD_master:
10629 case OMPD_critical:
10630 case OMPD_taskgroup:
10631 case OMPD_distribute:
10632 case OMPD_ordered:
10633 case OMPD_atomic:
10634 case OMPD_distribute_simd:
10635 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010636 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010637 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10638 case OMPD_unknown:
10639 llvm_unreachable("Unknown OpenMP directive");
10640 }
10641 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010642 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010643 switch (DKind) {
10644 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010645 case OMPD_teams_distribute_parallel_for_simd:
10646 case OMPD_teams_distribute:
10647 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010648 case OMPD_target_teams_distribute_parallel_for:
10649 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010650 case OMPD_target_teams_distribute:
10651 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010652 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010653 break;
10654 case OMPD_distribute_parallel_for:
10655 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010656 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010657 case OMPD_distribute_simd:
10658 // Do not capture thread_limit-clause expressions.
10659 break;
10660 case OMPD_parallel_for:
10661 case OMPD_parallel_for_simd:
10662 case OMPD_target_parallel_for_simd:
10663 case OMPD_target_parallel_for:
10664 case OMPD_task:
10665 case OMPD_taskloop:
10666 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010667 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010668 case OMPD_parallel_master_taskloop:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010669 case OMPD_target_data:
10670 case OMPD_target_enter_data:
10671 case OMPD_target_exit_data:
10672 case OMPD_target_update:
10673 case OMPD_teams:
10674 case OMPD_target:
10675 case OMPD_target_simd:
10676 case OMPD_target_parallel:
10677 case OMPD_cancel:
10678 case OMPD_parallel:
10679 case OMPD_parallel_sections:
10680 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010681 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010682 case OMPD_taskyield:
10683 case OMPD_barrier:
10684 case OMPD_taskwait:
10685 case OMPD_cancellation_point:
10686 case OMPD_flush:
10687 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010688 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010689 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010690 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010691 case OMPD_declare_target:
10692 case OMPD_end_declare_target:
10693 case OMPD_simd:
10694 case OMPD_for:
10695 case OMPD_for_simd:
10696 case OMPD_sections:
10697 case OMPD_section:
10698 case OMPD_single:
10699 case OMPD_master:
10700 case OMPD_critical:
10701 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010702 case OMPD_ordered:
10703 case OMPD_atomic:
10704 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010705 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010706 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10707 case OMPD_unknown:
10708 llvm_unreachable("Unknown OpenMP directive");
10709 }
10710 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010711 case OMPC_device:
10712 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010713 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010714 case OMPD_target_enter_data:
10715 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000010716 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000010717 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000010718 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000010719 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000010720 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000010721 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000010722 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000010723 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000010724 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000010725 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010726 CaptureRegion = OMPD_task;
10727 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010728 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010729 // Do not capture device-clause expressions.
10730 break;
10731 case OMPD_teams_distribute_parallel_for:
10732 case OMPD_teams_distribute_parallel_for_simd:
10733 case OMPD_teams:
10734 case OMPD_teams_distribute:
10735 case OMPD_teams_distribute_simd:
10736 case OMPD_distribute_parallel_for:
10737 case OMPD_distribute_parallel_for_simd:
10738 case OMPD_task:
10739 case OMPD_taskloop:
10740 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010741 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010742 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010743 case OMPD_cancel:
10744 case OMPD_parallel:
10745 case OMPD_parallel_sections:
10746 case OMPD_parallel_for:
10747 case OMPD_parallel_for_simd:
10748 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010749 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010750 case OMPD_taskyield:
10751 case OMPD_barrier:
10752 case OMPD_taskwait:
10753 case OMPD_cancellation_point:
10754 case OMPD_flush:
10755 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010756 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010757 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010758 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010759 case OMPD_declare_target:
10760 case OMPD_end_declare_target:
10761 case OMPD_simd:
10762 case OMPD_for:
10763 case OMPD_for_simd:
10764 case OMPD_sections:
10765 case OMPD_section:
10766 case OMPD_single:
10767 case OMPD_master:
10768 case OMPD_critical:
10769 case OMPD_taskgroup:
10770 case OMPD_distribute:
10771 case OMPD_ordered:
10772 case OMPD_atomic:
10773 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010774 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010775 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10776 case OMPD_unknown:
10777 llvm_unreachable("Unknown OpenMP directive");
10778 }
10779 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010780 case OMPC_grainsize:
10781 switch (DKind) {
10782 case OMPD_task:
10783 case OMPD_taskloop:
10784 case OMPD_taskloop_simd:
10785 case OMPD_master_taskloop:
10786 break;
10787 case OMPD_parallel_master_taskloop:
10788 CaptureRegion = OMPD_parallel;
10789 break;
10790 case OMPD_target_update:
10791 case OMPD_target_enter_data:
10792 case OMPD_target_exit_data:
10793 case OMPD_target:
10794 case OMPD_target_simd:
10795 case OMPD_target_teams:
10796 case OMPD_target_parallel:
10797 case OMPD_target_teams_distribute:
10798 case OMPD_target_teams_distribute_simd:
10799 case OMPD_target_parallel_for:
10800 case OMPD_target_parallel_for_simd:
10801 case OMPD_target_teams_distribute_parallel_for:
10802 case OMPD_target_teams_distribute_parallel_for_simd:
10803 case OMPD_target_data:
10804 case OMPD_teams_distribute_parallel_for:
10805 case OMPD_teams_distribute_parallel_for_simd:
10806 case OMPD_teams:
10807 case OMPD_teams_distribute:
10808 case OMPD_teams_distribute_simd:
10809 case OMPD_distribute_parallel_for:
10810 case OMPD_distribute_parallel_for_simd:
10811 case OMPD_cancel:
10812 case OMPD_parallel:
10813 case OMPD_parallel_sections:
10814 case OMPD_parallel_for:
10815 case OMPD_parallel_for_simd:
10816 case OMPD_threadprivate:
10817 case OMPD_allocate:
10818 case OMPD_taskyield:
10819 case OMPD_barrier:
10820 case OMPD_taskwait:
10821 case OMPD_cancellation_point:
10822 case OMPD_flush:
10823 case OMPD_declare_reduction:
10824 case OMPD_declare_mapper:
10825 case OMPD_declare_simd:
10826 case OMPD_declare_variant:
10827 case OMPD_declare_target:
10828 case OMPD_end_declare_target:
10829 case OMPD_simd:
10830 case OMPD_for:
10831 case OMPD_for_simd:
10832 case OMPD_sections:
10833 case OMPD_section:
10834 case OMPD_single:
10835 case OMPD_master:
10836 case OMPD_critical:
10837 case OMPD_taskgroup:
10838 case OMPD_distribute:
10839 case OMPD_ordered:
10840 case OMPD_atomic:
10841 case OMPD_distribute_simd:
10842 case OMPD_requires:
10843 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
10844 case OMPD_unknown:
10845 llvm_unreachable("Unknown OpenMP directive");
10846 }
10847 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010848 case OMPC_firstprivate:
10849 case OMPC_lastprivate:
10850 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010851 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010852 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010853 case OMPC_linear:
10854 case OMPC_default:
10855 case OMPC_proc_bind:
10856 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010857 case OMPC_safelen:
10858 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010859 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010860 case OMPC_collapse:
10861 case OMPC_private:
10862 case OMPC_shared:
10863 case OMPC_aligned:
10864 case OMPC_copyin:
10865 case OMPC_copyprivate:
10866 case OMPC_ordered:
10867 case OMPC_nowait:
10868 case OMPC_untied:
10869 case OMPC_mergeable:
10870 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010871 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010872 case OMPC_flush:
10873 case OMPC_read:
10874 case OMPC_write:
10875 case OMPC_update:
10876 case OMPC_capture:
10877 case OMPC_seq_cst:
10878 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010879 case OMPC_threads:
10880 case OMPC_simd:
10881 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010882 case OMPC_priority:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010883 case OMPC_nogroup:
10884 case OMPC_num_tasks:
10885 case OMPC_hint:
10886 case OMPC_defaultmap:
10887 case OMPC_unknown:
10888 case OMPC_uniform:
10889 case OMPC_to:
10890 case OMPC_from:
10891 case OMPC_use_device_ptr:
10892 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010893 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010894 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010895 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010896 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010897 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010898 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010899 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010900 llvm_unreachable("Unexpected OpenMP clause.");
10901 }
10902 return CaptureRegion;
10903}
10904
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010905OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10906 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010907 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010908 SourceLocation NameModifierLoc,
10909 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010910 SourceLocation EndLoc) {
10911 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010912 Stmt *HelperValStmt = nullptr;
10913 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010914 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10915 !Condition->isInstantiationDependent() &&
10916 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010917 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010918 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010919 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010920
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010921 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010922
10923 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10924 CaptureRegion =
10925 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000010926 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010927 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010928 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010929 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10930 HelperValStmt = buildPreInits(Context, Captures);
10931 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010932 }
10933
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010934 return new (Context)
10935 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
10936 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010937}
10938
Alexey Bataev3778b602014-07-17 07:32:53 +000010939OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
10940 SourceLocation StartLoc,
10941 SourceLocation LParenLoc,
10942 SourceLocation EndLoc) {
10943 Expr *ValExpr = Condition;
10944 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10945 !Condition->isInstantiationDependent() &&
10946 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010947 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000010948 if (Val.isInvalid())
10949 return nullptr;
10950
Richard Smith03a4aa32016-06-23 19:02:52 +000010951 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +000010952 }
10953
10954 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10955}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010956ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
10957 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000010958 if (!Op)
10959 return ExprError();
10960
10961 class IntConvertDiagnoser : public ICEConvertDiagnoser {
10962 public:
10963 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000010964 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000010965 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10966 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010967 return S.Diag(Loc, diag::err_omp_not_integral) << T;
10968 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010969 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
10970 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010971 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
10972 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010973 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
10974 QualType T,
10975 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010976 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
10977 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010978 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
10979 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010980 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000010981 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000010982 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010983 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10984 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010985 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
10986 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010987 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
10988 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010989 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000010990 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000010991 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010992 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
10993 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010994 llvm_unreachable("conversion functions are permitted");
10995 }
10996 } ConvertDiagnoser;
10997 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
10998}
10999
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011000static bool
11001isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11002 bool StrictlyPositive, bool BuildCapture = false,
11003 OpenMPDirectiveKind DKind = OMPD_unknown,
11004 OpenMPDirectiveKind *CaptureRegion = nullptr,
11005 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011006 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11007 !ValExpr->isInstantiationDependent()) {
11008 SourceLocation Loc = ValExpr->getExprLoc();
11009 ExprResult Value =
11010 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11011 if (Value.isInvalid())
11012 return false;
11013
11014 ValExpr = Value.get();
11015 // The expression must evaluate to a non-negative integer value.
11016 llvm::APSInt Result;
11017 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011018 Result.isSigned() &&
11019 !((!StrictlyPositive && Result.isNonNegative()) ||
11020 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011021 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011022 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11023 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011024 return false;
11025 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011026 if (!BuildCapture)
11027 return true;
11028 *CaptureRegion = getOpenMPCaptureRegionForClause(DKind, CKind);
11029 if (*CaptureRegion != OMPD_unknown &&
11030 !SemaRef.CurContext->isDependentContext()) {
11031 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11032 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11033 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11034 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11035 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011036 }
11037 return true;
11038}
11039
Alexey Bataev568a8332014-03-06 06:15:19 +000011040OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11041 SourceLocation StartLoc,
11042 SourceLocation LParenLoc,
11043 SourceLocation EndLoc) {
11044 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011045 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011046
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011047 // OpenMP [2.5, Restrictions]
11048 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011049 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011050 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011051 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011052
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011053 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011054 OpenMPDirectiveKind CaptureRegion =
11055 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
11056 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011057 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011058 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011059 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11060 HelperValStmt = buildPreInits(Context, Captures);
11061 }
11062
11063 return new (Context) OMPNumThreadsClause(
11064 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011065}
11066
Alexey Bataev62c87d22014-03-21 04:51:18 +000011067ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011068 OpenMPClauseKind CKind,
11069 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011070 if (!E)
11071 return ExprError();
11072 if (E->isValueDependent() || E->isTypeDependent() ||
11073 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011074 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011075 llvm::APSInt Result;
11076 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11077 if (ICE.isInvalid())
11078 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011079 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11080 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011081 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011082 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11083 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011084 return ExprError();
11085 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011086 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11087 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11088 << E->getSourceRange();
11089 return ExprError();
11090 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011091 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11092 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011093 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011094 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011095 return ICE;
11096}
11097
11098OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11099 SourceLocation LParenLoc,
11100 SourceLocation EndLoc) {
11101 // OpenMP [2.8.1, simd construct, Description]
11102 // The parameter of the safelen clause must be a constant
11103 // positive integer expression.
11104 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11105 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011106 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011107 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011108 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011109}
11110
Alexey Bataev66b15b52015-08-21 11:14:16 +000011111OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11112 SourceLocation LParenLoc,
11113 SourceLocation EndLoc) {
11114 // OpenMP [2.8.1, simd construct, Description]
11115 // The parameter of the simdlen clause must be a constant
11116 // positive integer expression.
11117 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11118 if (Simdlen.isInvalid())
11119 return nullptr;
11120 return new (Context)
11121 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11122}
11123
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011124/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011125static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11126 DSAStackTy *Stack) {
11127 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011128 if (!OMPAllocatorHandleT.isNull())
11129 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011130 // Build the predefined allocator expressions.
11131 bool ErrorFound = false;
11132 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11133 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11134 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11135 StringRef Allocator =
11136 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11137 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11138 auto *VD = dyn_cast_or_null<ValueDecl>(
11139 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11140 if (!VD) {
11141 ErrorFound = true;
11142 break;
11143 }
11144 QualType AllocatorType =
11145 VD->getType().getNonLValueExprType(S.getASTContext());
11146 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11147 if (!Res.isUsable()) {
11148 ErrorFound = true;
11149 break;
11150 }
11151 if (OMPAllocatorHandleT.isNull())
11152 OMPAllocatorHandleT = AllocatorType;
11153 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11154 ErrorFound = true;
11155 break;
11156 }
11157 Stack->setAllocator(AllocatorKind, Res.get());
11158 }
11159 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011160 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11161 return false;
11162 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011163 OMPAllocatorHandleT.addConst();
11164 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011165 return true;
11166}
11167
11168OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11169 SourceLocation LParenLoc,
11170 SourceLocation EndLoc) {
11171 // OpenMP [2.11.3, allocate Directive, Description]
11172 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011173 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011174 return nullptr;
11175
11176 ExprResult Allocator = DefaultLvalueConversion(A);
11177 if (Allocator.isInvalid())
11178 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011179 Allocator = PerformImplicitConversion(Allocator.get(),
11180 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011181 Sema::AA_Initializing,
11182 /*AllowExplicit=*/true);
11183 if (Allocator.isInvalid())
11184 return nullptr;
11185 return new (Context)
11186 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11187}
11188
Alexander Musman64d33f12014-06-04 07:53:32 +000011189OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11190 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011191 SourceLocation LParenLoc,
11192 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011193 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011194 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011195 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011196 // The parameter of the collapse clause must be a constant
11197 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011198 ExprResult NumForLoopsResult =
11199 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11200 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011201 return nullptr;
11202 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011203 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011204}
11205
Alexey Bataev10e775f2015-07-30 11:36:16 +000011206OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11207 SourceLocation EndLoc,
11208 SourceLocation LParenLoc,
11209 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011210 // OpenMP [2.7.1, loop construct, Description]
11211 // OpenMP [2.8.1, simd construct, Description]
11212 // OpenMP [2.9.6, distribute construct, Description]
11213 // The parameter of the ordered clause must be a constant
11214 // positive integer expression if any.
11215 if (NumForLoops && LParenLoc.isValid()) {
11216 ExprResult NumForLoopsResult =
11217 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11218 if (NumForLoopsResult.isInvalid())
11219 return nullptr;
11220 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011221 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011222 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011223 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011224 auto *Clause = OMPOrderedClause::Create(
11225 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11226 StartLoc, LParenLoc, EndLoc);
11227 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11228 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011229}
11230
Alexey Bataeved09d242014-05-28 05:53:51 +000011231OMPClause *Sema::ActOnOpenMPSimpleClause(
11232 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11233 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011234 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011235 switch (Kind) {
11236 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011237 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011238 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11239 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011240 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011241 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011242 Res = ActOnOpenMPProcBindClause(
11243 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11244 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011245 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011246 case OMPC_atomic_default_mem_order:
11247 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11248 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11249 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11250 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011251 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011252 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011253 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011254 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011255 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011256 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011257 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011258 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011259 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011260 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011261 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011262 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011263 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011264 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011265 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011266 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011267 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011268 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011269 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011270 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011271 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011272 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011273 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011274 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011275 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011276 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011277 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011278 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011279 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011280 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011281 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011282 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011283 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011284 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011285 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011286 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011287 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011288 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011289 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011290 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011291 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011292 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011293 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011294 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011295 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011296 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011297 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011298 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011299 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011300 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011301 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011302 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011303 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011304 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011305 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011306 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011307 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011308 llvm_unreachable("Clause is not allowed.");
11309 }
11310 return Res;
11311}
11312
Alexey Bataev6402bca2015-12-28 07:25:51 +000011313static std::string
11314getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11315 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011316 SmallString<256> Buffer;
11317 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011318 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11319 unsigned Skipped = Exclude.size();
11320 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011321 for (unsigned I = First; I < Last; ++I) {
11322 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011323 --Skipped;
11324 continue;
11325 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011326 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11327 if (I == Bound - Skipped)
11328 Out << " or ";
11329 else if (I != Bound + 1 - Skipped)
11330 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011331 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011332 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011333}
11334
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011335OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11336 SourceLocation KindKwLoc,
11337 SourceLocation StartLoc,
11338 SourceLocation LParenLoc,
11339 SourceLocation EndLoc) {
11340 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011341 static_assert(OMPC_DEFAULT_unknown > 0,
11342 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011343 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011344 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11345 /*Last=*/OMPC_DEFAULT_unknown)
11346 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011347 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011348 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011349 switch (Kind) {
11350 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011351 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011352 break;
11353 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011354 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011355 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011356 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011357 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011358 break;
11359 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011360 return new (Context)
11361 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011362}
11363
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011364OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11365 SourceLocation KindKwLoc,
11366 SourceLocation StartLoc,
11367 SourceLocation LParenLoc,
11368 SourceLocation EndLoc) {
11369 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011370 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011371 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11372 /*Last=*/OMPC_PROC_BIND_unknown)
11373 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011374 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011375 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011376 return new (Context)
11377 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011378}
11379
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011380OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11381 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11382 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11383 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11384 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11385 << getListOfPossibleValues(
11386 OMPC_atomic_default_mem_order, /*First=*/0,
11387 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11388 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11389 return nullptr;
11390 }
11391 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11392 LParenLoc, EndLoc);
11393}
11394
Alexey Bataev56dafe82014-06-20 07:16:17 +000011395OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011396 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011397 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011398 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011399 SourceLocation EndLoc) {
11400 OMPClause *Res = nullptr;
11401 switch (Kind) {
11402 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011403 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11404 assert(Argument.size() == NumberOfElements &&
11405 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011406 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011407 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11408 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11409 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11410 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11411 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011412 break;
11413 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011414 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11415 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11416 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11417 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011418 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011419 case OMPC_dist_schedule:
11420 Res = ActOnOpenMPDistScheduleClause(
11421 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11422 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11423 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011424 case OMPC_defaultmap:
11425 enum { Modifier, DefaultmapKind };
11426 Res = ActOnOpenMPDefaultmapClause(
11427 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11428 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011429 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11430 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011431 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011432 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011433 case OMPC_num_threads:
11434 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011435 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011436 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011437 case OMPC_collapse:
11438 case OMPC_default:
11439 case OMPC_proc_bind:
11440 case OMPC_private:
11441 case OMPC_firstprivate:
11442 case OMPC_lastprivate:
11443 case OMPC_shared:
11444 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011445 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011446 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011447 case OMPC_linear:
11448 case OMPC_aligned:
11449 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011450 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011451 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011452 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011453 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011454 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011455 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011456 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011457 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011458 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011459 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011460 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011461 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011462 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011463 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011464 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011465 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011466 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011467 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011468 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011469 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011470 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011471 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011472 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011473 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011474 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011475 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011476 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011477 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011478 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011479 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011480 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011481 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011482 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011483 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011484 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011485 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011486 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011487 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011488 llvm_unreachable("Clause is not allowed.");
11489 }
11490 return Res;
11491}
11492
Alexey Bataev6402bca2015-12-28 07:25:51 +000011493static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11494 OpenMPScheduleClauseModifier M2,
11495 SourceLocation M1Loc, SourceLocation M2Loc) {
11496 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11497 SmallVector<unsigned, 2> Excluded;
11498 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11499 Excluded.push_back(M2);
11500 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11501 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11502 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11503 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11504 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11505 << getListOfPossibleValues(OMPC_schedule,
11506 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11507 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11508 Excluded)
11509 << getOpenMPClauseName(OMPC_schedule);
11510 return true;
11511 }
11512 return false;
11513}
11514
Alexey Bataev56dafe82014-06-20 07:16:17 +000011515OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011516 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011517 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011518 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11519 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11520 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11521 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11522 return nullptr;
11523 // OpenMP, 2.7.1, Loop Construct, Restrictions
11524 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11525 // but not both.
11526 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11527 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11528 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11529 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11530 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11531 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11532 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11533 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11534 return nullptr;
11535 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011536 if (Kind == OMPC_SCHEDULE_unknown) {
11537 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011538 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11539 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11540 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11541 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11542 Exclude);
11543 } else {
11544 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11545 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011546 }
11547 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11548 << Values << getOpenMPClauseName(OMPC_schedule);
11549 return nullptr;
11550 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011551 // OpenMP, 2.7.1, Loop Construct, Restrictions
11552 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11553 // schedule(guided).
11554 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11555 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11556 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11557 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11558 diag::err_omp_schedule_nonmonotonic_static);
11559 return nullptr;
11560 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011561 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011562 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011563 if (ChunkSize) {
11564 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11565 !ChunkSize->isInstantiationDependent() &&
11566 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011567 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011568 ExprResult Val =
11569 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11570 if (Val.isInvalid())
11571 return nullptr;
11572
11573 ValExpr = Val.get();
11574
11575 // OpenMP [2.7.1, Restrictions]
11576 // chunk_size must be a loop invariant integer expression with a positive
11577 // value.
11578 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000011579 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11580 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11581 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011582 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000011583 return nullptr;
11584 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000011585 } else if (getOpenMPCaptureRegionForClause(
11586 DSAStack->getCurrentDirective(), OMPC_schedule) !=
11587 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011588 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011589 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011590 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000011591 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11592 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011593 }
11594 }
11595 }
11596
Alexey Bataev6402bca2015-12-28 07:25:51 +000011597 return new (Context)
11598 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000011599 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011600}
11601
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011602OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
11603 SourceLocation StartLoc,
11604 SourceLocation EndLoc) {
11605 OMPClause *Res = nullptr;
11606 switch (Kind) {
11607 case OMPC_ordered:
11608 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
11609 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000011610 case OMPC_nowait:
11611 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
11612 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011613 case OMPC_untied:
11614 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
11615 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011616 case OMPC_mergeable:
11617 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
11618 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011619 case OMPC_read:
11620 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
11621 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000011622 case OMPC_write:
11623 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
11624 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000011625 case OMPC_update:
11626 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
11627 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000011628 case OMPC_capture:
11629 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
11630 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011631 case OMPC_seq_cst:
11632 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
11633 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000011634 case OMPC_threads:
11635 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
11636 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011637 case OMPC_simd:
11638 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
11639 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000011640 case OMPC_nogroup:
11641 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
11642 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011643 case OMPC_unified_address:
11644 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
11645 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011646 case OMPC_unified_shared_memory:
11647 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11648 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011649 case OMPC_reverse_offload:
11650 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
11651 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011652 case OMPC_dynamic_allocators:
11653 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
11654 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011655 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011656 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011657 case OMPC_num_threads:
11658 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011659 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011660 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011661 case OMPC_collapse:
11662 case OMPC_schedule:
11663 case OMPC_private:
11664 case OMPC_firstprivate:
11665 case OMPC_lastprivate:
11666 case OMPC_shared:
11667 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011668 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011669 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011670 case OMPC_linear:
11671 case OMPC_aligned:
11672 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011673 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011674 case OMPC_default:
11675 case OMPC_proc_bind:
11676 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011677 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011678 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011679 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011680 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011681 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011682 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011683 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011684 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011685 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000011686 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011687 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011688 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011689 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011690 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011691 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011692 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011693 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011694 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011695 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011696 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011697 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011698 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011699 llvm_unreachable("Clause is not allowed.");
11700 }
11701 return Res;
11702}
11703
Alexey Bataev236070f2014-06-20 11:19:47 +000011704OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11705 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000011706 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000011707 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
11708}
11709
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011710OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11711 SourceLocation EndLoc) {
11712 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
11713}
11714
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011715OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11716 SourceLocation EndLoc) {
11717 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
11718}
11719
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011720OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
11721 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011722 return new (Context) OMPReadClause(StartLoc, EndLoc);
11723}
11724
Alexey Bataevdea47612014-07-23 07:46:59 +000011725OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
11726 SourceLocation EndLoc) {
11727 return new (Context) OMPWriteClause(StartLoc, EndLoc);
11728}
11729
Alexey Bataev67a4f222014-07-23 10:25:33 +000011730OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11731 SourceLocation EndLoc) {
11732 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
11733}
11734
Alexey Bataev459dec02014-07-24 06:46:57 +000011735OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11736 SourceLocation EndLoc) {
11737 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
11738}
11739
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011740OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11741 SourceLocation EndLoc) {
11742 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
11743}
11744
Alexey Bataev346265e2015-09-25 10:37:12 +000011745OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11746 SourceLocation EndLoc) {
11747 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
11748}
11749
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011750OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11751 SourceLocation EndLoc) {
11752 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
11753}
11754
Alexey Bataevb825de12015-12-07 10:51:44 +000011755OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11756 SourceLocation EndLoc) {
11757 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
11758}
11759
Kelvin Li1408f912018-09-26 04:28:39 +000011760OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11761 SourceLocation EndLoc) {
11762 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
11763}
11764
Patrick Lyster4a370b92018-10-01 13:47:43 +000011765OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11766 SourceLocation EndLoc) {
11767 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11768}
11769
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011770OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11771 SourceLocation EndLoc) {
11772 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
11773}
11774
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011775OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11776 SourceLocation EndLoc) {
11777 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
11778}
11779
Alexey Bataevc5e02582014-06-16 07:08:35 +000011780OMPClause *Sema::ActOnOpenMPVarListClause(
11781 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011782 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11783 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11784 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000011785 OpenMPLinearClauseKind LinKind,
11786 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011787 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
11788 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
11789 SourceLocation StartLoc = Locs.StartLoc;
11790 SourceLocation LParenLoc = Locs.LParenLoc;
11791 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011792 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011793 switch (Kind) {
11794 case OMPC_private:
11795 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11796 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011797 case OMPC_firstprivate:
11798 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11799 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011800 case OMPC_lastprivate:
11801 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11802 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011803 case OMPC_shared:
11804 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
11805 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011806 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000011807 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011808 EndLoc, ReductionOrMapperIdScopeSpec,
11809 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011810 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000011811 case OMPC_task_reduction:
11812 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011813 EndLoc, ReductionOrMapperIdScopeSpec,
11814 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000011815 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000011816 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011817 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11818 EndLoc, ReductionOrMapperIdScopeSpec,
11819 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000011820 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000011821 case OMPC_linear:
11822 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011823 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000011824 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011825 case OMPC_aligned:
11826 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
11827 ColonLoc, EndLoc);
11828 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011829 case OMPC_copyin:
11830 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
11831 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011832 case OMPC_copyprivate:
11833 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11834 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000011835 case OMPC_flush:
11836 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
11837 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011838 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000011839 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011840 StartLoc, LParenLoc, EndLoc);
11841 break;
11842 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011843 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
11844 ReductionOrMapperIdScopeSpec,
11845 ReductionOrMapperId, MapType, IsMapTypeImplicit,
11846 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011847 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011848 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000011849 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
11850 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000011851 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000011852 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000011853 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
11854 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000011855 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000011856 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011857 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011858 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000011859 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011860 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011861 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000011862 case OMPC_allocate:
11863 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
11864 ColonLoc, EndLoc);
11865 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011866 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011867 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011868 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011869 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011870 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011871 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011872 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011873 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011874 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011875 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011876 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011877 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011878 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011879 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011880 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011881 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011882 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011883 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011884 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011885 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000011886 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011887 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011888 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011889 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011890 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011891 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011892 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011893 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011894 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011895 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011896 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011897 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011898 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011899 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000011900 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011901 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011902 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011903 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011904 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011905 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011906 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011907 llvm_unreachable("Clause is not allowed.");
11908 }
11909 return Res;
11910}
11911
Alexey Bataev90c228f2016-02-08 09:29:13 +000011912ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000011913 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000011914 ExprResult Res = BuildDeclRefExpr(
11915 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
11916 if (!Res.isUsable())
11917 return ExprError();
11918 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
11919 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
11920 if (!Res.isUsable())
11921 return ExprError();
11922 }
11923 if (VK != VK_LValue && Res.get()->isGLValue()) {
11924 Res = DefaultLvalueConversion(Res.get());
11925 if (!Res.isUsable())
11926 return ExprError();
11927 }
11928 return Res;
11929}
11930
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011931OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11932 SourceLocation StartLoc,
11933 SourceLocation LParenLoc,
11934 SourceLocation EndLoc) {
11935 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000011936 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000011937 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011938 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011939 SourceLocation ELoc;
11940 SourceRange ERange;
11941 Expr *SimpleRefExpr = RefExpr;
11942 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000011943 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011944 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011945 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011946 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011947 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011948 ValueDecl *D = Res.first;
11949 if (!D)
11950 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011951
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011952 QualType Type = D->getType();
11953 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011954
11955 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11956 // A variable that appears in a private clause must not have an incomplete
11957 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011958 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011959 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011960 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011961
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011962 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11963 // A variable that is privatized must not have a const-qualified type
11964 // unless it is of class type with a mutable member. This restriction does
11965 // not apply to the firstprivate clause.
11966 //
11967 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
11968 // A variable that appears in a private clause must not have a
11969 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011970 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011971 continue;
11972
Alexey Bataev758e55e2013-09-06 18:03:48 +000011973 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11974 // in a Construct]
11975 // Variables with the predetermined data-sharing attributes may not be
11976 // listed in data-sharing attributes clauses, except for the cases
11977 // listed below. For these exceptions only, listing a predetermined
11978 // variable in a data-sharing attribute clause is allowed and overrides
11979 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011980 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011981 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011982 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11983 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000011984 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011985 continue;
11986 }
11987
Alexey Bataeve3727102018-04-18 15:57:46 +000011988 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011989 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011990 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000011991 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011992 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11993 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000011994 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011995 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011996 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011997 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011998 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011999 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012000 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012001 continue;
12002 }
12003
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012004 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12005 // A list item cannot appear in both a map clause and a data-sharing
12006 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012007 //
12008 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12009 // A list item cannot appear in both a map clause and a data-sharing
12010 // attribute clause on the same construct unless the construct is a
12011 // combined construct.
12012 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12013 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012014 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012015 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012016 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012017 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12018 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12019 ConflictKind = WhereFoundClauseKind;
12020 return true;
12021 })) {
12022 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012023 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012024 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012025 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012026 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012027 continue;
12028 }
12029 }
12030
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012031 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12032 // A variable of class type (or array thereof) that appears in a private
12033 // clause requires an accessible, unambiguous default constructor for the
12034 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012035 // Generate helper private variable and initialize it with the default
12036 // value. The address of the original variable is replaced by the address of
12037 // the new private variable in CodeGen. This new variable is not added to
12038 // IdResolver, so the code in the OpenMP region uses original variable for
12039 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012040 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012041 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012042 buildVarDecl(*this, ELoc, Type, D->getName(),
12043 D->hasAttrs() ? &D->getAttrs() : nullptr,
12044 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012045 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012046 if (VDPrivate->isInvalidDecl())
12047 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012048 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012049 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012050
Alexey Bataev90c228f2016-02-08 09:29:13 +000012051 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012052 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012053 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012054 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012055 Vars.push_back((VD || CurContext->isDependentContext())
12056 ? RefExpr->IgnoreParens()
12057 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012058 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012059 }
12060
Alexey Bataeved09d242014-05-28 05:53:51 +000012061 if (Vars.empty())
12062 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012063
Alexey Bataev03b340a2014-10-21 03:16:40 +000012064 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12065 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012066}
12067
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012068namespace {
12069class DiagsUninitializedSeveretyRAII {
12070private:
12071 DiagnosticsEngine &Diags;
12072 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012073 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012074
12075public:
12076 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12077 bool IsIgnored)
12078 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12079 if (!IsIgnored) {
12080 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12081 /*Map*/ diag::Severity::Ignored, Loc);
12082 }
12083 }
12084 ~DiagsUninitializedSeveretyRAII() {
12085 if (!IsIgnored)
12086 Diags.popMappings(SavedLoc);
12087 }
12088};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012089}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012090
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012091OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12092 SourceLocation StartLoc,
12093 SourceLocation LParenLoc,
12094 SourceLocation EndLoc) {
12095 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012096 SmallVector<Expr *, 8> PrivateCopies;
12097 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012098 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012099 bool IsImplicitClause =
12100 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012101 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012102
Alexey Bataeve3727102018-04-18 15:57:46 +000012103 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012104 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012105 SourceLocation ELoc;
12106 SourceRange ERange;
12107 Expr *SimpleRefExpr = RefExpr;
12108 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012109 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012110 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012111 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012112 PrivateCopies.push_back(nullptr);
12113 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012114 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012115 ValueDecl *D = Res.first;
12116 if (!D)
12117 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012118
Alexey Bataev60da77e2016-02-29 05:54:20 +000012119 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012120 QualType Type = D->getType();
12121 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012122
12123 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12124 // A variable that appears in a private clause must not have an incomplete
12125 // type or a reference type.
12126 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012127 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012128 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012129 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012130
12131 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12132 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012133 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012134 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012135 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012136
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012137 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012138 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012139 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012140 DSAStackTy::DSAVarData DVar =
12141 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012142 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012143 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012144 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012145 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12146 // A list item that specifies a given variable may not appear in more
12147 // than one clause on the same directive, except that a variable may be
12148 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012149 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12150 // A list item may appear in a firstprivate or lastprivate clause but not
12151 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012152 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012153 (isOpenMPDistributeDirective(CurrDir) ||
12154 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012155 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012156 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012157 << getOpenMPClauseName(DVar.CKind)
12158 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012159 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012160 continue;
12161 }
12162
12163 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12164 // in a Construct]
12165 // Variables with the predetermined data-sharing attributes may not be
12166 // listed in data-sharing attributes clauses, except for the cases
12167 // listed below. For these exceptions only, listing a predetermined
12168 // variable in a data-sharing attribute clause is allowed and overrides
12169 // the variable's predetermined data-sharing attributes.
12170 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12171 // in a Construct, C/C++, p.2]
12172 // Variables with const-qualified type having no mutable member may be
12173 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012174 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012175 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12176 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012177 << getOpenMPClauseName(DVar.CKind)
12178 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012179 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012180 continue;
12181 }
12182
12183 // OpenMP [2.9.3.4, Restrictions, p.2]
12184 // A list item that is private within a parallel region must not appear
12185 // in a firstprivate clause on a worksharing construct if any of the
12186 // worksharing regions arising from the worksharing construct ever bind
12187 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012188 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12189 // A list item that is private within a teams region must not appear in a
12190 // firstprivate clause on a distribute construct if any of the distribute
12191 // regions arising from the distribute construct ever bind to any of the
12192 // teams regions arising from the teams construct.
12193 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12194 // A list item that appears in a reduction clause of a teams construct
12195 // must not appear in a firstprivate clause on a distribute construct if
12196 // any of the distribute regions arising from the distribute construct
12197 // ever bind to any of the teams regions arising from the teams construct.
12198 if ((isOpenMPWorksharingDirective(CurrDir) ||
12199 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012200 !isOpenMPParallelDirective(CurrDir) &&
12201 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012202 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012203 if (DVar.CKind != OMPC_shared &&
12204 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012205 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012206 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012207 Diag(ELoc, diag::err_omp_required_access)
12208 << getOpenMPClauseName(OMPC_firstprivate)
12209 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012210 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012211 continue;
12212 }
12213 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012214 // OpenMP [2.9.3.4, Restrictions, p.3]
12215 // A list item that appears in a reduction clause of a parallel construct
12216 // must not appear in a firstprivate clause on a worksharing or task
12217 // construct if any of the worksharing or task regions arising from the
12218 // worksharing or task construct ever bind to any of the parallel regions
12219 // arising from the parallel construct.
12220 // OpenMP [2.9.3.4, Restrictions, p.4]
12221 // A list item that appears in a reduction clause in worksharing
12222 // construct must not appear in a firstprivate clause in a task construct
12223 // encountered during execution of any of the worksharing regions arising
12224 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012225 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012226 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012227 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12228 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012229 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012230 isOpenMPWorksharingDirective(K) ||
12231 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012232 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012233 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012234 if (DVar.CKind == OMPC_reduction &&
12235 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012236 isOpenMPWorksharingDirective(DVar.DKind) ||
12237 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012238 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12239 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012240 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012241 continue;
12242 }
12243 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012244
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012245 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12246 // A list item cannot appear in both a map clause and a data-sharing
12247 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012248 //
12249 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12250 // A list item cannot appear in both a map clause and a data-sharing
12251 // attribute clause on the same construct unless the construct is a
12252 // combined construct.
12253 if ((LangOpts.OpenMP <= 45 &&
12254 isOpenMPTargetExecutionDirective(CurrDir)) ||
12255 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012256 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012257 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012258 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012259 [&ConflictKind](
12260 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12261 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012262 ConflictKind = WhereFoundClauseKind;
12263 return true;
12264 })) {
12265 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012266 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012267 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012268 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012269 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012270 continue;
12271 }
12272 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012273 }
12274
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012275 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012276 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012277 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012278 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12279 << getOpenMPClauseName(OMPC_firstprivate) << Type
12280 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12281 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012282 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012283 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012284 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012285 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012286 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012287 continue;
12288 }
12289
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012290 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012291 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012292 buildVarDecl(*this, ELoc, Type, D->getName(),
12293 D->hasAttrs() ? &D->getAttrs() : nullptr,
12294 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012295 // Generate helper private variable and initialize it with the value of the
12296 // original variable. The address of the original variable is replaced by
12297 // the address of the new private variable in the CodeGen. This new variable
12298 // is not added to IdResolver, so the code in the OpenMP region uses
12299 // original variable for proper diagnostics and variable capturing.
12300 Expr *VDInitRefExpr = nullptr;
12301 // For arrays generate initializer for single element and replace it by the
12302 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012303 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012304 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012305 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012306 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012307 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012308 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012309 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12310 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012311 InitializedEntity Entity =
12312 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012313 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12314
12315 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12316 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12317 if (Result.isInvalid())
12318 VDPrivate->setInvalidDecl();
12319 else
12320 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012321 // Remove temp variable declaration.
12322 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012323 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012324 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12325 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012326 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12327 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012328 AddInitializerToDecl(VDPrivate,
12329 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012330 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012331 }
12332 if (VDPrivate->isInvalidDecl()) {
12333 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012334 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012335 diag::note_omp_task_predetermined_firstprivate_here);
12336 }
12337 continue;
12338 }
12339 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012340 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012341 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12342 RefExpr->getExprLoc());
12343 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012344 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012345 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012346 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012347 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012348 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012349 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012350 ExprCaptures.push_back(Ref->getDecl());
12351 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012352 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012353 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012354 Vars.push_back((VD || CurContext->isDependentContext())
12355 ? RefExpr->IgnoreParens()
12356 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012357 PrivateCopies.push_back(VDPrivateRefExpr);
12358 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012359 }
12360
Alexey Bataeved09d242014-05-28 05:53:51 +000012361 if (Vars.empty())
12362 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012363
12364 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012365 Vars, PrivateCopies, Inits,
12366 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012367}
12368
Alexander Musman1bb328c2014-06-04 13:06:39 +000012369OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12370 SourceLocation StartLoc,
12371 SourceLocation LParenLoc,
12372 SourceLocation EndLoc) {
12373 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012374 SmallVector<Expr *, 8> SrcExprs;
12375 SmallVector<Expr *, 8> DstExprs;
12376 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012377 SmallVector<Decl *, 4> ExprCaptures;
12378 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012379 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012380 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012381 SourceLocation ELoc;
12382 SourceRange ERange;
12383 Expr *SimpleRefExpr = RefExpr;
12384 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012385 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012386 // It will be analyzed later.
12387 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012388 SrcExprs.push_back(nullptr);
12389 DstExprs.push_back(nullptr);
12390 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012391 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012392 ValueDecl *D = Res.first;
12393 if (!D)
12394 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012395
Alexey Bataev74caaf22016-02-20 04:09:36 +000012396 QualType Type = D->getType();
12397 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012398
12399 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12400 // A variable that appears in a lastprivate clause must not have an
12401 // incomplete type or a reference type.
12402 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012403 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012404 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012405 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012406
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012407 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12408 // A variable that is privatized must not have a const-qualified type
12409 // unless it is of class type with a mutable member. This restriction does
12410 // not apply to the firstprivate clause.
12411 //
12412 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12413 // A variable that appears in a lastprivate clause must not have a
12414 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012415 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012416 continue;
12417
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012418 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012419 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12420 // in a Construct]
12421 // Variables with the predetermined data-sharing attributes may not be
12422 // listed in data-sharing attributes clauses, except for the cases
12423 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012424 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12425 // A list item may appear in a firstprivate or lastprivate clause but not
12426 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012427 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012428 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012429 (isOpenMPDistributeDirective(CurrDir) ||
12430 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012431 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12432 Diag(ELoc, diag::err_omp_wrong_dsa)
12433 << getOpenMPClauseName(DVar.CKind)
12434 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012435 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012436 continue;
12437 }
12438
Alexey Bataevf29276e2014-06-18 04:14:57 +000012439 // OpenMP [2.14.3.5, Restrictions, p.2]
12440 // A list item that is private within a parallel region, or that appears in
12441 // the reduction clause of a parallel construct, must not appear in a
12442 // lastprivate clause on a worksharing construct if any of the corresponding
12443 // worksharing regions ever binds to any of the corresponding parallel
12444 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012445 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012446 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012447 !isOpenMPParallelDirective(CurrDir) &&
12448 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012449 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012450 if (DVar.CKind != OMPC_shared) {
12451 Diag(ELoc, diag::err_omp_required_access)
12452 << getOpenMPClauseName(OMPC_lastprivate)
12453 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012454 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012455 continue;
12456 }
12457 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012458
Alexander Musman1bb328c2014-06-04 13:06:39 +000012459 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012460 // A variable of class type (or array thereof) that appears in a
12461 // lastprivate clause requires an accessible, unambiguous default
12462 // constructor for the class type, unless the list item is also specified
12463 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012464 // A variable of class type (or array thereof) that appears in a
12465 // lastprivate clause requires an accessible, unambiguous copy assignment
12466 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012467 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012468 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12469 Type.getUnqualifiedType(), ".lastprivate.src",
12470 D->hasAttrs() ? &D->getAttrs() : nullptr);
12471 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012472 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012473 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012474 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012475 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012476 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012477 // For arrays generate assignment operation for single element and replace
12478 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012479 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12480 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012481 if (AssignmentOp.isInvalid())
12482 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012483 AssignmentOp =
12484 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012485 if (AssignmentOp.isInvalid())
12486 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012487
Alexey Bataev74caaf22016-02-20 04:09:36 +000012488 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012489 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012490 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012491 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012492 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012493 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012494 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012495 ExprCaptures.push_back(Ref->getDecl());
12496 }
12497 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012498 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012499 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012500 ExprResult RefRes = DefaultLvalueConversion(Ref);
12501 if (!RefRes.isUsable())
12502 continue;
12503 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012504 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12505 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012506 if (!PostUpdateRes.isUsable())
12507 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012508 ExprPostUpdates.push_back(
12509 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012510 }
12511 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012512 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012513 Vars.push_back((VD || CurContext->isDependentContext())
12514 ? RefExpr->IgnoreParens()
12515 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012516 SrcExprs.push_back(PseudoSrcExpr);
12517 DstExprs.push_back(PseudoDstExpr);
12518 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012519 }
12520
12521 if (Vars.empty())
12522 return nullptr;
12523
12524 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012525 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012526 buildPreInits(Context, ExprCaptures),
12527 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012528}
12529
Alexey Bataev758e55e2013-09-06 18:03:48 +000012530OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12531 SourceLocation StartLoc,
12532 SourceLocation LParenLoc,
12533 SourceLocation EndLoc) {
12534 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012535 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012536 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012537 SourceLocation ELoc;
12538 SourceRange ERange;
12539 Expr *SimpleRefExpr = RefExpr;
12540 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012541 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012542 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012543 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012544 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012545 ValueDecl *D = Res.first;
12546 if (!D)
12547 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012548
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012549 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012550 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12551 // in a Construct]
12552 // Variables with the predetermined data-sharing attributes may not be
12553 // listed in data-sharing attributes clauses, except for the cases
12554 // listed below. For these exceptions only, listing a predetermined
12555 // variable in a data-sharing attribute clause is allowed and overrides
12556 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012557 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012558 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12559 DVar.RefExpr) {
12560 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12561 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012562 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012563 continue;
12564 }
12565
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012566 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012567 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012568 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012569 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012570 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12571 ? RefExpr->IgnoreParens()
12572 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012573 }
12574
Alexey Bataeved09d242014-05-28 05:53:51 +000012575 if (Vars.empty())
12576 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012577
12578 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12579}
12580
Alexey Bataevc5e02582014-06-16 07:08:35 +000012581namespace {
12582class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12583 DSAStackTy *Stack;
12584
12585public:
12586 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012587 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12588 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012589 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12590 return false;
12591 if (DVar.CKind != OMPC_unknown)
12592 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012593 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012594 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012595 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012596 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012597 }
12598 return false;
12599 }
12600 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012601 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012602 if (Child && Visit(Child))
12603 return true;
12604 }
12605 return false;
12606 }
Alexey Bataev23b69422014-06-18 07:08:49 +000012607 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012608};
Alexey Bataev23b69422014-06-18 07:08:49 +000012609} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000012610
Alexey Bataev60da77e2016-02-29 05:54:20 +000012611namespace {
12612// Transform MemberExpression for specified FieldDecl of current class to
12613// DeclRefExpr to specified OMPCapturedExprDecl.
12614class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
12615 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000012616 ValueDecl *Field = nullptr;
12617 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012618
12619public:
12620 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
12621 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
12622
12623 ExprResult TransformMemberExpr(MemberExpr *E) {
12624 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
12625 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000012626 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012627 return CapturedExpr;
12628 }
12629 return BaseTransform::TransformMemberExpr(E);
12630 }
12631 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
12632};
12633} // namespace
12634
Alexey Bataev97d18bf2018-04-11 19:21:00 +000012635template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000012636static T filterLookupForUDReductionAndMapper(
12637 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012638 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012639 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012640 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012641 return Res;
12642 }
12643 }
12644 return T();
12645}
12646
Alexey Bataev43b90b72018-09-12 16:31:59 +000012647static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
12648 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
12649
12650 for (auto RD : D->redecls()) {
12651 // Don't bother with extra checks if we already know this one isn't visible.
12652 if (RD == D)
12653 continue;
12654
12655 auto ND = cast<NamedDecl>(RD);
12656 if (LookupResult::isVisible(SemaRef, ND))
12657 return ND;
12658 }
12659
12660 return nullptr;
12661}
12662
12663static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000012664argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000012665 SourceLocation Loc, QualType Ty,
12666 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
12667 // Find all of the associated namespaces and classes based on the
12668 // arguments we have.
12669 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12670 Sema::AssociatedClassSet AssociatedClasses;
12671 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
12672 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
12673 AssociatedClasses);
12674
12675 // C++ [basic.lookup.argdep]p3:
12676 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12677 // and let Y be the lookup set produced by argument dependent
12678 // lookup (defined as follows). If X contains [...] then Y is
12679 // empty. Otherwise Y is the set of declarations found in the
12680 // namespaces associated with the argument types as described
12681 // below. The set of declarations found by the lookup of the name
12682 // is the union of X and Y.
12683 //
12684 // Here, we compute Y and add its members to the overloaded
12685 // candidate set.
12686 for (auto *NS : AssociatedNamespaces) {
12687 // When considering an associated namespace, the lookup is the
12688 // same as the lookup performed when the associated namespace is
12689 // used as a qualifier (3.4.3.2) except that:
12690 //
12691 // -- Any using-directives in the associated namespace are
12692 // ignored.
12693 //
12694 // -- Any namespace-scope friend functions declared in
12695 // associated classes are visible within their respective
12696 // namespaces even if they are not visible during an ordinary
12697 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000012698 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000012699 for (auto *D : R) {
12700 auto *Underlying = D;
12701 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12702 Underlying = USD->getTargetDecl();
12703
Michael Kruse4304e9d2019-02-19 16:38:20 +000012704 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
12705 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000012706 continue;
12707
12708 if (!SemaRef.isVisible(D)) {
12709 D = findAcceptableDecl(SemaRef, D);
12710 if (!D)
12711 continue;
12712 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12713 Underlying = USD->getTargetDecl();
12714 }
12715 Lookups.emplace_back();
12716 Lookups.back().addDecl(Underlying);
12717 }
12718 }
12719}
12720
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012721static ExprResult
12722buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
12723 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
12724 const DeclarationNameInfo &ReductionId, QualType Ty,
12725 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
12726 if (ReductionIdScopeSpec.isInvalid())
12727 return ExprError();
12728 SmallVector<UnresolvedSet<8>, 4> Lookups;
12729 if (S) {
12730 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12731 Lookup.suppressDiagnostics();
12732 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012733 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012734 do {
12735 S = S->getParent();
12736 } while (S && !S->isDeclScope(D));
12737 if (S)
12738 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000012739 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012740 Lookups.back().append(Lookup.begin(), Lookup.end());
12741 Lookup.clear();
12742 }
12743 } else if (auto *ULE =
12744 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
12745 Lookups.push_back(UnresolvedSet<8>());
12746 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012747 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012748 if (D == PrevD)
12749 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000012750 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012751 Lookups.back().addDecl(DRD);
12752 PrevD = D;
12753 }
12754 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000012755 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
12756 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012757 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000012758 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012759 return !D->isInvalidDecl() &&
12760 (D->getType()->isDependentType() ||
12761 D->getType()->isInstantiationDependentType() ||
12762 D->getType()->containsUnexpandedParameterPack());
12763 })) {
12764 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000012765 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000012766 if (Set.empty())
12767 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012768 ResSet.append(Set.begin(), Set.end());
12769 // The last item marks the end of all declarations at the specified scope.
12770 ResSet.addDecl(Set[Set.size() - 1]);
12771 }
12772 return UnresolvedLookupExpr::Create(
12773 SemaRef.Context, /*NamingClass=*/nullptr,
12774 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
12775 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
12776 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000012777 // Lookup inside the classes.
12778 // C++ [over.match.oper]p3:
12779 // For a unary operator @ with an operand of a type whose
12780 // cv-unqualified version is T1, and for a binary operator @ with
12781 // a left operand of a type whose cv-unqualified version is T1 and
12782 // a right operand of a type whose cv-unqualified version is T2,
12783 // three sets of candidate functions, designated member
12784 // candidates, non-member candidates and built-in candidates, are
12785 // constructed as follows:
12786 // -- If T1 is a complete class type or a class currently being
12787 // defined, the set of member candidates is the result of the
12788 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
12789 // the set of member candidates is empty.
12790 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12791 Lookup.suppressDiagnostics();
12792 if (const auto *TyRec = Ty->getAs<RecordType>()) {
12793 // Complete the type if it can be completed.
12794 // If the type is neither complete nor being defined, bail out now.
12795 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
12796 TyRec->getDecl()->getDefinition()) {
12797 Lookup.clear();
12798 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
12799 if (Lookup.empty()) {
12800 Lookups.emplace_back();
12801 Lookups.back().append(Lookup.begin(), Lookup.end());
12802 }
12803 }
12804 }
12805 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000012806 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000012807 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000012808 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12809 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
12810 if (!D->isInvalidDecl() &&
12811 SemaRef.Context.hasSameType(D->getType(), Ty))
12812 return D;
12813 return nullptr;
12814 }))
12815 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
12816 VK_LValue, Loc);
12817 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000012818 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12819 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
12820 if (!D->isInvalidDecl() &&
12821 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
12822 !Ty.isMoreQualifiedThan(D->getType()))
12823 return D;
12824 return nullptr;
12825 })) {
12826 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
12827 /*DetectVirtual=*/false);
12828 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
12829 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
12830 VD->getType().getUnqualifiedType()))) {
12831 if (SemaRef.CheckBaseClassAccess(
12832 Loc, VD->getType(), Ty, Paths.front(),
12833 /*DiagID=*/0) != Sema::AR_inaccessible) {
12834 SemaRef.BuildBasePathArray(Paths, BasePath);
12835 return SemaRef.BuildDeclRefExpr(
12836 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
12837 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012838 }
12839 }
12840 }
12841 }
12842 if (ReductionIdScopeSpec.isSet()) {
12843 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
12844 return ExprError();
12845 }
12846 return ExprEmpty();
12847}
12848
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012849namespace {
12850/// Data for the reduction-based clauses.
12851struct ReductionData {
12852 /// List of original reduction items.
12853 SmallVector<Expr *, 8> Vars;
12854 /// List of private copies of the reduction items.
12855 SmallVector<Expr *, 8> Privates;
12856 /// LHS expressions for the reduction_op expressions.
12857 SmallVector<Expr *, 8> LHSs;
12858 /// RHS expressions for the reduction_op expressions.
12859 SmallVector<Expr *, 8> RHSs;
12860 /// Reduction operation expression.
12861 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000012862 /// Taskgroup descriptors for the corresponding reduction items in
12863 /// in_reduction clauses.
12864 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012865 /// List of captures for clause.
12866 SmallVector<Decl *, 4> ExprCaptures;
12867 /// List of postupdate expressions.
12868 SmallVector<Expr *, 4> ExprPostUpdates;
12869 ReductionData() = delete;
12870 /// Reserves required memory for the reduction data.
12871 ReductionData(unsigned Size) {
12872 Vars.reserve(Size);
12873 Privates.reserve(Size);
12874 LHSs.reserve(Size);
12875 RHSs.reserve(Size);
12876 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000012877 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012878 ExprCaptures.reserve(Size);
12879 ExprPostUpdates.reserve(Size);
12880 }
12881 /// Stores reduction item and reduction operation only (required for dependent
12882 /// reduction item).
12883 void push(Expr *Item, Expr *ReductionOp) {
12884 Vars.emplace_back(Item);
12885 Privates.emplace_back(nullptr);
12886 LHSs.emplace_back(nullptr);
12887 RHSs.emplace_back(nullptr);
12888 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012889 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012890 }
12891 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000012892 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
12893 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012894 Vars.emplace_back(Item);
12895 Privates.emplace_back(Private);
12896 LHSs.emplace_back(LHS);
12897 RHSs.emplace_back(RHS);
12898 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012899 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012900 }
12901};
12902} // namespace
12903
Alexey Bataeve3727102018-04-18 15:57:46 +000012904static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012905 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
12906 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
12907 const Expr *Length = OASE->getLength();
12908 if (Length == nullptr) {
12909 // For array sections of the form [1:] or [:], we would need to analyze
12910 // the lower bound...
12911 if (OASE->getColonLoc().isValid())
12912 return false;
12913
12914 // This is an array subscript which has implicit length 1!
12915 SingleElement = true;
12916 ArraySizes.push_back(llvm::APSInt::get(1));
12917 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012918 Expr::EvalResult Result;
12919 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012920 return false;
12921
Fangrui Song407659a2018-11-30 23:41:18 +000012922 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012923 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
12924 ArraySizes.push_back(ConstantLengthValue);
12925 }
12926
12927 // Get the base of this array section and walk up from there.
12928 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
12929
12930 // We require length = 1 for all array sections except the right-most to
12931 // guarantee that the memory region is contiguous and has no holes in it.
12932 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
12933 Length = TempOASE->getLength();
12934 if (Length == nullptr) {
12935 // For array sections of the form [1:] or [:], we would need to analyze
12936 // the lower bound...
12937 if (OASE->getColonLoc().isValid())
12938 return false;
12939
12940 // This is an array subscript which has implicit length 1!
12941 ArraySizes.push_back(llvm::APSInt::get(1));
12942 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012943 Expr::EvalResult Result;
12944 if (!Length->EvaluateAsInt(Result, Context))
12945 return false;
12946
12947 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
12948 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012949 return false;
12950
12951 ArraySizes.push_back(ConstantLengthValue);
12952 }
12953 Base = TempOASE->getBase()->IgnoreParenImpCasts();
12954 }
12955
12956 // If we have a single element, we don't need to add the implicit lengths.
12957 if (!SingleElement) {
12958 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
12959 // Has implicit length 1!
12960 ArraySizes.push_back(llvm::APSInt::get(1));
12961 Base = TempASE->getBase()->IgnoreParenImpCasts();
12962 }
12963 }
12964
12965 // This array section can be privatized as a single value or as a constant
12966 // sized array.
12967 return true;
12968}
12969
Alexey Bataeve3727102018-04-18 15:57:46 +000012970static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000012971 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
12972 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12973 SourceLocation ColonLoc, SourceLocation EndLoc,
12974 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012975 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012976 DeclarationName DN = ReductionId.getName();
12977 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012978 BinaryOperatorKind BOK = BO_Comma;
12979
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012980 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012981 // OpenMP [2.14.3.6, reduction clause]
12982 // C
12983 // reduction-identifier is either an identifier or one of the following
12984 // operators: +, -, *, &, |, ^, && and ||
12985 // C++
12986 // reduction-identifier is either an id-expression or one of the following
12987 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000012988 switch (OOK) {
12989 case OO_Plus:
12990 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012991 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012992 break;
12993 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012994 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012995 break;
12996 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012997 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012998 break;
12999 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013000 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013001 break;
13002 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013003 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013004 break;
13005 case OO_AmpAmp:
13006 BOK = BO_LAnd;
13007 break;
13008 case OO_PipePipe:
13009 BOK = BO_LOr;
13010 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013011 case OO_New:
13012 case OO_Delete:
13013 case OO_Array_New:
13014 case OO_Array_Delete:
13015 case OO_Slash:
13016 case OO_Percent:
13017 case OO_Tilde:
13018 case OO_Exclaim:
13019 case OO_Equal:
13020 case OO_Less:
13021 case OO_Greater:
13022 case OO_LessEqual:
13023 case OO_GreaterEqual:
13024 case OO_PlusEqual:
13025 case OO_MinusEqual:
13026 case OO_StarEqual:
13027 case OO_SlashEqual:
13028 case OO_PercentEqual:
13029 case OO_CaretEqual:
13030 case OO_AmpEqual:
13031 case OO_PipeEqual:
13032 case OO_LessLess:
13033 case OO_GreaterGreater:
13034 case OO_LessLessEqual:
13035 case OO_GreaterGreaterEqual:
13036 case OO_EqualEqual:
13037 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013038 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013039 case OO_PlusPlus:
13040 case OO_MinusMinus:
13041 case OO_Comma:
13042 case OO_ArrowStar:
13043 case OO_Arrow:
13044 case OO_Call:
13045 case OO_Subscript:
13046 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013047 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013048 case NUM_OVERLOADED_OPERATORS:
13049 llvm_unreachable("Unexpected reduction identifier");
13050 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013051 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013052 if (II->isStr("max"))
13053 BOK = BO_GT;
13054 else if (II->isStr("min"))
13055 BOK = BO_LT;
13056 }
13057 break;
13058 }
13059 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013060 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013061 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013062 else
13063 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013064 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013065
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013066 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13067 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013068 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013069 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013070 // OpenMP [2.1, C/C++]
13071 // A list item is a variable or array section, subject to the restrictions
13072 // specified in Section 2.4 on page 42 and in each of the sections
13073 // describing clauses and directives for which a list appears.
13074 // OpenMP [2.14.3.3, Restrictions, p.1]
13075 // A variable that is part of another variable (as an array or
13076 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013077 if (!FirstIter && IR != ER)
13078 ++IR;
13079 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013080 SourceLocation ELoc;
13081 SourceRange ERange;
13082 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013083 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013084 /*AllowArraySection=*/true);
13085 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013086 // Try to find 'declare reduction' corresponding construct before using
13087 // builtin/overloaded operators.
13088 QualType Type = Context.DependentTy;
13089 CXXCastPath BasePath;
13090 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013091 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013092 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013093 Expr *ReductionOp = nullptr;
13094 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013095 (DeclareReductionRef.isUnset() ||
13096 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013097 ReductionOp = DeclareReductionRef.get();
13098 // It will be analyzed later.
13099 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013100 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013101 ValueDecl *D = Res.first;
13102 if (!D)
13103 continue;
13104
Alexey Bataev88202be2017-07-27 13:20:36 +000013105 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013106 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013107 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13108 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013109 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013110 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013111 } else if (OASE) {
13112 QualType BaseType =
13113 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13114 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013115 Type = ATy->getElementType();
13116 else
13117 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013118 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013119 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013120 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013121 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013122 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013123
Alexey Bataevc5e02582014-06-16 07:08:35 +000013124 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13125 // A variable that appears in a private clause must not have an incomplete
13126 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013127 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013128 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013129 continue;
13130 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013131 // A list item that appears in a reduction clause must not be
13132 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013133 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13134 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013135 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013136
13137 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013138 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13139 // If a list-item is a reference type then it must bind to the same object
13140 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013141 if (!ASE && !OASE) {
13142 if (VD) {
13143 VarDecl *VDDef = VD->getDefinition();
13144 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13145 DSARefChecker Check(Stack);
13146 if (Check.Visit(VDDef->getInit())) {
13147 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13148 << getOpenMPClauseName(ClauseKind) << ERange;
13149 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13150 continue;
13151 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013152 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013153 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013154
Alexey Bataevbc529672018-09-28 19:33:14 +000013155 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13156 // in a Construct]
13157 // Variables with the predetermined data-sharing attributes may not be
13158 // listed in data-sharing attributes clauses, except for the cases
13159 // listed below. For these exceptions only, listing a predetermined
13160 // variable in a data-sharing attribute clause is allowed and overrides
13161 // the variable's predetermined data-sharing attributes.
13162 // OpenMP [2.14.3.6, Restrictions, p.3]
13163 // Any number of reduction clauses can be specified on the directive,
13164 // but a list item can appear only once in the reduction clauses for that
13165 // directive.
13166 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13167 if (DVar.CKind == OMPC_reduction) {
13168 S.Diag(ELoc, diag::err_omp_once_referenced)
13169 << getOpenMPClauseName(ClauseKind);
13170 if (DVar.RefExpr)
13171 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13172 continue;
13173 }
13174 if (DVar.CKind != OMPC_unknown) {
13175 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13176 << getOpenMPClauseName(DVar.CKind)
13177 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013178 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013179 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013180 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013181
13182 // OpenMP [2.14.3.6, Restrictions, p.1]
13183 // A list item that appears in a reduction clause of a worksharing
13184 // construct must be shared in the parallel regions to which any of the
13185 // worksharing regions arising from the worksharing construct bind.
13186 if (isOpenMPWorksharingDirective(CurrDir) &&
13187 !isOpenMPParallelDirective(CurrDir) &&
13188 !isOpenMPTeamsDirective(CurrDir)) {
13189 DVar = Stack->getImplicitDSA(D, true);
13190 if (DVar.CKind != OMPC_shared) {
13191 S.Diag(ELoc, diag::err_omp_required_access)
13192 << getOpenMPClauseName(OMPC_reduction)
13193 << getOpenMPClauseName(OMPC_shared);
13194 reportOriginalDsa(S, Stack, D, DVar);
13195 continue;
13196 }
13197 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013198 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013199
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013200 // Try to find 'declare reduction' corresponding construct before using
13201 // builtin/overloaded operators.
13202 CXXCastPath BasePath;
13203 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013204 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013205 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13206 if (DeclareReductionRef.isInvalid())
13207 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013208 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013209 (DeclareReductionRef.isUnset() ||
13210 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013211 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013212 continue;
13213 }
13214 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13215 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013216 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013217 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013218 << Type << ReductionIdRange;
13219 continue;
13220 }
13221
13222 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13223 // The type of a list item that appears in a reduction clause must be valid
13224 // for the reduction-identifier. For a max or min reduction in C, the type
13225 // of the list item must be an allowed arithmetic data type: char, int,
13226 // float, double, or _Bool, possibly modified with long, short, signed, or
13227 // unsigned. For a max or min reduction in C++, the type of the list item
13228 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13229 // double, or bool, possibly modified with long, short, signed, or unsigned.
13230 if (DeclareReductionRef.isUnset()) {
13231 if ((BOK == BO_GT || BOK == BO_LT) &&
13232 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013233 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13234 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013235 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013236 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013237 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13238 VarDecl::DeclarationOnly;
13239 S.Diag(D->getLocation(),
13240 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013241 << D;
13242 }
13243 continue;
13244 }
13245 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013246 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013247 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13248 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013249 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013250 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13251 VarDecl::DeclarationOnly;
13252 S.Diag(D->getLocation(),
13253 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013254 << D;
13255 }
13256 continue;
13257 }
13258 }
13259
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013260 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013261 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13262 D->hasAttrs() ? &D->getAttrs() : nullptr);
13263 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13264 D->hasAttrs() ? &D->getAttrs() : nullptr);
13265 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013266
13267 // Try if we can determine constant lengths for all array sections and avoid
13268 // the VLA.
13269 bool ConstantLengthOASE = false;
13270 if (OASE) {
13271 bool SingleElement;
13272 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013273 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013274 Context, OASE, SingleElement, ArraySizes);
13275
13276 // If we don't have a single element, we must emit a constant array type.
13277 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013278 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013279 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13280 ArrayType::Normal,
13281 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013282 }
13283 }
13284
13285 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013286 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013287 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013288 if (!Context.getTargetInfo().isVLASupported()) {
13289 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13290 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13291 S.Diag(ELoc, diag::note_vla_unsupported);
13292 } else {
13293 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13294 S.targetDiag(ELoc, diag::note_vla_unsupported);
13295 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013296 continue;
13297 }
David Majnemer9d168222016-08-05 17:44:54 +000013298 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013299 // Create pseudo array type for private copy. The size for this array will
13300 // be generated during codegen.
13301 // For array subscripts or single variables Private Ty is the same as Type
13302 // (type of the variable or single array element).
13303 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013304 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013305 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013306 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013307 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013308 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013309 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013310 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013311 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013312 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013313 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13314 D->hasAttrs() ? &D->getAttrs() : nullptr,
13315 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013316 // Add initializer for private variable.
13317 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013318 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13319 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013320 if (DeclareReductionRef.isUsable()) {
13321 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13322 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13323 if (DRD->getInitializer()) {
13324 Init = DRDRef;
13325 RHSVD->setInit(DRDRef);
13326 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013327 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013328 } else {
13329 switch (BOK) {
13330 case BO_Add:
13331 case BO_Xor:
13332 case BO_Or:
13333 case BO_LOr:
13334 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13335 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013336 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013337 break;
13338 case BO_Mul:
13339 case BO_LAnd:
13340 if (Type->isScalarType() || Type->isAnyComplexType()) {
13341 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013342 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013343 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013344 break;
13345 case BO_And: {
13346 // '&' reduction op - initializer is '~0'.
13347 QualType OrigType = Type;
13348 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13349 Type = ComplexTy->getElementType();
13350 if (Type->isRealFloatingType()) {
13351 llvm::APFloat InitValue =
13352 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13353 /*isIEEE=*/true);
13354 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13355 Type, ELoc);
13356 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013357 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013358 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13359 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13360 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13361 }
13362 if (Init && OrigType->isAnyComplexType()) {
13363 // Init = 0xFFFF + 0xFFFFi;
13364 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013365 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013366 }
13367 Type = OrigType;
13368 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013369 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013370 case BO_LT:
13371 case BO_GT: {
13372 // 'min' reduction op - initializer is 'Largest representable number in
13373 // the reduction list item type'.
13374 // 'max' reduction op - initializer is 'Least representable number in
13375 // the reduction list item type'.
13376 if (Type->isIntegerType() || Type->isPointerType()) {
13377 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013378 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013379 QualType IntTy =
13380 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13381 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013382 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13383 : llvm::APInt::getMinValue(Size)
13384 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13385 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013386 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13387 if (Type->isPointerType()) {
13388 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013389 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013390 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013391 if (CastExpr.isInvalid())
13392 continue;
13393 Init = CastExpr.get();
13394 }
13395 } else if (Type->isRealFloatingType()) {
13396 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13397 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13398 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13399 Type, ELoc);
13400 }
13401 break;
13402 }
13403 case BO_PtrMemD:
13404 case BO_PtrMemI:
13405 case BO_MulAssign:
13406 case BO_Div:
13407 case BO_Rem:
13408 case BO_Sub:
13409 case BO_Shl:
13410 case BO_Shr:
13411 case BO_LE:
13412 case BO_GE:
13413 case BO_EQ:
13414 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013415 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013416 case BO_AndAssign:
13417 case BO_XorAssign:
13418 case BO_OrAssign:
13419 case BO_Assign:
13420 case BO_AddAssign:
13421 case BO_SubAssign:
13422 case BO_DivAssign:
13423 case BO_RemAssign:
13424 case BO_ShlAssign:
13425 case BO_ShrAssign:
13426 case BO_Comma:
13427 llvm_unreachable("Unexpected reduction operation");
13428 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013429 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013430 if (Init && DeclareReductionRef.isUnset())
13431 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13432 else if (!Init)
13433 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013434 if (RHSVD->isInvalidDecl())
13435 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013436 if (!RHSVD->hasInit() &&
13437 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013438 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13439 << Type << ReductionIdRange;
13440 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13441 VarDecl::DeclarationOnly;
13442 S.Diag(D->getLocation(),
13443 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013444 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013445 continue;
13446 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013447 // Store initializer for single element in private copy. Will be used during
13448 // codegen.
13449 PrivateVD->setInit(RHSVD->getInit());
13450 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013451 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013452 ExprResult ReductionOp;
13453 if (DeclareReductionRef.isUsable()) {
13454 QualType RedTy = DeclareReductionRef.get()->getType();
13455 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013456 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13457 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013458 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013459 LHS = S.DefaultLvalueConversion(LHS.get());
13460 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013461 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13462 CK_UncheckedDerivedToBase, LHS.get(),
13463 &BasePath, LHS.get()->getValueKind());
13464 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13465 CK_UncheckedDerivedToBase, RHS.get(),
13466 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013467 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013468 FunctionProtoType::ExtProtoInfo EPI;
13469 QualType Params[] = {PtrRedTy, PtrRedTy};
13470 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13471 auto *OVE = new (Context) OpaqueValueExpr(
13472 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013473 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013474 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013475 ReductionOp =
13476 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013477 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013478 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013479 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013480 if (ReductionOp.isUsable()) {
13481 if (BOK != BO_LT && BOK != BO_GT) {
13482 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013483 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013484 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013485 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013486 auto *ConditionalOp = new (Context)
13487 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13488 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013489 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013490 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013491 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013492 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013493 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013494 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13495 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013496 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013497 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013498 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013499 }
13500
Alexey Bataevfa312f32017-07-21 18:48:21 +000013501 // OpenMP [2.15.4.6, Restrictions, p.2]
13502 // A list item that appears in an in_reduction clause of a task construct
13503 // must appear in a task_reduction clause of a construct associated with a
13504 // taskgroup region that includes the participating task in its taskgroup
13505 // set. The construct associated with the innermost region that meets this
13506 // condition must specify the same reduction-identifier as the in_reduction
13507 // clause.
13508 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013509 SourceRange ParentSR;
13510 BinaryOperatorKind ParentBOK;
13511 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013512 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013513 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013514 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13515 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013516 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013517 Stack->getTopMostTaskgroupReductionData(
13518 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013519 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13520 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13521 if (!IsParentBOK && !IsParentReductionOp) {
13522 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13523 continue;
13524 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013525 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13526 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13527 IsParentReductionOp) {
13528 bool EmitError = true;
13529 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13530 llvm::FoldingSetNodeID RedId, ParentRedId;
13531 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13532 DeclareReductionRef.get()->Profile(RedId, Context,
13533 /*Canonical=*/true);
13534 EmitError = RedId != ParentRedId;
13535 }
13536 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013537 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013538 diag::err_omp_reduction_identifier_mismatch)
13539 << ReductionIdRange << RefExpr->getSourceRange();
13540 S.Diag(ParentSR.getBegin(),
13541 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013542 << ParentSR
13543 << (IsParentBOK ? ParentBOKDSA.RefExpr
13544 : ParentReductionOpDSA.RefExpr)
13545 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013546 continue;
13547 }
13548 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013549 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13550 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013551 }
13552
Alexey Bataev60da77e2016-02-29 05:54:20 +000013553 DeclRefExpr *Ref = nullptr;
13554 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013555 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013556 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013557 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013558 VarsExpr =
13559 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13560 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013561 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013562 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013563 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013564 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013565 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013566 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013567 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013568 if (!RefRes.isUsable())
13569 continue;
13570 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013571 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13572 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013573 if (!PostUpdateRes.isUsable())
13574 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013575 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13576 Stack->getCurrentDirective() == OMPD_taskgroup) {
13577 S.Diag(RefExpr->getExprLoc(),
13578 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000013579 << RefExpr->getSourceRange();
13580 continue;
13581 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013582 RD.ExprPostUpdates.emplace_back(
13583 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000013584 }
13585 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013586 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000013587 // All reduction items are still marked as reduction (to do not increase
13588 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013589 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013590 if (CurrDir == OMPD_taskgroup) {
13591 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013592 Stack->addTaskgroupReductionData(D, ReductionIdRange,
13593 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000013594 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013595 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013596 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013597 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
13598 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013599 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013600 return RD.Vars.empty();
13601}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013602
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013603OMPClause *Sema::ActOnOpenMPReductionClause(
13604 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13605 SourceLocation ColonLoc, SourceLocation EndLoc,
13606 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13607 ArrayRef<Expr *> UnresolvedReductions) {
13608 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013609 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013610 StartLoc, LParenLoc, ColonLoc, EndLoc,
13611 ReductionIdScopeSpec, ReductionId,
13612 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013613 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000013614
Alexey Bataevc5e02582014-06-16 07:08:35 +000013615 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013616 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13617 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13618 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13619 buildPreInits(Context, RD.ExprCaptures),
13620 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000013621}
13622
Alexey Bataev169d96a2017-07-18 20:17:46 +000013623OMPClause *Sema::ActOnOpenMPTaskReductionClause(
13624 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13625 SourceLocation ColonLoc, SourceLocation EndLoc,
13626 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13627 ArrayRef<Expr *> UnresolvedReductions) {
13628 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013629 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
13630 StartLoc, LParenLoc, ColonLoc, EndLoc,
13631 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013632 UnresolvedReductions, RD))
13633 return nullptr;
13634
13635 return OMPTaskReductionClause::Create(
13636 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13637 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13638 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13639 buildPreInits(Context, RD.ExprCaptures),
13640 buildPostUpdate(*this, RD.ExprPostUpdates));
13641}
13642
Alexey Bataevfa312f32017-07-21 18:48:21 +000013643OMPClause *Sema::ActOnOpenMPInReductionClause(
13644 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13645 SourceLocation ColonLoc, SourceLocation EndLoc,
13646 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13647 ArrayRef<Expr *> UnresolvedReductions) {
13648 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013649 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013650 StartLoc, LParenLoc, ColonLoc, EndLoc,
13651 ReductionIdScopeSpec, ReductionId,
13652 UnresolvedReductions, RD))
13653 return nullptr;
13654
13655 return OMPInReductionClause::Create(
13656 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13657 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000013658 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013659 buildPreInits(Context, RD.ExprCaptures),
13660 buildPostUpdate(*this, RD.ExprPostUpdates));
13661}
13662
Alexey Bataevecba70f2016-04-12 11:02:11 +000013663bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
13664 SourceLocation LinLoc) {
13665 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
13666 LinKind == OMPC_LINEAR_unknown) {
13667 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
13668 return true;
13669 }
13670 return false;
13671}
13672
Alexey Bataeve3727102018-04-18 15:57:46 +000013673bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000013674 OpenMPLinearClauseKind LinKind,
13675 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013676 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000013677 // A variable must not have an incomplete type or a reference type.
13678 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
13679 return true;
13680 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
13681 !Type->isReferenceType()) {
13682 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
13683 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
13684 return true;
13685 }
13686 Type = Type.getNonReferenceType();
13687
Joel E. Dennybae586f2019-01-04 22:12:13 +000013688 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13689 // A variable that is privatized must not have a const-qualified type
13690 // unless it is of class type with a mutable member. This restriction does
13691 // not apply to the firstprivate clause.
13692 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000013693 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013694
13695 // A list item must be of integral or pointer type.
13696 Type = Type.getUnqualifiedType().getCanonicalType();
13697 const auto *Ty = Type.getTypePtrOrNull();
13698 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
13699 !Ty->isPointerType())) {
13700 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
13701 if (D) {
13702 bool IsDecl =
13703 !VD ||
13704 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13705 Diag(D->getLocation(),
13706 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13707 << D;
13708 }
13709 return true;
13710 }
13711 return false;
13712}
13713
Alexey Bataev182227b2015-08-20 10:54:39 +000013714OMPClause *Sema::ActOnOpenMPLinearClause(
13715 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
13716 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
13717 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013718 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013719 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000013720 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013721 SmallVector<Decl *, 4> ExprCaptures;
13722 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013723 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000013724 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000013725 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013726 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013727 SourceLocation ELoc;
13728 SourceRange ERange;
13729 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013730 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013731 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013732 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013733 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013734 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013735 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000013736 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013737 ValueDecl *D = Res.first;
13738 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000013739 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000013740
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013741 QualType Type = D->getType();
13742 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000013743
13744 // OpenMP [2.14.3.7, linear clause]
13745 // A list-item cannot appear in more than one linear clause.
13746 // A list-item that appears in a linear clause cannot appear in any
13747 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013748 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000013749 if (DVar.RefExpr) {
13750 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13751 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000013752 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000013753 continue;
13754 }
13755
Alexey Bataevecba70f2016-04-12 11:02:11 +000013756 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000013757 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013758 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000013759
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013760 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000013761 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013762 buildVarDecl(*this, ELoc, Type, D->getName(),
13763 D->hasAttrs() ? &D->getAttrs() : nullptr,
13764 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013765 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013766 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013767 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013768 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013769 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013770 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013771 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013772 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013773 ExprCaptures.push_back(Ref->getDecl());
13774 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13775 ExprResult RefRes = DefaultLvalueConversion(Ref);
13776 if (!RefRes.isUsable())
13777 continue;
13778 ExprResult PostUpdateRes =
13779 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
13780 SimpleRefExpr, RefRes.get());
13781 if (!PostUpdateRes.isUsable())
13782 continue;
13783 ExprPostUpdates.push_back(
13784 IgnoredValueConversions(PostUpdateRes.get()).get());
13785 }
13786 }
13787 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013788 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013789 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013790 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013791 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013792 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013793 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013794 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013795
13796 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013797 Vars.push_back((VD || CurContext->isDependentContext())
13798 ? RefExpr->IgnoreParens()
13799 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013800 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000013801 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000013802 }
13803
13804 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013805 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013806
13807 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000013808 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013809 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
13810 !Step->isInstantiationDependent() &&
13811 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013812 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000013813 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000013814 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013815 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013816 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000013817
Alexander Musman3276a272015-03-21 10:12:56 +000013818 // Build var to save the step value.
13819 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013820 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000013821 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013822 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013823 ExprResult CalcStep =
13824 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013825 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013826
Alexander Musman8dba6642014-04-22 13:09:42 +000013827 // Warn about zero linear step (it would be probably better specified as
13828 // making corresponding variables 'const').
13829 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000013830 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
13831 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000013832 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
13833 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000013834 if (!IsConstant && CalcStep.isUsable()) {
13835 // Calculate the step beforehand instead of doing this on each iteration.
13836 // (This is not used if the number of iterations may be kfold-ed).
13837 CalcStepExpr = CalcStep.get();
13838 }
Alexander Musman8dba6642014-04-22 13:09:42 +000013839 }
13840
Alexey Bataev182227b2015-08-20 10:54:39 +000013841 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
13842 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013843 StepExpr, CalcStepExpr,
13844 buildPreInits(Context, ExprCaptures),
13845 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000013846}
13847
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013848static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
13849 Expr *NumIterations, Sema &SemaRef,
13850 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000013851 // Walk the vars and build update/final expressions for the CodeGen.
13852 SmallVector<Expr *, 8> Updates;
13853 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000013854 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000013855 Expr *Step = Clause.getStep();
13856 Expr *CalcStep = Clause.getCalcStep();
13857 // OpenMP [2.14.3.7, linear clause]
13858 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000013859 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000013860 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013861 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000013862 Step = cast<BinaryOperator>(CalcStep)->getLHS();
13863 bool HasErrors = false;
13864 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013865 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000013866 OpenMPLinearClauseKind LinKind = Clause.getModifier();
13867 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013868 SourceLocation ELoc;
13869 SourceRange ERange;
13870 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013871 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013872 ValueDecl *D = Res.first;
13873 if (Res.second || !D) {
13874 Updates.push_back(nullptr);
13875 Finals.push_back(nullptr);
13876 HasErrors = true;
13877 continue;
13878 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013879 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000013880 // OpenMP [2.15.11, distribute simd Construct]
13881 // A list item may not appear in a linear clause, unless it is the loop
13882 // iteration variable.
13883 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
13884 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
13885 SemaRef.Diag(ELoc,
13886 diag::err_omp_linear_distribute_var_non_loop_iteration);
13887 Updates.push_back(nullptr);
13888 Finals.push_back(nullptr);
13889 HasErrors = true;
13890 continue;
13891 }
Alexander Musman3276a272015-03-21 10:12:56 +000013892 Expr *InitExpr = *CurInit;
13893
13894 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000013895 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013896 Expr *CapturedRef;
13897 if (LinKind == OMPC_LINEAR_uval)
13898 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
13899 else
13900 CapturedRef =
13901 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
13902 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
13903 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000013904
13905 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013906 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000013907 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000013908 Update = buildCounterUpdate(
13909 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
13910 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013911 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013912 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013913 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013914 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013915
13916 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013917 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000013918 if (!Info.first)
13919 Final =
13920 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000013921 InitExpr, NumIterations, Step, /*Subtract=*/false,
13922 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013923 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013924 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013925 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013926 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013927
Alexander Musman3276a272015-03-21 10:12:56 +000013928 if (!Update.isUsable() || !Final.isUsable()) {
13929 Updates.push_back(nullptr);
13930 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000013931 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013932 HasErrors = true;
13933 } else {
13934 Updates.push_back(Update.get());
13935 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000013936 if (!Info.first)
13937 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000013938 }
Richard Trieucc3949d2016-02-18 22:34:54 +000013939 ++CurInit;
13940 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000013941 }
Alexey Bataev195ae902019-08-08 13:42:45 +000013942 if (Expr *S = Clause.getStep())
13943 UsedExprs.push_back(S);
13944 // Fill the remaining part with the nullptr.
13945 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013946 Clause.setUpdates(Updates);
13947 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000013948 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000013949 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000013950}
13951
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013952OMPClause *Sema::ActOnOpenMPAlignedClause(
13953 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
13954 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013955 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013956 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000013957 assert(RefExpr && "NULL expr in OpenMP linear clause.");
13958 SourceLocation ELoc;
13959 SourceRange ERange;
13960 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013961 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000013962 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013963 // It will be analyzed later.
13964 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013965 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000013966 ValueDecl *D = Res.first;
13967 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013968 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013969
Alexey Bataev1efd1662016-03-29 10:59:56 +000013970 QualType QType = D->getType();
13971 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013972
13973 // OpenMP [2.8.1, simd construct, Restrictions]
13974 // The type of list items appearing in the aligned clause must be
13975 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013976 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013977 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000013978 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013979 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000013980 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013981 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000013982 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013983 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000013984 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013985 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000013986 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013987 continue;
13988 }
13989
13990 // OpenMP [2.8.1, simd construct, Restrictions]
13991 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013992 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000013993 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013994 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
13995 << getOpenMPClauseName(OMPC_aligned);
13996 continue;
13997 }
13998
Alexey Bataev1efd1662016-03-29 10:59:56 +000013999 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014000 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014001 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14002 Vars.push_back(DefaultFunctionArrayConversion(
14003 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14004 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014005 }
14006
14007 // OpenMP [2.8.1, simd construct, Description]
14008 // The parameter of the aligned clause, alignment, must be a constant
14009 // positive integer expression.
14010 // If no optional parameter is specified, implementation-defined default
14011 // alignments for SIMD instructions on the target platforms are assumed.
14012 if (Alignment != nullptr) {
14013 ExprResult AlignResult =
14014 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14015 if (AlignResult.isInvalid())
14016 return nullptr;
14017 Alignment = AlignResult.get();
14018 }
14019 if (Vars.empty())
14020 return nullptr;
14021
14022 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14023 EndLoc, Vars, Alignment);
14024}
14025
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014026OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14027 SourceLocation StartLoc,
14028 SourceLocation LParenLoc,
14029 SourceLocation EndLoc) {
14030 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014031 SmallVector<Expr *, 8> SrcExprs;
14032 SmallVector<Expr *, 8> DstExprs;
14033 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014034 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014035 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14036 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014037 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014038 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014039 SrcExprs.push_back(nullptr);
14040 DstExprs.push_back(nullptr);
14041 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014042 continue;
14043 }
14044
Alexey Bataeved09d242014-05-28 05:53:51 +000014045 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014046 // OpenMP [2.1, C/C++]
14047 // A list item is a variable name.
14048 // OpenMP [2.14.4.1, Restrictions, p.1]
14049 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014050 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014051 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014052 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14053 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014054 continue;
14055 }
14056
14057 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014058 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014059
14060 QualType Type = VD->getType();
14061 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14062 // It will be analyzed later.
14063 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014064 SrcExprs.push_back(nullptr);
14065 DstExprs.push_back(nullptr);
14066 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014067 continue;
14068 }
14069
14070 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14071 // A list item that appears in a copyin clause must be threadprivate.
14072 if (!DSAStack->isThreadPrivate(VD)) {
14073 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014074 << getOpenMPClauseName(OMPC_copyin)
14075 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014076 continue;
14077 }
14078
14079 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14080 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014081 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014082 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014083 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14084 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014085 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014086 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014087 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014088 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014089 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014090 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014091 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014092 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014093 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014094 // For arrays generate assignment operation for single element and replace
14095 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014096 ExprResult AssignmentOp =
14097 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14098 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014099 if (AssignmentOp.isInvalid())
14100 continue;
14101 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014102 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014103 if (AssignmentOp.isInvalid())
14104 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014105
14106 DSAStack->addDSA(VD, DE, OMPC_copyin);
14107 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014108 SrcExprs.push_back(PseudoSrcExpr);
14109 DstExprs.push_back(PseudoDstExpr);
14110 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014111 }
14112
Alexey Bataeved09d242014-05-28 05:53:51 +000014113 if (Vars.empty())
14114 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014115
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014116 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14117 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014118}
14119
Alexey Bataevbae9a792014-06-27 10:37:06 +000014120OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14121 SourceLocation StartLoc,
14122 SourceLocation LParenLoc,
14123 SourceLocation EndLoc) {
14124 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014125 SmallVector<Expr *, 8> SrcExprs;
14126 SmallVector<Expr *, 8> DstExprs;
14127 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014128 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014129 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14130 SourceLocation ELoc;
14131 SourceRange ERange;
14132 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014133 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014134 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014135 // It will be analyzed later.
14136 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014137 SrcExprs.push_back(nullptr);
14138 DstExprs.push_back(nullptr);
14139 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014140 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014141 ValueDecl *D = Res.first;
14142 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014143 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014144
Alexey Bataeve122da12016-03-17 10:50:17 +000014145 QualType Type = D->getType();
14146 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014147
14148 // OpenMP [2.14.4.2, Restrictions, p.2]
14149 // A list item that appears in a copyprivate clause may not appear in a
14150 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014151 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014152 DSAStackTy::DSAVarData DVar =
14153 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014154 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14155 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014156 Diag(ELoc, diag::err_omp_wrong_dsa)
14157 << getOpenMPClauseName(DVar.CKind)
14158 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014159 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014160 continue;
14161 }
14162
14163 // OpenMP [2.11.4.2, Restrictions, p.1]
14164 // All list items that appear in a copyprivate clause must be either
14165 // threadprivate or private in the enclosing context.
14166 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014167 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014168 if (DVar.CKind == OMPC_shared) {
14169 Diag(ELoc, diag::err_omp_required_access)
14170 << getOpenMPClauseName(OMPC_copyprivate)
14171 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014172 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014173 continue;
14174 }
14175 }
14176 }
14177
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014178 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014179 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014180 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014181 << getOpenMPClauseName(OMPC_copyprivate) << Type
14182 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014183 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014184 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014185 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014186 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014187 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014188 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014189 continue;
14190 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014191
Alexey Bataevbae9a792014-06-27 10:37:06 +000014192 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14193 // A variable of class type (or array thereof) that appears in a
14194 // copyin clause requires an accessible, unambiguous copy assignment
14195 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014196 Type = Context.getBaseElementType(Type.getNonReferenceType())
14197 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014198 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014199 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014200 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014201 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14202 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014203 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014204 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014205 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14206 ExprResult AssignmentOp = BuildBinOp(
14207 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014208 if (AssignmentOp.isInvalid())
14209 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014210 AssignmentOp =
14211 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014212 if (AssignmentOp.isInvalid())
14213 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014214
14215 // No need to mark vars as copyprivate, they are already threadprivate or
14216 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014217 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014218 Vars.push_back(
14219 VD ? RefExpr->IgnoreParens()
14220 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014221 SrcExprs.push_back(PseudoSrcExpr);
14222 DstExprs.push_back(PseudoDstExpr);
14223 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014224 }
14225
14226 if (Vars.empty())
14227 return nullptr;
14228
Alexey Bataeva63048e2015-03-23 06:18:07 +000014229 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14230 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014231}
14232
Alexey Bataev6125da92014-07-21 11:26:11 +000014233OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14234 SourceLocation StartLoc,
14235 SourceLocation LParenLoc,
14236 SourceLocation EndLoc) {
14237 if (VarList.empty())
14238 return nullptr;
14239
14240 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14241}
Alexey Bataevdea47612014-07-23 07:46:59 +000014242
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014243OMPClause *
14244Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14245 SourceLocation DepLoc, SourceLocation ColonLoc,
14246 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14247 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014248 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014249 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014250 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014251 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014252 return nullptr;
14253 }
14254 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014255 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14256 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014257 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014258 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014259 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14260 /*Last=*/OMPC_DEPEND_unknown, Except)
14261 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014262 return nullptr;
14263 }
14264 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014265 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014266 llvm::APSInt DepCounter(/*BitWidth=*/32);
14267 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014268 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14269 if (const Expr *OrderedCountExpr =
14270 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014271 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14272 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014273 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014274 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014275 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014276 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14277 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14278 // It will be analyzed later.
14279 Vars.push_back(RefExpr);
14280 continue;
14281 }
14282
14283 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014284 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014285 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014286 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014287 DepCounter >= TotalDepCount) {
14288 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14289 continue;
14290 }
14291 ++DepCounter;
14292 // OpenMP [2.13.9, Summary]
14293 // depend(dependence-type : vec), where dependence-type is:
14294 // 'sink' and where vec is the iteration vector, which has the form:
14295 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14296 // where n is the value specified by the ordered clause in the loop
14297 // directive, xi denotes the loop iteration variable of the i-th nested
14298 // loop associated with the loop directive, and di is a constant
14299 // non-negative integer.
14300 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014301 // It will be analyzed later.
14302 Vars.push_back(RefExpr);
14303 continue;
14304 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014305 SimpleExpr = SimpleExpr->IgnoreImplicit();
14306 OverloadedOperatorKind OOK = OO_None;
14307 SourceLocation OOLoc;
14308 Expr *LHS = SimpleExpr;
14309 Expr *RHS = nullptr;
14310 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14311 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14312 OOLoc = BO->getOperatorLoc();
14313 LHS = BO->getLHS()->IgnoreParenImpCasts();
14314 RHS = BO->getRHS()->IgnoreParenImpCasts();
14315 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14316 OOK = OCE->getOperator();
14317 OOLoc = OCE->getOperatorLoc();
14318 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14319 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14320 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14321 OOK = MCE->getMethodDecl()
14322 ->getNameInfo()
14323 .getName()
14324 .getCXXOverloadedOperator();
14325 OOLoc = MCE->getCallee()->getExprLoc();
14326 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14327 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014328 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014329 SourceLocation ELoc;
14330 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014331 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014332 if (Res.second) {
14333 // It will be analyzed later.
14334 Vars.push_back(RefExpr);
14335 }
14336 ValueDecl *D = Res.first;
14337 if (!D)
14338 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014339
Alexey Bataev17daedf2018-02-15 22:42:57 +000014340 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14341 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14342 continue;
14343 }
14344 if (RHS) {
14345 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14346 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14347 if (RHSRes.isInvalid())
14348 continue;
14349 }
14350 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014351 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014352 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014353 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014354 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014355 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014356 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14357 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014358 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014359 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014360 continue;
14361 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014362 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014363 } else {
14364 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14365 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14366 (ASE &&
14367 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14368 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14369 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14370 << RefExpr->getSourceRange();
14371 continue;
14372 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014373
14374 ExprResult Res;
14375 {
14376 Sema::TentativeAnalysisScope Trap(*this);
14377 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14378 RefExpr->IgnoreParenImpCasts());
14379 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014380 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14381 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14382 << RefExpr->getSourceRange();
14383 continue;
14384 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014385 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014386 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014387 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014388
14389 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14390 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014391 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014392 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14393 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14394 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14395 }
14396 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14397 Vars.empty())
14398 return nullptr;
14399
Alexey Bataev8b427062016-05-25 12:36:08 +000014400 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014401 DepKind, DepLoc, ColonLoc, Vars,
14402 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014403 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14404 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014405 DSAStack->addDoacrossDependClause(C, OpsOffs);
14406 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014407}
Michael Wonge710d542015-08-07 16:16:36 +000014408
14409OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14410 SourceLocation LParenLoc,
14411 SourceLocation EndLoc) {
14412 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014413 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014414
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014415 // OpenMP [2.9.1, Restrictions]
14416 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014417 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014418 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014419 return nullptr;
14420
Alexey Bataev931e19b2017-10-02 16:32:39 +000014421 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014422 OpenMPDirectiveKind CaptureRegion =
14423 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14424 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014425 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014426 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014427 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14428 HelperValStmt = buildPreInits(Context, Captures);
14429 }
14430
Alexey Bataev8451efa2018-01-15 19:06:12 +000014431 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14432 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014433}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014434
Alexey Bataeve3727102018-04-18 15:57:46 +000014435static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014436 DSAStackTy *Stack, QualType QTy,
14437 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014438 NamedDecl *ND;
14439 if (QTy->isIncompleteType(&ND)) {
14440 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14441 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014442 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014443 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14444 !QTy.isTrivialType(SemaRef.Context))
14445 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014446 return true;
14447}
14448
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014449/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014450/// (array section or array subscript) does NOT specify the whole size of the
14451/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014452static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014453 const Expr *E,
14454 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014455 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014456
14457 // If this is an array subscript, it refers to the whole size if the size of
14458 // the dimension is constant and equals 1. Also, an array section assumes the
14459 // format of an array subscript if no colon is used.
14460 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014461 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014462 return ATy->getSize().getSExtValue() != 1;
14463 // Size can't be evaluated statically.
14464 return false;
14465 }
14466
14467 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014468 const Expr *LowerBound = OASE->getLowerBound();
14469 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014470
14471 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014472 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014473 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014474 Expr::EvalResult Result;
14475 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014476 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014477
14478 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014479 if (ConstLowerBound.getSExtValue())
14480 return true;
14481 }
14482
14483 // If we don't have a length we covering the whole dimension.
14484 if (!Length)
14485 return false;
14486
14487 // If the base is a pointer, we don't have a way to get the size of the
14488 // pointee.
14489 if (BaseQTy->isPointerType())
14490 return false;
14491
14492 // We can only check if the length is the same as the size of the dimension
14493 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014494 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014495 if (!CATy)
14496 return false;
14497
Fangrui Song407659a2018-11-30 23:41:18 +000014498 Expr::EvalResult Result;
14499 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014500 return false; // Can't get the integer value as a constant.
14501
Fangrui Song407659a2018-11-30 23:41:18 +000014502 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014503 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14504}
14505
14506// Return true if it can be proven that the provided array expression (array
14507// section or array subscript) does NOT specify a single element of the array
14508// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014509static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014510 const Expr *E,
14511 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014512 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014513
14514 // An array subscript always refer to a single element. Also, an array section
14515 // assumes the format of an array subscript if no colon is used.
14516 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14517 return false;
14518
14519 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014520 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014521
14522 // If we don't have a length we have to check if the array has unitary size
14523 // for this dimension. Also, we should always expect a length if the base type
14524 // is pointer.
14525 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014526 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014527 return ATy->getSize().getSExtValue() != 1;
14528 // We cannot assume anything.
14529 return false;
14530 }
14531
14532 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014533 Expr::EvalResult Result;
14534 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014535 return false; // Can't get the integer value as a constant.
14536
Fangrui Song407659a2018-11-30 23:41:18 +000014537 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014538 return ConstLength.getSExtValue() != 1;
14539}
14540
Samuel Antao661c0902016-05-26 17:39:58 +000014541// Return the expression of the base of the mappable expression or null if it
14542// cannot be determined and do all the necessary checks to see if the expression
14543// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014544// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014545static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014546 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014547 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014548 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014549 SourceLocation ELoc = E->getExprLoc();
14550 SourceRange ERange = E->getSourceRange();
14551
14552 // The base of elements of list in a map clause have to be either:
14553 // - a reference to variable or field.
14554 // - a member expression.
14555 // - an array expression.
14556 //
14557 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14558 // reference to 'r'.
14559 //
14560 // If we have:
14561 //
14562 // struct SS {
14563 // Bla S;
14564 // foo() {
14565 // #pragma omp target map (S.Arr[:12]);
14566 // }
14567 // }
14568 //
14569 // We want to retrieve the member expression 'this->S';
14570
Alexey Bataeve3727102018-04-18 15:57:46 +000014571 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014572
Samuel Antao5de996e2016-01-22 20:21:36 +000014573 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14574 // If a list item is an array section, it must specify contiguous storage.
14575 //
14576 // For this restriction it is sufficient that we make sure only references
14577 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014578 // exist except in the rightmost expression (unless they cover the whole
14579 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000014580 //
14581 // r.ArrS[3:5].Arr[6:7]
14582 //
14583 // r.ArrS[3:5].x
14584 //
14585 // but these would be valid:
14586 // r.ArrS[3].Arr[6:7]
14587 //
14588 // r.ArrS[3].x
14589
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014590 bool AllowUnitySizeArraySection = true;
14591 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014592
Dmitry Polukhin644a9252016-03-11 07:58:34 +000014593 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014594 E = E->IgnoreParenImpCasts();
14595
14596 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
14597 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000014598 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014599
14600 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014601
14602 // If we got a reference to a declaration, we should not expect any array
14603 // section before that.
14604 AllowUnitySizeArraySection = false;
14605 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014606
14607 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014608 CurComponents.emplace_back(CurE, CurE->getDecl());
14609 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014610 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000014611
14612 if (isa<CXXThisExpr>(BaseE))
14613 // We found a base expression: this->Val.
14614 RelevantExpr = CurE;
14615 else
14616 E = BaseE;
14617
14618 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014619 if (!NoDiagnose) {
14620 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
14621 << CurE->getSourceRange();
14622 return nullptr;
14623 }
14624 if (RelevantExpr)
14625 return nullptr;
14626 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014627 }
14628
14629 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
14630
14631 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
14632 // A bit-field cannot appear in a map clause.
14633 //
14634 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014635 if (!NoDiagnose) {
14636 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
14637 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
14638 return nullptr;
14639 }
14640 if (RelevantExpr)
14641 return nullptr;
14642 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014643 }
14644
14645 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14646 // If the type of a list item is a reference to a type T then the type
14647 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014648 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014649
14650 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
14651 // A list item cannot be a variable that is a member of a structure with
14652 // a union type.
14653 //
Alexey Bataeve3727102018-04-18 15:57:46 +000014654 if (CurType->isUnionType()) {
14655 if (!NoDiagnose) {
14656 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
14657 << CurE->getSourceRange();
14658 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014659 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014660 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014661 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014662
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014663 // If we got a member expression, we should not expect any array section
14664 // before that:
14665 //
14666 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
14667 // If a list item is an element of a structure, only the rightmost symbol
14668 // of the variable reference can be an array section.
14669 //
14670 AllowUnitySizeArraySection = false;
14671 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014672
14673 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014674 CurComponents.emplace_back(CurE, FD);
14675 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014676 E = CurE->getBase()->IgnoreParenImpCasts();
14677
14678 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014679 if (!NoDiagnose) {
14680 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14681 << 0 << CurE->getSourceRange();
14682 return nullptr;
14683 }
14684 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014685 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014686
14687 // If we got an array subscript that express the whole dimension we
14688 // can have any array expressions before. If it only expressing part of
14689 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000014690 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014691 E->getType()))
14692 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014693
Patrick Lystere13b1e32019-01-02 19:28:48 +000014694 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14695 Expr::EvalResult Result;
14696 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
14697 if (!Result.Val.getInt().isNullValue()) {
14698 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14699 diag::err_omp_invalid_map_this_expr);
14700 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14701 diag::note_omp_invalid_subscript_on_this_ptr_map);
14702 }
14703 }
14704 RelevantExpr = TE;
14705 }
14706
Samuel Antao90927002016-04-26 14:54:23 +000014707 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014708 CurComponents.emplace_back(CurE, nullptr);
14709 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014710 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000014711 E = CurE->getBase()->IgnoreParenImpCasts();
14712
Alexey Bataev27041fa2017-12-05 15:22:49 +000014713 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014714 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14715
Samuel Antao5de996e2016-01-22 20:21:36 +000014716 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14717 // If the type of a list item is a reference to a type T then the type
14718 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000014719 if (CurType->isReferenceType())
14720 CurType = CurType->getPointeeType();
14721
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014722 bool IsPointer = CurType->isAnyPointerType();
14723
14724 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014725 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14726 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014727 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014728 }
14729
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014730 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000014731 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014732 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000014733 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014734
Samuel Antaodab51bb2016-07-18 23:22:11 +000014735 if (AllowWholeSizeArraySection) {
14736 // Any array section is currently allowed. Allowing a whole size array
14737 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014738 //
14739 // If this array section refers to the whole dimension we can still
14740 // accept other array sections before this one, except if the base is a
14741 // pointer. Otherwise, only unitary sections are accepted.
14742 if (NotWhole || IsPointer)
14743 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000014744 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014745 // A unity or whole array section is not allowed and that is not
14746 // compatible with the properties of the current array section.
14747 SemaRef.Diag(
14748 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
14749 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014750 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014751 }
Samuel Antao90927002016-04-26 14:54:23 +000014752
Patrick Lystere13b1e32019-01-02 19:28:48 +000014753 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14754 Expr::EvalResult ResultR;
14755 Expr::EvalResult ResultL;
14756 if (CurE->getLength()->EvaluateAsInt(ResultR,
14757 SemaRef.getASTContext())) {
14758 if (!ResultR.Val.getInt().isOneValue()) {
14759 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14760 diag::err_omp_invalid_map_this_expr);
14761 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14762 diag::note_omp_invalid_length_on_this_ptr_mapping);
14763 }
14764 }
14765 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
14766 ResultL, SemaRef.getASTContext())) {
14767 if (!ResultL.Val.getInt().isNullValue()) {
14768 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14769 diag::err_omp_invalid_map_this_expr);
14770 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14771 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
14772 }
14773 }
14774 RelevantExpr = TE;
14775 }
14776
Samuel Antao90927002016-04-26 14:54:23 +000014777 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014778 CurComponents.emplace_back(CurE, nullptr);
14779 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014780 if (!NoDiagnose) {
14781 // If nothing else worked, this is not a valid map clause expression.
14782 SemaRef.Diag(
14783 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
14784 << ERange;
14785 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000014786 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014787 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014788 }
14789
14790 return RelevantExpr;
14791}
14792
14793// Return true if expression E associated with value VD has conflicts with other
14794// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000014795static bool checkMapConflicts(
14796 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000014797 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000014798 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
14799 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014800 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000014801 SourceLocation ELoc = E->getExprLoc();
14802 SourceRange ERange = E->getSourceRange();
14803
14804 // In order to easily check the conflicts we need to match each component of
14805 // the expression under test with the components of the expressions that are
14806 // already in the stack.
14807
Samuel Antao5de996e2016-01-22 20:21:36 +000014808 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014809 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014810 "Map clause expression with unexpected base!");
14811
14812 // Variables to help detecting enclosing problems in data environment nests.
14813 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000014814 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014815
Samuel Antao90927002016-04-26 14:54:23 +000014816 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
14817 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000014818 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
14819 ERange, CKind, &EnclosingExpr,
14820 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
14821 StackComponents,
14822 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014823 assert(!StackComponents.empty() &&
14824 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014825 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014826 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000014827 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014828
Samuel Antao90927002016-04-26 14:54:23 +000014829 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000014830 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000014831
Samuel Antao5de996e2016-01-22 20:21:36 +000014832 // Expressions must start from the same base. Here we detect at which
14833 // point both expressions diverge from each other and see if we can
14834 // detect if the memory referred to both expressions is contiguous and
14835 // do not overlap.
14836 auto CI = CurComponents.rbegin();
14837 auto CE = CurComponents.rend();
14838 auto SI = StackComponents.rbegin();
14839 auto SE = StackComponents.rend();
14840 for (; CI != CE && SI != SE; ++CI, ++SI) {
14841
14842 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
14843 // At most one list item can be an array item derived from a given
14844 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000014845 if (CurrentRegionOnly &&
14846 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
14847 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
14848 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
14849 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
14850 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000014851 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000014852 << CI->getAssociatedExpression()->getSourceRange();
14853 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
14854 diag::note_used_here)
14855 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000014856 return true;
14857 }
14858
14859 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000014860 if (CI->getAssociatedExpression()->getStmtClass() !=
14861 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000014862 break;
14863
14864 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000014865 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000014866 break;
14867 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000014868 // Check if the extra components of the expressions in the enclosing
14869 // data environment are redundant for the current base declaration.
14870 // If they are, the maps completely overlap, which is legal.
14871 for (; SI != SE; ++SI) {
14872 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000014873 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000014874 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000014875 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014876 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000014877 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014878 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000014879 Type =
14880 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14881 }
14882 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000014883 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000014884 SemaRef, SI->getAssociatedExpression(), Type))
14885 break;
14886 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014887
14888 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14889 // List items of map clauses in the same construct must not share
14890 // original storage.
14891 //
14892 // If the expressions are exactly the same or one is a subset of the
14893 // other, it means they are sharing storage.
14894 if (CI == CE && SI == SE) {
14895 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014896 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000014897 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014898 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014899 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014900 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14901 << ERange;
14902 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014903 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14904 << RE->getSourceRange();
14905 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014906 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014907 // If we find the same expression in the enclosing data environment,
14908 // that is legal.
14909 IsEnclosedByDataEnvironmentExpr = true;
14910 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000014911 }
14912
Samuel Antao90927002016-04-26 14:54:23 +000014913 QualType DerivedType =
14914 std::prev(CI)->getAssociatedDeclaration()->getType();
14915 SourceLocation DerivedLoc =
14916 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000014917
14918 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14919 // If the type of a list item is a reference to a type T then the type
14920 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000014921 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014922
14923 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
14924 // A variable for which the type is pointer and an array section
14925 // derived from that variable must not appear as list items of map
14926 // clauses of the same construct.
14927 //
14928 // Also, cover one of the cases in:
14929 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
14930 // If any part of the original storage of a list item has corresponding
14931 // storage in the device data environment, all of the original storage
14932 // must have corresponding storage in the device data environment.
14933 //
14934 if (DerivedType->isAnyPointerType()) {
14935 if (CI == CE || SI == SE) {
14936 SemaRef.Diag(
14937 DerivedLoc,
14938 diag::err_omp_pointer_mapped_along_with_derived_section)
14939 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000014940 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14941 << RE->getSourceRange();
14942 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000014943 }
14944 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000014945 SI->getAssociatedExpression()->getStmtClass() ||
14946 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
14947 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014948 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000014949 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000014950 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000014951 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14952 << RE->getSourceRange();
14953 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014954 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014955 }
14956
14957 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14958 // List items of map clauses in the same construct must not share
14959 // original storage.
14960 //
14961 // An expression is a subset of the other.
14962 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014963 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000014964 if (CI != CE || SI != SE) {
14965 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
14966 // a pointer.
14967 auto Begin =
14968 CI != CE ? CurComponents.begin() : StackComponents.begin();
14969 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
14970 auto It = Begin;
14971 while (It != End && !It->getAssociatedDeclaration())
14972 std::advance(It, 1);
14973 assert(It != End &&
14974 "Expected at least one component with the declaration.");
14975 if (It != Begin && It->getAssociatedDeclaration()
14976 ->getType()
14977 .getCanonicalType()
14978 ->isAnyPointerType()) {
14979 IsEnclosedByDataEnvironmentExpr = false;
14980 EnclosingExpr = nullptr;
14981 return false;
14982 }
14983 }
Samuel Antao661c0902016-05-26 17:39:58 +000014984 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014985 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014986 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014987 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14988 << ERange;
14989 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014990 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14991 << RE->getSourceRange();
14992 return true;
14993 }
14994
14995 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000014996 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000014997 if (!CurrentRegionOnly && SI != SE)
14998 EnclosingExpr = RE;
14999
15000 // The current expression is a subset of the expression in the data
15001 // environment.
15002 IsEnclosedByDataEnvironmentExpr |=
15003 (!CurrentRegionOnly && CI != CE && SI == SE);
15004
15005 return false;
15006 });
15007
15008 if (CurrentRegionOnly)
15009 return FoundError;
15010
15011 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15012 // If any part of the original storage of a list item has corresponding
15013 // storage in the device data environment, all of the original storage must
15014 // have corresponding storage in the device data environment.
15015 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15016 // If a list item is an element of a structure, and a different element of
15017 // the structure has a corresponding list item in the device data environment
15018 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015019 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015020 // data environment prior to the task encountering the construct.
15021 //
15022 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15023 SemaRef.Diag(ELoc,
15024 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15025 << ERange;
15026 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15027 << EnclosingExpr->getSourceRange();
15028 return true;
15029 }
15030
15031 return FoundError;
15032}
15033
Michael Kruse4304e9d2019-02-19 16:38:20 +000015034// Look up the user-defined mapper given the mapper name and mapped type, and
15035// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015036static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15037 CXXScopeSpec &MapperIdScopeSpec,
15038 const DeclarationNameInfo &MapperId,
15039 QualType Type,
15040 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015041 if (MapperIdScopeSpec.isInvalid())
15042 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015043 // Get the actual type for the array type.
15044 if (Type->isArrayType()) {
15045 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15046 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15047 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015048 // Find all user-defined mappers with the given MapperId.
15049 SmallVector<UnresolvedSet<8>, 4> Lookups;
15050 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15051 Lookup.suppressDiagnostics();
15052 if (S) {
15053 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15054 NamedDecl *D = Lookup.getRepresentativeDecl();
15055 while (S && !S->isDeclScope(D))
15056 S = S->getParent();
15057 if (S)
15058 S = S->getParent();
15059 Lookups.emplace_back();
15060 Lookups.back().append(Lookup.begin(), Lookup.end());
15061 Lookup.clear();
15062 }
15063 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15064 // Extract the user-defined mappers with the given MapperId.
15065 Lookups.push_back(UnresolvedSet<8>());
15066 for (NamedDecl *D : ULE->decls()) {
15067 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15068 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15069 Lookups.back().addDecl(DMD);
15070 }
15071 }
15072 // Defer the lookup for dependent types. The results will be passed through
15073 // UnresolvedMapper on instantiation.
15074 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15075 Type->isInstantiationDependentType() ||
15076 Type->containsUnexpandedParameterPack() ||
15077 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15078 return !D->isInvalidDecl() &&
15079 (D->getType()->isDependentType() ||
15080 D->getType()->isInstantiationDependentType() ||
15081 D->getType()->containsUnexpandedParameterPack());
15082 })) {
15083 UnresolvedSet<8> URS;
15084 for (const UnresolvedSet<8> &Set : Lookups) {
15085 if (Set.empty())
15086 continue;
15087 URS.append(Set.begin(), Set.end());
15088 }
15089 return UnresolvedLookupExpr::Create(
15090 SemaRef.Context, /*NamingClass=*/nullptr,
15091 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15092 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15093 }
Michael Kruse945249b2019-09-26 22:53:01 +000015094 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015095 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15096 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015097 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15098 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15099 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15100 return ExprError();
15101 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015102 // Perform argument dependent lookup.
15103 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15104 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15105 // Return the first user-defined mapper with the desired type.
15106 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15107 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15108 if (!D->isInvalidDecl() &&
15109 SemaRef.Context.hasSameType(D->getType(), Type))
15110 return D;
15111 return nullptr;
15112 }))
15113 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15114 // Find the first user-defined mapper with a type derived from the desired
15115 // type.
15116 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15117 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15118 if (!D->isInvalidDecl() &&
15119 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15120 !Type.isMoreQualifiedThan(D->getType()))
15121 return D;
15122 return nullptr;
15123 })) {
15124 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15125 /*DetectVirtual=*/false);
15126 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15127 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15128 VD->getType().getUnqualifiedType()))) {
15129 if (SemaRef.CheckBaseClassAccess(
15130 Loc, VD->getType(), Type, Paths.front(),
15131 /*DiagID=*/0) != Sema::AR_inaccessible) {
15132 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15133 }
15134 }
15135 }
15136 }
15137 // Report error if a mapper is specified, but cannot be found.
15138 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15139 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15140 << Type << MapperId.getName();
15141 return ExprError();
15142 }
15143 return ExprEmpty();
15144}
15145
Samuel Antao661c0902016-05-26 17:39:58 +000015146namespace {
15147// Utility struct that gathers all the related lists associated with a mappable
15148// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015149struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015150 // The list of expressions.
15151 ArrayRef<Expr *> VarList;
15152 // The list of processed expressions.
15153 SmallVector<Expr *, 16> ProcessedVarList;
15154 // The mappble components for each expression.
15155 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15156 // The base declaration of the variable.
15157 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015158 // The reference to the user-defined mapper associated with every expression.
15159 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015160
15161 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15162 // We have a list of components and base declarations for each entry in the
15163 // variable list.
15164 VarComponents.reserve(VarList.size());
15165 VarBaseDeclarations.reserve(VarList.size());
15166 }
15167};
15168}
15169
15170// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015171// \a CKind. In the check process the valid expressions, mappable expression
15172// components, variables, and user-defined mappers are extracted and used to
15173// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15174// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15175// and \a MapperId are expected to be valid if the clause kind is 'map'.
15176static void checkMappableExpressionList(
15177 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15178 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015179 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15180 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015181 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015182 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015183 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15184 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015185 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015186
15187 // If the identifier of user-defined mapper is not specified, it is "default".
15188 // We do not change the actual name in this clause to distinguish whether a
15189 // mapper is specified explicitly, i.e., it is not explicitly specified when
15190 // MapperId.getName() is empty.
15191 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15192 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15193 MapperId.setName(DeclNames.getIdentifier(
15194 &SemaRef.getASTContext().Idents.get("default")));
15195 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015196
15197 // Iterators to find the current unresolved mapper expression.
15198 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15199 bool UpdateUMIt = false;
15200 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015201
Samuel Antao90927002016-04-26 14:54:23 +000015202 // Keep track of the mappable components and base declarations in this clause.
15203 // Each entry in the list is going to have a list of components associated. We
15204 // record each set of the components so that we can build the clause later on.
15205 // In the end we should have the same amount of declarations and component
15206 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015207
Alexey Bataeve3727102018-04-18 15:57:46 +000015208 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015209 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015210 SourceLocation ELoc = RE->getExprLoc();
15211
Michael Kruse4304e9d2019-02-19 16:38:20 +000015212 // Find the current unresolved mapper expression.
15213 if (UpdateUMIt && UMIt != UMEnd) {
15214 UMIt++;
15215 assert(
15216 UMIt != UMEnd &&
15217 "Expect the size of UnresolvedMappers to match with that of VarList");
15218 }
15219 UpdateUMIt = true;
15220 if (UMIt != UMEnd)
15221 UnresolvedMapper = *UMIt;
15222
Alexey Bataeve3727102018-04-18 15:57:46 +000015223 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015224
15225 if (VE->isValueDependent() || VE->isTypeDependent() ||
15226 VE->isInstantiationDependent() ||
15227 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015228 // Try to find the associated user-defined mapper.
15229 ExprResult ER = buildUserDefinedMapperRef(
15230 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15231 VE->getType().getCanonicalType(), UnresolvedMapper);
15232 if (ER.isInvalid())
15233 continue;
15234 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015235 // We can only analyze this information once the missing information is
15236 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015237 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015238 continue;
15239 }
15240
Alexey Bataeve3727102018-04-18 15:57:46 +000015241 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015242
Samuel Antao5de996e2016-01-22 20:21:36 +000015243 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015244 SemaRef.Diag(ELoc,
15245 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015246 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015247 continue;
15248 }
15249
Samuel Antao90927002016-04-26 14:54:23 +000015250 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15251 ValueDecl *CurDeclaration = nullptr;
15252
15253 // Obtain the array or member expression bases if required. Also, fill the
15254 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015255 const Expr *BE = checkMapClauseExpressionBase(
15256 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015257 if (!BE)
15258 continue;
15259
Samuel Antao90927002016-04-26 14:54:23 +000015260 assert(!CurComponents.empty() &&
15261 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015262
Patrick Lystere13b1e32019-01-02 19:28:48 +000015263 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15264 // Add store "this" pointer to class in DSAStackTy for future checking
15265 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015266 // Try to find the associated user-defined mapper.
15267 ExprResult ER = buildUserDefinedMapperRef(
15268 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15269 VE->getType().getCanonicalType(), UnresolvedMapper);
15270 if (ER.isInvalid())
15271 continue;
15272 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015273 // Skip restriction checking for variable or field declarations
15274 MVLI.ProcessedVarList.push_back(RE);
15275 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15276 MVLI.VarComponents.back().append(CurComponents.begin(),
15277 CurComponents.end());
15278 MVLI.VarBaseDeclarations.push_back(nullptr);
15279 continue;
15280 }
15281
Samuel Antao90927002016-04-26 14:54:23 +000015282 // For the following checks, we rely on the base declaration which is
15283 // expected to be associated with the last component. The declaration is
15284 // expected to be a variable or a field (if 'this' is being mapped).
15285 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15286 assert(CurDeclaration && "Null decl on map clause.");
15287 assert(
15288 CurDeclaration->isCanonicalDecl() &&
15289 "Expecting components to have associated only canonical declarations.");
15290
15291 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015292 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015293
15294 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015295 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015296
15297 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015298 // threadprivate variables cannot appear in a map clause.
15299 // OpenMP 4.5 [2.10.5, target update Construct]
15300 // threadprivate variables cannot appear in a from clause.
15301 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015302 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015303 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15304 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015305 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015306 continue;
15307 }
15308
Samuel Antao5de996e2016-01-22 20:21:36 +000015309 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15310 // A list item cannot appear in both a map clause and a data-sharing
15311 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015312
Samuel Antao5de996e2016-01-22 20:21:36 +000015313 // Check conflicts with other map clause expressions. We check the conflicts
15314 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015315 // environment, because the restrictions are different. We only have to
15316 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015317 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015318 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015319 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015320 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015321 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015322 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015323 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015324
Samuel Antao661c0902016-05-26 17:39:58 +000015325 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015326 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15327 // If the type of a list item is a reference to a type T then the type will
15328 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015329 auto I = llvm::find_if(
15330 CurComponents,
15331 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15332 return MC.getAssociatedDeclaration();
15333 });
15334 assert(I != CurComponents.end() && "Null decl on map clause.");
15335 QualType Type =
15336 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015337
Samuel Antao661c0902016-05-26 17:39:58 +000015338 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15339 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015340 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015341 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015342 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015343 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015344 continue;
15345
Samuel Antao661c0902016-05-26 17:39:58 +000015346 if (CKind == OMPC_map) {
15347 // target enter data
15348 // OpenMP [2.10.2, Restrictions, p. 99]
15349 // A map-type must be specified in all map clauses and must be either
15350 // to or alloc.
15351 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15352 if (DKind == OMPD_target_enter_data &&
15353 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15354 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15355 << (IsMapTypeImplicit ? 1 : 0)
15356 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15357 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015358 continue;
15359 }
Samuel Antao661c0902016-05-26 17:39:58 +000015360
15361 // target exit_data
15362 // OpenMP [2.10.3, Restrictions, p. 102]
15363 // A map-type must be specified in all map clauses and must be either
15364 // from, release, or delete.
15365 if (DKind == OMPD_target_exit_data &&
15366 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15367 MapType == OMPC_MAP_delete)) {
15368 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15369 << (IsMapTypeImplicit ? 1 : 0)
15370 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15371 << getOpenMPDirectiveName(DKind);
15372 continue;
15373 }
15374
15375 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15376 // A list item cannot appear in both a map clause and a data-sharing
15377 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015378 //
15379 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15380 // A list item cannot appear in both a map clause and a data-sharing
15381 // attribute clause on the same construct unless the construct is a
15382 // combined construct.
15383 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15384 isOpenMPTargetExecutionDirective(DKind)) ||
15385 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015386 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015387 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015388 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015389 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015390 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015391 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015392 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015393 continue;
15394 }
15395 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015396 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015397
Michael Kruse01f670d2019-02-22 22:29:42 +000015398 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015399 ExprResult ER = buildUserDefinedMapperRef(
15400 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15401 Type.getCanonicalType(), UnresolvedMapper);
15402 if (ER.isInvalid())
15403 continue;
15404 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015405
Samuel Antao90927002016-04-26 14:54:23 +000015406 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015407 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015408
15409 // Store the components in the stack so that they can be used to check
15410 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015411 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15412 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015413
15414 // Save the components and declaration to create the clause. For purposes of
15415 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015416 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015417 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15418 MVLI.VarComponents.back().append(CurComponents.begin(),
15419 CurComponents.end());
15420 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15421 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015422 }
Samuel Antao661c0902016-05-26 17:39:58 +000015423}
15424
Michael Kruse4304e9d2019-02-19 16:38:20 +000015425OMPClause *Sema::ActOnOpenMPMapClause(
15426 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15427 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15428 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15429 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15430 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15431 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15432 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15433 OMPC_MAP_MODIFIER_unknown,
15434 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015435 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15436
15437 // Process map-type-modifiers, flag errors for duplicate modifiers.
15438 unsigned Count = 0;
15439 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15440 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15441 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15442 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15443 continue;
15444 }
15445 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015446 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015447 Modifiers[Count] = MapTypeModifiers[I];
15448 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15449 ++Count;
15450 }
15451
Michael Kruse4304e9d2019-02-19 16:38:20 +000015452 MappableVarListInfo MVLI(VarList);
15453 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015454 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15455 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015456
Samuel Antao5de996e2016-01-22 20:21:36 +000015457 // We need to produce a map clause even if we don't have variables so that
15458 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015459 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15460 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15461 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15462 MapperIdScopeSpec.getWithLocInContext(Context),
15463 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015464}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015465
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015466QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15467 TypeResult ParsedType) {
15468 assert(ParsedType.isUsable());
15469
15470 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15471 if (ReductionType.isNull())
15472 return QualType();
15473
15474 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15475 // A type name in a declare reduction directive cannot be a function type, an
15476 // array type, a reference type, or a type qualified with const, volatile or
15477 // restrict.
15478 if (ReductionType.hasQualifiers()) {
15479 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15480 return QualType();
15481 }
15482
15483 if (ReductionType->isFunctionType()) {
15484 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15485 return QualType();
15486 }
15487 if (ReductionType->isReferenceType()) {
15488 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15489 return QualType();
15490 }
15491 if (ReductionType->isArrayType()) {
15492 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15493 return QualType();
15494 }
15495 return ReductionType;
15496}
15497
15498Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15499 Scope *S, DeclContext *DC, DeclarationName Name,
15500 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15501 AccessSpecifier AS, Decl *PrevDeclInScope) {
15502 SmallVector<Decl *, 8> Decls;
15503 Decls.reserve(ReductionTypes.size());
15504
15505 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015506 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015507 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15508 // A reduction-identifier may not be re-declared in the current scope for the
15509 // same type or for a type that is compatible according to the base language
15510 // rules.
15511 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15512 OMPDeclareReductionDecl *PrevDRD = nullptr;
15513 bool InCompoundScope = true;
15514 if (S != nullptr) {
15515 // Find previous declaration with the same name not referenced in other
15516 // declarations.
15517 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15518 InCompoundScope =
15519 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15520 LookupName(Lookup, S);
15521 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15522 /*AllowInlineNamespace=*/false);
15523 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015524 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015525 while (Filter.hasNext()) {
15526 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15527 if (InCompoundScope) {
15528 auto I = UsedAsPrevious.find(PrevDecl);
15529 if (I == UsedAsPrevious.end())
15530 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015531 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015532 UsedAsPrevious[D] = true;
15533 }
15534 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15535 PrevDecl->getLocation();
15536 }
15537 Filter.done();
15538 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015539 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015540 if (!PrevData.second) {
15541 PrevDRD = PrevData.first;
15542 break;
15543 }
15544 }
15545 }
15546 } else if (PrevDeclInScope != nullptr) {
15547 auto *PrevDRDInScope = PrevDRD =
15548 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15549 do {
15550 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15551 PrevDRDInScope->getLocation();
15552 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15553 } while (PrevDRDInScope != nullptr);
15554 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015555 for (const auto &TyData : ReductionTypes) {
15556 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015557 bool Invalid = false;
15558 if (I != PreviousRedeclTypes.end()) {
15559 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15560 << TyData.first;
15561 Diag(I->second, diag::note_previous_definition);
15562 Invalid = true;
15563 }
15564 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15565 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15566 Name, TyData.first, PrevDRD);
15567 DC->addDecl(DRD);
15568 DRD->setAccess(AS);
15569 Decls.push_back(DRD);
15570 if (Invalid)
15571 DRD->setInvalidDecl();
15572 else
15573 PrevDRD = DRD;
15574 }
15575
15576 return DeclGroupPtrTy::make(
15577 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15578}
15579
15580void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15581 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15582
15583 // Enter new function scope.
15584 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015585 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015586 getCurFunction()->setHasOMPDeclareReductionCombiner();
15587
15588 if (S != nullptr)
15589 PushDeclContext(S, DRD);
15590 else
15591 CurContext = DRD;
15592
Faisal Valid143a0c2017-04-01 21:30:49 +000015593 PushExpressionEvaluationContext(
15594 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015595
15596 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015597 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
15598 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
15599 // uses semantics of argument handles by value, but it should be passed by
15600 // reference. C lang does not support references, so pass all parameters as
15601 // pointers.
15602 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015603 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015604 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015605 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
15606 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
15607 // uses semantics of argument handles by value, but it should be passed by
15608 // reference. C lang does not support references, so pass all parameters as
15609 // pointers.
15610 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015611 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015612 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
15613 if (S != nullptr) {
15614 PushOnScopeChains(OmpInParm, S);
15615 PushOnScopeChains(OmpOutParm, S);
15616 } else {
15617 DRD->addDecl(OmpInParm);
15618 DRD->addDecl(OmpOutParm);
15619 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015620 Expr *InE =
15621 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
15622 Expr *OutE =
15623 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
15624 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015625}
15626
15627void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
15628 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15629 DiscardCleanupsInEvaluationContext();
15630 PopExpressionEvaluationContext();
15631
15632 PopDeclContext();
15633 PopFunctionScopeInfo();
15634
15635 if (Combiner != nullptr)
15636 DRD->setCombiner(Combiner);
15637 else
15638 DRD->setInvalidDecl();
15639}
15640
Alexey Bataev070f43a2017-09-06 14:49:58 +000015641VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015642 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15643
15644 // Enter new function scope.
15645 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015646 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015647
15648 if (S != nullptr)
15649 PushDeclContext(S, DRD);
15650 else
15651 CurContext = DRD;
15652
Faisal Valid143a0c2017-04-01 21:30:49 +000015653 PushExpressionEvaluationContext(
15654 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015655
15656 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015657 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
15658 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
15659 // uses semantics of argument handles by value, but it should be passed by
15660 // reference. C lang does not support references, so pass all parameters as
15661 // pointers.
15662 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015663 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015664 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015665 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
15666 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
15667 // uses semantics of argument handles by value, but it should be passed by
15668 // reference. C lang does not support references, so pass all parameters as
15669 // pointers.
15670 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015671 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015672 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015673 if (S != nullptr) {
15674 PushOnScopeChains(OmpPrivParm, S);
15675 PushOnScopeChains(OmpOrigParm, S);
15676 } else {
15677 DRD->addDecl(OmpPrivParm);
15678 DRD->addDecl(OmpOrigParm);
15679 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015680 Expr *OrigE =
15681 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
15682 Expr *PrivE =
15683 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
15684 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000015685 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015686}
15687
Alexey Bataev070f43a2017-09-06 14:49:58 +000015688void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
15689 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015690 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15691 DiscardCleanupsInEvaluationContext();
15692 PopExpressionEvaluationContext();
15693
15694 PopDeclContext();
15695 PopFunctionScopeInfo();
15696
Alexey Bataev070f43a2017-09-06 14:49:58 +000015697 if (Initializer != nullptr) {
15698 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
15699 } else if (OmpPrivParm->hasInit()) {
15700 DRD->setInitializer(OmpPrivParm->getInit(),
15701 OmpPrivParm->isDirectInit()
15702 ? OMPDeclareReductionDecl::DirectInit
15703 : OMPDeclareReductionDecl::CopyInit);
15704 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015705 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000015706 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015707}
15708
15709Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
15710 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015711 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015712 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015713 if (S)
15714 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
15715 /*AddToContext=*/false);
15716 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015717 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000015718 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015719 }
15720 return DeclReductions;
15721}
15722
Michael Kruse251e1482019-02-01 20:25:04 +000015723TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
15724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15725 QualType T = TInfo->getType();
15726 if (D.isInvalidType())
15727 return true;
15728
15729 if (getLangOpts().CPlusPlus) {
15730 // Check that there are no default arguments (C++ only).
15731 CheckExtraCXXDefaultArguments(D);
15732 }
15733
15734 return CreateParsedType(T, TInfo);
15735}
15736
15737QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
15738 TypeResult ParsedType) {
15739 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
15740
15741 QualType MapperType = GetTypeFromParser(ParsedType.get());
15742 assert(!MapperType.isNull() && "Expect valid mapper type");
15743
15744 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15745 // The type must be of struct, union or class type in C and C++
15746 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
15747 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
15748 return QualType();
15749 }
15750 return MapperType;
15751}
15752
15753OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
15754 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
15755 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
15756 Decl *PrevDeclInScope) {
15757 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
15758 forRedeclarationInCurContext());
15759 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15760 // A mapper-identifier may not be redeclared in the current scope for the
15761 // same type or for a type that is compatible according to the base language
15762 // rules.
15763 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15764 OMPDeclareMapperDecl *PrevDMD = nullptr;
15765 bool InCompoundScope = true;
15766 if (S != nullptr) {
15767 // Find previous declaration with the same name not referenced in other
15768 // declarations.
15769 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15770 InCompoundScope =
15771 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15772 LookupName(Lookup, S);
15773 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15774 /*AllowInlineNamespace=*/false);
15775 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
15776 LookupResult::Filter Filter = Lookup.makeFilter();
15777 while (Filter.hasNext()) {
15778 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
15779 if (InCompoundScope) {
15780 auto I = UsedAsPrevious.find(PrevDecl);
15781 if (I == UsedAsPrevious.end())
15782 UsedAsPrevious[PrevDecl] = false;
15783 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
15784 UsedAsPrevious[D] = true;
15785 }
15786 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15787 PrevDecl->getLocation();
15788 }
15789 Filter.done();
15790 if (InCompoundScope) {
15791 for (const auto &PrevData : UsedAsPrevious) {
15792 if (!PrevData.second) {
15793 PrevDMD = PrevData.first;
15794 break;
15795 }
15796 }
15797 }
15798 } else if (PrevDeclInScope) {
15799 auto *PrevDMDInScope = PrevDMD =
15800 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
15801 do {
15802 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
15803 PrevDMDInScope->getLocation();
15804 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
15805 } while (PrevDMDInScope != nullptr);
15806 }
15807 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
15808 bool Invalid = false;
15809 if (I != PreviousRedeclTypes.end()) {
15810 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
15811 << MapperType << Name;
15812 Diag(I->second, diag::note_previous_definition);
15813 Invalid = true;
15814 }
15815 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
15816 MapperType, VN, PrevDMD);
15817 DC->addDecl(DMD);
15818 DMD->setAccess(AS);
15819 if (Invalid)
15820 DMD->setInvalidDecl();
15821
15822 // Enter new function scope.
15823 PushFunctionScope();
15824 setFunctionHasBranchProtectedScope();
15825
15826 CurContext = DMD;
15827
15828 return DMD;
15829}
15830
15831void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
15832 Scope *S,
15833 QualType MapperType,
15834 SourceLocation StartLoc,
15835 DeclarationName VN) {
15836 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
15837 if (S)
15838 PushOnScopeChains(VD, S);
15839 else
15840 DMD->addDecl(VD);
15841 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
15842 DMD->setMapperVarRef(MapperVarRefExpr);
15843}
15844
15845Sema::DeclGroupPtrTy
15846Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
15847 ArrayRef<OMPClause *> ClauseList) {
15848 PopDeclContext();
15849 PopFunctionScopeInfo();
15850
15851 if (D) {
15852 if (S)
15853 PushOnScopeChains(D, S, /*AddToContext=*/false);
15854 D->CreateClauses(Context, ClauseList);
15855 }
15856
15857 return DeclGroupPtrTy::make(DeclGroupRef(D));
15858}
15859
David Majnemer9d168222016-08-05 17:44:54 +000015860OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000015861 SourceLocation StartLoc,
15862 SourceLocation LParenLoc,
15863 SourceLocation EndLoc) {
15864 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015865 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015866
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015867 // OpenMP [teams Constrcut, Restrictions]
15868 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015869 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000015870 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015871 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015872
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015873 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015874 OpenMPDirectiveKind CaptureRegion =
15875 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
15876 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015877 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015878 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015879 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15880 HelperValStmt = buildPreInits(Context, Captures);
15881 }
15882
15883 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
15884 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000015885}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015886
15887OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
15888 SourceLocation StartLoc,
15889 SourceLocation LParenLoc,
15890 SourceLocation EndLoc) {
15891 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015892 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015893
15894 // OpenMP [teams Constrcut, Restrictions]
15895 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015896 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000015897 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015898 return nullptr;
15899
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015900 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015901 OpenMPDirectiveKind CaptureRegion =
15902 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
15903 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015904 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015905 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015906 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15907 HelperValStmt = buildPreInits(Context, Captures);
15908 }
15909
15910 return new (Context) OMPThreadLimitClause(
15911 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015912}
Alexey Bataeva0569352015-12-01 10:17:31 +000015913
15914OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
15915 SourceLocation StartLoc,
15916 SourceLocation LParenLoc,
15917 SourceLocation EndLoc) {
15918 Expr *ValExpr = Priority;
15919
15920 // OpenMP [2.9.1, task Constrcut]
15921 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015922 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000015923 /*StrictlyPositive=*/false))
15924 return nullptr;
15925
15926 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15927}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015928
15929OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
15930 SourceLocation StartLoc,
15931 SourceLocation LParenLoc,
15932 SourceLocation EndLoc) {
15933 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000015934 Stmt *HelperValStmt = nullptr;
15935 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015936
15937 // OpenMP [2.9.2, taskloop Constrcut]
15938 // The parameter of the grainsize clause must be a positive integer
15939 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000015940 if (!isNonNegativeIntegerValue(
15941 ValExpr, *this, OMPC_grainsize,
15942 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
15943 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015944 return nullptr;
15945
Alexey Bataevb9c55e22019-10-14 19:29:52 +000015946 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
15947 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015948}
Alexey Bataev382967a2015-12-08 12:06:20 +000015949
15950OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
15951 SourceLocation StartLoc,
15952 SourceLocation LParenLoc,
15953 SourceLocation EndLoc) {
15954 Expr *ValExpr = NumTasks;
15955
15956 // OpenMP [2.9.2, taskloop Constrcut]
15957 // The parameter of the num_tasks clause must be a positive integer
15958 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015959 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000015960 /*StrictlyPositive=*/true))
15961 return nullptr;
15962
15963 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15964}
15965
Alexey Bataev28c75412015-12-15 08:19:24 +000015966OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
15967 SourceLocation LParenLoc,
15968 SourceLocation EndLoc) {
15969 // OpenMP [2.13.2, critical construct, Description]
15970 // ... where hint-expression is an integer constant expression that evaluates
15971 // to a valid lock hint.
15972 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
15973 if (HintExpr.isInvalid())
15974 return nullptr;
15975 return new (Context)
15976 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
15977}
15978
Carlo Bertollib4adf552016-01-15 18:50:31 +000015979OMPClause *Sema::ActOnOpenMPDistScheduleClause(
15980 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15981 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
15982 SourceLocation EndLoc) {
15983 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
15984 std::string Values;
15985 Values += "'";
15986 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
15987 Values += "'";
15988 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15989 << Values << getOpenMPClauseName(OMPC_dist_schedule);
15990 return nullptr;
15991 }
15992 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000015993 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000015994 if (ChunkSize) {
15995 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15996 !ChunkSize->isInstantiationDependent() &&
15997 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015998 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000015999 ExprResult Val =
16000 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16001 if (Val.isInvalid())
16002 return nullptr;
16003
16004 ValExpr = Val.get();
16005
16006 // OpenMP [2.7.1, Restrictions]
16007 // chunk_size must be a loop invariant integer expression with a positive
16008 // value.
16009 llvm::APSInt Result;
16010 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16011 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16012 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16013 << "dist_schedule" << ChunkSize->getSourceRange();
16014 return nullptr;
16015 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016016 } else if (getOpenMPCaptureRegionForClause(
16017 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
16018 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016019 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016020 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016021 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016022 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16023 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016024 }
16025 }
16026 }
16027
16028 return new (Context)
16029 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016030 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016031}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016032
16033OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16034 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16035 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16036 SourceLocation KindLoc, SourceLocation EndLoc) {
16037 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000016038 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016039 std::string Value;
16040 SourceLocation Loc;
16041 Value += "'";
16042 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16043 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000016044 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016045 Loc = MLoc;
16046 } else {
16047 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000016048 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016049 Loc = KindLoc;
16050 }
16051 Value += "'";
16052 Diag(Loc, diag::err_omp_unexpected_clause_value)
16053 << Value << getOpenMPClauseName(OMPC_defaultmap);
16054 return nullptr;
16055 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000016056 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016057
16058 return new (Context)
16059 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16060}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016061
16062bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16063 DeclContext *CurLexicalContext = getCurLexicalContext();
16064 if (!CurLexicalContext->isFileContext() &&
16065 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016066 !CurLexicalContext->isExternCXXContext() &&
16067 !isa<CXXRecordDecl>(CurLexicalContext) &&
16068 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16069 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16070 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016071 Diag(Loc, diag::err_omp_region_not_file_context);
16072 return false;
16073 }
Kelvin Libc38e632018-09-10 02:07:09 +000016074 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016075 return true;
16076}
16077
16078void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016079 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016080 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016081 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016082}
16083
Alexey Bataev729e2422019-08-23 16:11:14 +000016084NamedDecl *
16085Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16086 const DeclarationNameInfo &Id,
16087 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016088 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16089 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16090
16091 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016092 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016093 Lookup.suppressDiagnostics();
16094
16095 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016096 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016097 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016098 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016099 CTK_ErrorRecovery)) {
16100 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16101 << Id.getName());
16102 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016103 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016104 }
16105
16106 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016107 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016108 }
16109
16110 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016111 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16112 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016113 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016114 return nullptr;
16115 }
16116 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16117 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16118 return ND;
16119}
16120
16121void Sema::ActOnOpenMPDeclareTargetName(
16122 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16123 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16124 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16125 isa<FunctionTemplateDecl>(ND)) &&
16126 "Expected variable, function or function template.");
16127
16128 // Diagnose marking after use as it may lead to incorrect diagnosis and
16129 // codegen.
16130 if (LangOpts.OpenMP >= 50 &&
16131 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16132 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16133
16134 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16135 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16136 if (DevTy.hasValue() && *DevTy != DT) {
16137 Diag(Loc, diag::err_omp_device_type_mismatch)
16138 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16139 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16140 return;
16141 }
16142 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16143 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16144 if (!Res) {
16145 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16146 SourceRange(Loc, Loc));
16147 ND->addAttr(A);
16148 if (ASTMutationListener *ML = Context.getASTMutationListener())
16149 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16150 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16151 } else if (*Res != MT) {
16152 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016153 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016154}
16155
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016156static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16157 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016158 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016159 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016160 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016161 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16162 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16163 if (SemaRef.LangOpts.OpenMP >= 50 &&
16164 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16165 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16166 VD->hasGlobalStorage()) {
16167 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16168 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16169 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16170 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16171 // If a lambda declaration and definition appears between a
16172 // declare target directive and the matching end declare target
16173 // directive, all variables that are captured by the lambda
16174 // expression must also appear in a to clause.
16175 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016176 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016177 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16178 << VD << 0 << SR;
16179 return;
16180 }
16181 }
16182 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016183 return;
16184 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16185 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016186}
16187
16188static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16189 Sema &SemaRef, DSAStackTy *Stack,
16190 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016191 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016192 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16193 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016194}
16195
Kelvin Li1ce87c72017-12-12 20:08:12 +000016196void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16197 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016198 if (!D || D->isInvalidDecl())
16199 return;
16200 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016201 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016202 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016203 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016204 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16205 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016206 return;
16207 // 2.10.6: threadprivate variable cannot appear in a declare target
16208 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016209 if (DSAStack->isThreadPrivate(VD)) {
16210 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016211 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016212 return;
16213 }
16214 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016215 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16216 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016217 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016218 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16219 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016220 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016221 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16222 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16223 return;
16224 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016225 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016226 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16227 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16228 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16229 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016230 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016231 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16232 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16233 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016234 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016235 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16236 // Problem if any with var declared with incomplete type will be reported
16237 // as normal, so no need to check it here.
16238 if ((E || !VD->getType()->isIncompleteType()) &&
16239 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16240 return;
16241 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16242 // Checking declaration inside declare target region.
16243 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16244 isa<FunctionTemplateDecl>(D)) {
16245 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016246 Context, OMPDeclareTargetDeclAttr::MT_To,
16247 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016248 D->addAttr(A);
16249 if (ASTMutationListener *ML = Context.getASTMutationListener())
16250 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16251 }
16252 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016253 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016254 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016255 if (!E)
16256 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016257 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16258}
Samuel Antao661c0902016-05-26 17:39:58 +000016259
16260OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016261 CXXScopeSpec &MapperIdScopeSpec,
16262 DeclarationNameInfo &MapperId,
16263 const OMPVarListLocTy &Locs,
16264 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016265 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016266 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16267 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016268 if (MVLI.ProcessedVarList.empty())
16269 return nullptr;
16270
Michael Kruse01f670d2019-02-22 22:29:42 +000016271 return OMPToClause::Create(
16272 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16273 MVLI.VarComponents, MVLI.UDMapperList,
16274 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016275}
Samuel Antaoec172c62016-05-26 17:49:04 +000016276
16277OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016278 CXXScopeSpec &MapperIdScopeSpec,
16279 DeclarationNameInfo &MapperId,
16280 const OMPVarListLocTy &Locs,
16281 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016282 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016283 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16284 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016285 if (MVLI.ProcessedVarList.empty())
16286 return nullptr;
16287
Michael Kruse0336c752019-02-25 20:34:15 +000016288 return OMPFromClause::Create(
16289 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16290 MVLI.VarComponents, MVLI.UDMapperList,
16291 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016292}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016293
16294OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016295 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016296 MappableVarListInfo MVLI(VarList);
16297 SmallVector<Expr *, 8> PrivateCopies;
16298 SmallVector<Expr *, 8> Inits;
16299
Alexey Bataeve3727102018-04-18 15:57:46 +000016300 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016301 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16302 SourceLocation ELoc;
16303 SourceRange ERange;
16304 Expr *SimpleRefExpr = RefExpr;
16305 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16306 if (Res.second) {
16307 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016308 MVLI.ProcessedVarList.push_back(RefExpr);
16309 PrivateCopies.push_back(nullptr);
16310 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016311 }
16312 ValueDecl *D = Res.first;
16313 if (!D)
16314 continue;
16315
16316 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016317 Type = Type.getNonReferenceType().getUnqualifiedType();
16318
16319 auto *VD = dyn_cast<VarDecl>(D);
16320
16321 // Item should be a pointer or reference to pointer.
16322 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016323 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16324 << 0 << RefExpr->getSourceRange();
16325 continue;
16326 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016327
16328 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016329 auto VDPrivate =
16330 buildVarDecl(*this, ELoc, Type, D->getName(),
16331 D->hasAttrs() ? &D->getAttrs() : nullptr,
16332 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016333 if (VDPrivate->isInvalidDecl())
16334 continue;
16335
16336 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016337 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016338 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16339
16340 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016341 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016342 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016343 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16344 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016345 AddInitializerToDecl(VDPrivate,
16346 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016347 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016348
16349 // If required, build a capture to implement the privatization initialized
16350 // with the current list item value.
16351 DeclRefExpr *Ref = nullptr;
16352 if (!VD)
16353 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16354 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16355 PrivateCopies.push_back(VDPrivateRefExpr);
16356 Inits.push_back(VDInitRefExpr);
16357
16358 // We need to add a data sharing attribute for this variable to make sure it
16359 // is correctly captured. A variable that shows up in a use_device_ptr has
16360 // similar properties of a first private variable.
16361 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16362
16363 // Create a mappable component for the list item. List items in this clause
16364 // only need a component.
16365 MVLI.VarBaseDeclarations.push_back(D);
16366 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16367 MVLI.VarComponents.back().push_back(
16368 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016369 }
16370
Samuel Antaocc10b852016-07-28 14:23:26 +000016371 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016372 return nullptr;
16373
Samuel Antaocc10b852016-07-28 14:23:26 +000016374 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016375 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16376 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016377}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016378
16379OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016380 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016381 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016382 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016383 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016384 SourceLocation ELoc;
16385 SourceRange ERange;
16386 Expr *SimpleRefExpr = RefExpr;
16387 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16388 if (Res.second) {
16389 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016390 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016391 }
16392 ValueDecl *D = Res.first;
16393 if (!D)
16394 continue;
16395
16396 QualType Type = D->getType();
16397 // item should be a pointer or array or reference to pointer or array
16398 if (!Type.getNonReferenceType()->isPointerType() &&
16399 !Type.getNonReferenceType()->isArrayType()) {
16400 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16401 << 0 << RefExpr->getSourceRange();
16402 continue;
16403 }
Samuel Antao6890b092016-07-28 14:25:09 +000016404
16405 // Check if the declaration in the clause does not show up in any data
16406 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016407 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016408 if (isOpenMPPrivate(DVar.CKind)) {
16409 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16410 << getOpenMPClauseName(DVar.CKind)
16411 << getOpenMPClauseName(OMPC_is_device_ptr)
16412 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016413 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016414 continue;
16415 }
16416
Alexey Bataeve3727102018-04-18 15:57:46 +000016417 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016418 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016419 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016420 [&ConflictExpr](
16421 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16422 OpenMPClauseKind) -> bool {
16423 ConflictExpr = R.front().getAssociatedExpression();
16424 return true;
16425 })) {
16426 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16427 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16428 << ConflictExpr->getSourceRange();
16429 continue;
16430 }
16431
16432 // Store the components in the stack so that they can be used to check
16433 // against other clauses later on.
16434 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16435 DSAStack->addMappableExpressionComponents(
16436 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16437
16438 // Record the expression we've just processed.
16439 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16440
16441 // Create a mappable component for the list item. List items in this clause
16442 // only need a component. We use a null declaration to signal fields in
16443 // 'this'.
16444 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16445 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16446 "Unexpected device pointer expression!");
16447 MVLI.VarBaseDeclarations.push_back(
16448 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16449 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16450 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016451 }
16452
Samuel Antao6890b092016-07-28 14:25:09 +000016453 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016454 return nullptr;
16455
Michael Kruse4304e9d2019-02-19 16:38:20 +000016456 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16457 MVLI.VarBaseDeclarations,
16458 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016459}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016460
16461OMPClause *Sema::ActOnOpenMPAllocateClause(
16462 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16463 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16464 if (Allocator) {
16465 // OpenMP [2.11.4 allocate Clause, Description]
16466 // allocator is an expression of omp_allocator_handle_t type.
16467 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16468 return nullptr;
16469
16470 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16471 if (AllocatorRes.isInvalid())
16472 return nullptr;
16473 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16474 DSAStack->getOMPAllocatorHandleT(),
16475 Sema::AA_Initializing,
16476 /*AllowExplicit=*/true);
16477 if (AllocatorRes.isInvalid())
16478 return nullptr;
16479 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016480 } else {
16481 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16482 // allocate clauses that appear on a target construct or on constructs in a
16483 // target region must specify an allocator expression unless a requires
16484 // directive with the dynamic_allocators clause is present in the same
16485 // compilation unit.
16486 if (LangOpts.OpenMPIsDevice &&
16487 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16488 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016489 }
16490 // Analyze and build list of variables.
16491 SmallVector<Expr *, 8> Vars;
16492 for (Expr *RefExpr : VarList) {
16493 assert(RefExpr && "NULL expr in OpenMP private clause.");
16494 SourceLocation ELoc;
16495 SourceRange ERange;
16496 Expr *SimpleRefExpr = RefExpr;
16497 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16498 if (Res.second) {
16499 // It will be analyzed later.
16500 Vars.push_back(RefExpr);
16501 }
16502 ValueDecl *D = Res.first;
16503 if (!D)
16504 continue;
16505
16506 auto *VD = dyn_cast<VarDecl>(D);
16507 DeclRefExpr *Ref = nullptr;
16508 if (!VD && !CurContext->isDependentContext())
16509 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16510 Vars.push_back((VD || CurContext->isDependentContext())
16511 ? RefExpr->IgnoreParens()
16512 : Ref);
16513 }
16514
16515 if (Vars.empty())
16516 return nullptr;
16517
16518 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16519 ColonLoc, EndLoc, Vars);
16520}