blob: 64e7b9dcd2d4f21cf5a2d5c0c560764b0732587c [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 Bataev0ee89c12019-12-12 14:13:02 -050026#include "clang/Basic/PartialDiagnostic.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000028#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "clang/Sema/SemaInternal.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060032#include "llvm/ADT/IndexedMap.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000033#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataev36635632020-01-17 20:39:04 -050034#include "llvm/ADT/STLExtras.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060035#include "llvm/Frontend/OpenMP/OMPConstants.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000036using namespace clang;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060037using namespace llvm::omp;
Alexey Bataeva769e072013-03-22 06:34:35 +000038
Alexey Bataev758e55e2013-09-06 18:03:48 +000039//===----------------------------------------------------------------------===//
40// Stack of data-sharing attributes for variables
41//===----------------------------------------------------------------------===//
42
Alexey Bataeve3727102018-04-18 15:57:46 +000043static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000044 Sema &SemaRef, Expr *E,
45 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000046 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000050enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051 DSA_unspecified = 0, /// Data sharing attribute not specified.
52 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
53 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000054};
55
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000056/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000058class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000059public:
Alexey Bataeve3727102018-04-18 15:57:46 +000060 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 OpenMPDirectiveKind DKind = OMPD_unknown;
62 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000063 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000065 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000066 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000067 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
68 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
69 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000070 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataeve3727102018-04-18 15:57:46 +000073 using OperatorOffsetTy =
74 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000075 using DoacrossDependMapTy =
76 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000077
Alexey Bataev758e55e2013-09-06 18:03:48 +000078private:
Alexey Bataeve3727102018-04-18 15:57:46 +000079 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000080 OpenMPClauseKind Attributes = OMPC_unknown;
81 /// Pointer to a reference expression and a flag which shows that the
82 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000083 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000084 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000085 };
Alexey Bataeve3727102018-04-18 15:57:46 +000086 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
Alexey Bataevb6e70842019-12-16 15:54:17 -050087 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
Alexey Bataeve3727102018-04-18 15:57:46 +000088 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
89 using LoopControlVariablesMapTy =
90 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000091 /// Struct that associates a component with the clause kind where they are
92 /// found.
93 struct MappedExprComponentTy {
94 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
95 OpenMPClauseKind Kind = OMPC_unknown;
96 };
Alexey Bataeve3727102018-04-18 15:57:46 +000097 using MappedExprComponentsTy =
98 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
99 using CriticalsWithHintsTy =
100 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000101 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000102 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000103 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000104 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000105 ReductionData() = default;
106 void set(BinaryOperatorKind BO, SourceRange RR) {
107 ReductionRange = RR;
108 ReductionOp = BO;
109 }
110 void set(const Expr *RefExpr, SourceRange RR) {
111 ReductionRange = RR;
112 ReductionOp = RefExpr;
113 }
114 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000115 using DeclReductionMapTy =
116 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500117 struct DefaultmapInfo {
118 OpenMPDefaultmapClauseModifier ImplicitBehavior =
119 OMPC_DEFAULTMAP_MODIFIER_unknown;
120 SourceLocation SLoc;
121 DefaultmapInfo() = default;
122 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
123 : ImplicitBehavior(M), SLoc(Loc) {}
124 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000125
Alexey Bataeve3727102018-04-18 15:57:46 +0000126 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000128 DeclReductionMapTy ReductionMap;
Alexey Bataevb6e70842019-12-16 15:54:17 -0500129 UsedRefMapTy AlignedMap;
130 UsedRefMapTy NontemporalMap;
Samuel Antao90927002016-04-26 14:54:23 +0000131 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000132 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000133 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000134 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500135 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000136 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000137 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000139 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000140 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
141 /// get the data (loop counters etc.) about enclosing loop-based construct.
142 /// This data is required during codegen.
143 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000144 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000145 /// 'ordered' clause, the second one is true if the regions has 'ordered'
146 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000147 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000148 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000149 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000150 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000151 bool NowaitRegion = false;
152 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000153 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000154 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000155 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000156 /// Reference to the taskgroup task_reduction reference expression.
157 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000158 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataevf3c508f2020-01-23 10:47:16 -0500159 SmallVector<Expr *, 4> InnerUsedAllocators;
Alexey Bataeva495c642019-03-11 19:51:42 +0000160 /// List of globals marked as declare target link in this target region
161 /// (isOpenMPTargetExecutionDirective(Directive) == true).
162 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000163 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000164 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000165 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
166 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000167 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000168 };
169
Alexey Bataeve3727102018-04-18 15:57:46 +0000170 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000171
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000172 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000173 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000174 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
175 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000176 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000177 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000178 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000179 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000180 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000181 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000182 /// captured by reference.
183 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000184 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000185 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186
Richard Smith375dec52019-05-30 23:21:14 +0000187 /// Iterators over the stack iterate in order from innermost to outermost
188 /// directive.
189 using const_iterator = StackTy::const_reverse_iterator;
190 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000191 return Stack.empty() ? const_iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000193 }
194 const_iterator end() const {
195 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
196 }
197 using iterator = StackTy::reverse_iterator;
198 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000199 return Stack.empty() ? iterator()
200 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000201 }
202 iterator end() {
203 return Stack.empty() ? iterator() : Stack.back().first.rend();
204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000205
Richard Smith375dec52019-05-30 23:21:14 +0000206 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000207
Alexey Bataev4b465392017-04-26 15:06:24 +0000208 bool isStackEmpty() const {
209 return Stack.empty() ||
210 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000211 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000212 }
Richard Smith375dec52019-05-30 23:21:14 +0000213 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000214 return isStackEmpty() ? 0
215 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000216 }
217
218 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000219 size_t Size = getStackSize();
220 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000221 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000222 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000223 }
224 const SharingMapTy *getTopOfStackOrNull() const {
225 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
226 }
227 SharingMapTy &getTopOfStack() {
228 assert(!isStackEmpty() && "no current directive");
229 return *getTopOfStackOrNull();
230 }
231 const SharingMapTy &getTopOfStack() const {
232 return const_cast<DSAStackTy&>(*this).getTopOfStack();
233 }
234
235 SharingMapTy *getSecondOnStackOrNull() {
236 size_t Size = getStackSize();
237 if (Size <= 1)
238 return nullptr;
239 return &Stack.back().first[Size - 2];
240 }
241 const SharingMapTy *getSecondOnStackOrNull() const {
242 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
243 }
244
245 /// Get the stack element at a certain level (previously returned by
246 /// \c getNestingLevel).
247 ///
248 /// Note that nesting levels count from outermost to innermost, and this is
249 /// the reverse of our iteration order where new inner levels are pushed at
250 /// the front of the stack.
251 SharingMapTy &getStackElemAtLevel(unsigned Level) {
252 assert(Level < getStackSize() && "no such stack element");
253 return Stack.back().first[Level];
254 }
255 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
256 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
257 }
258
259 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
260
261 /// Checks if the variable is a local for OpenMP region.
262 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000263
Kelvin Li1408f912018-09-26 04:28:39 +0000264 /// Vector of previously declared requires directives
265 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000266 /// omp_allocator_handle_t type.
267 QualType OMPAllocatorHandleT;
268 /// Expression for the predefined allocators.
269 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
270 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000271 /// Vector of previously encountered target directives
272 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000273
Alexey Bataev758e55e2013-09-06 18:03:48 +0000274public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000275 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000276
Alexey Bataev27ef9512019-03-20 20:14:22 +0000277 /// Sets omp_allocator_handle_t type.
278 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
279 /// Gets omp_allocator_handle_t type.
280 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
281 /// Sets the given default allocator.
282 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
283 Expr *Allocator) {
284 OMPPredefinedAllocators[AllocatorKind] = Allocator;
285 }
286 /// Returns the specified default allocator.
287 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
288 return OMPPredefinedAllocators[AllocatorKind];
289 }
290
Alexey Bataevaac108a2015-06-23 04:51:00 +0000291 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000292 OpenMPClauseKind getClauseParsingMode() const {
293 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
294 return ClauseKindMode;
295 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000296 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297
Richard Smith0621a8f2019-05-31 00:45:10 +0000298 bool isBodyComplete() const {
299 const SharingMapTy *Top = getTopOfStackOrNull();
300 return Top && Top->BodyComplete;
301 }
302 void setBodyComplete() {
303 getTopOfStack().BodyComplete = true;
304 }
305
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000306 bool isForceVarCapturing() const { return ForceCapturing; }
307 void setForceVarCapturing(bool V) { ForceCapturing = V; }
308
Alexey Bataev60705422018-10-30 15:50:12 +0000309 void setForceCaptureByReferenceInTargetExecutable(bool V) {
310 ForceCaptureByReferenceInTargetExecutable = V;
311 }
312 bool isForceCaptureByReferenceInTargetExecutable() const {
313 return ForceCaptureByReferenceInTargetExecutable;
314 }
315
Alexey Bataev758e55e2013-09-06 18:03:48 +0000316 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000317 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000318 assert(!IgnoredStackElements &&
319 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000320 if (Stack.empty() ||
321 Stack.back().second != CurrentNonCapturingFunctionScope)
322 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
323 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
324 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000325 }
326
327 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000328 assert(!IgnoredStackElements &&
329 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000330 assert(!Stack.back().first.empty() &&
331 "Data-sharing attributes stack is empty!");
332 Stack.back().first.pop_back();
333 }
334
Richard Smith0621a8f2019-05-31 00:45:10 +0000335 /// RAII object to temporarily leave the scope of a directive when we want to
336 /// logically operate in its parent.
337 class ParentDirectiveScope {
338 DSAStackTy &Self;
339 bool Active;
340 public:
341 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
342 : Self(Self), Active(false) {
343 if (Activate)
344 enable();
345 }
346 ~ParentDirectiveScope() { disable(); }
347 void disable() {
348 if (Active) {
349 --Self.IgnoredStackElements;
350 Active = false;
351 }
352 }
353 void enable() {
354 if (!Active) {
355 ++Self.IgnoredStackElements;
356 Active = true;
357 }
358 }
359 };
360
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000361 /// Marks that we're started loop parsing.
362 void loopInit() {
363 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
364 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000365 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000366 }
367 /// Start capturing of the variables in the loop context.
368 void loopStart() {
369 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
370 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000371 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000372 }
373 /// true, if variables are captured, false otherwise.
374 bool isLoopStarted() const {
375 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
376 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000377 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000378 }
379 /// Marks (or clears) declaration as possibly loop counter.
380 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000381 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000382 D ? D->getCanonicalDecl() : D;
383 }
384 /// Gets the possible loop counter decl.
385 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000386 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000387 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000388 /// Start new OpenMP region stack in new non-capturing function.
389 void pushFunction() {
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 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
393 assert(!isa<CapturingScopeInfo>(CurFnScope));
394 CurrentNonCapturingFunctionScope = CurFnScope;
395 }
396 /// Pop region stack for non-capturing function.
397 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000398 assert(!IgnoredStackElements &&
399 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000400 if (!Stack.empty() && Stack.back().second == OldFSI) {
401 assert(Stack.back().first.empty());
402 Stack.pop_back();
403 }
404 CurrentNonCapturingFunctionScope = nullptr;
405 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
406 if (!isa<CapturingScopeInfo>(FSI)) {
407 CurrentNonCapturingFunctionScope = FSI;
408 break;
409 }
410 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000411 }
412
Alexey Bataeve3727102018-04-18 15:57:46 +0000413 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000414 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000415 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000416 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000417 getCriticalWithHint(const DeclarationNameInfo &Name) const {
418 auto I = Criticals.find(Name.getAsString());
419 if (I != Criticals.end())
420 return I->second;
421 return std::make_pair(nullptr, llvm::APSInt());
422 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000423 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000424 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000425 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000426 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexey Bataevb6e70842019-12-16 15:54:17 -0500427 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
428 /// add it and return NULL; otherwise return previous occurrence's expression
429 /// for diagnostics.
430 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000433 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000434 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000435 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000436 /// \return The index of the loop control variable in the list of associated
437 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000438 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000440 /// parent region.
441 /// \return The index of the loop control variable in the list of associated
442 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000443 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000444 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000445 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000446 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000448 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000449 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000450 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451
Alexey Bataevfa312f32017-07-21 18:48:21 +0000452 /// Adds additional information for the reduction items with the reduction id
453 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000454 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000455 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000456 /// Adds additional information for the reduction items with the reduction id
457 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000458 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000459 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000460 /// Returns the location and reduction operation from the innermost parent
461 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000462 const DSAVarData
463 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
464 BinaryOperatorKind &BOK,
465 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000466 /// Returns the location and reduction operation from the innermost parent
467 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000468 const DSAVarData
469 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
470 const Expr *&ReductionRef,
471 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000472 /// Return reduction reference expression for the current taskgroup.
473 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000474 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000475 "taskgroup reference expression requested for non taskgroup "
476 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000477 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000478 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000479 /// Checks if the given \p VD declaration is actually a taskgroup reduction
480 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000481 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000482 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
483 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000484 ->getDecl() == VD;
485 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000486
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000488 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000489 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000490 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000491 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000492 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000493 /// match specified \a CPred predicate in any directive which matches \a DPred
494 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000495 const DSAVarData
496 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
497 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
498 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000499 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000500 /// match specified \a CPred predicate in any innermost directive which
501 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000502 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000503 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000504 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000506 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000507 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000508 /// attributes which match specified \a CPred predicate at the specified
509 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000510 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000511 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000512 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000515 /// specified \a DPred predicate.
516 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000517 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000518 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000519
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000521 bool hasDirective(
522 const llvm::function_ref<bool(
523 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
524 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000525 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000526
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000527 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000528 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000529 const SharingMapTy *Top = getTopOfStackOrNull();
530 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000531 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000533 OpenMPDirectiveKind getDirective(unsigned Level) const {
534 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000535 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000536 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000537 /// Returns the capture region at the specified level.
538 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
539 unsigned OpenMPCaptureLevel) const {
540 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
541 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
542 return CaptureRegions[OpenMPCaptureLevel];
543 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000544 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000545 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000546 const SharingMapTy *Parent = getSecondOnStackOrNull();
547 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000548 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000549
Kelvin Li1408f912018-09-26 04:28:39 +0000550 /// Add requires decl to internal vector
551 void addRequiresDecl(OMPRequiresDecl *RD) {
552 RequiresDecls.push_back(RD);
553 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000554
Alexey Bataev318f431b2019-03-22 15:25:12 +0000555 /// Checks if the defined 'requires' directive has specified type of clause.
556 template <typename ClauseType>
557 bool hasRequiresDeclWithClause() {
558 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
559 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
560 return isa<ClauseType>(C);
561 });
562 });
563 }
564
Kelvin Li1408f912018-09-26 04:28:39 +0000565 /// Checks for a duplicate clause amongst previously declared requires
566 /// directives
567 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
568 bool IsDuplicate = false;
569 for (OMPClause *CNew : ClauseList) {
570 for (const OMPRequiresDecl *D : RequiresDecls) {
571 for (const OMPClause *CPrev : D->clauselists()) {
572 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
573 SemaRef.Diag(CNew->getBeginLoc(),
574 diag::err_omp_requires_clause_redeclaration)
575 << getOpenMPClauseName(CNew->getClauseKind());
576 SemaRef.Diag(CPrev->getBeginLoc(),
577 diag::note_omp_requires_previous_clause)
578 << getOpenMPClauseName(CPrev->getClauseKind());
579 IsDuplicate = true;
580 }
581 }
582 }
583 }
584 return IsDuplicate;
585 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000586
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000587 /// Add location of previously encountered target to internal vector
588 void addTargetDirLocation(SourceLocation LocStart) {
589 TargetLocations.push_back(LocStart);
590 }
591
592 // Return previously encountered target region locations.
593 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
594 return TargetLocations;
595 }
596
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000597 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000598 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000599 getTopOfStack().DefaultAttr = DSA_none;
600 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000601 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000602 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000603 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000604 getTopOfStack().DefaultAttr = DSA_shared;
605 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000606 }
cchene06f3e02019-11-15 13:02:06 -0500607 /// Set default data mapping attribute to Modifier:Kind
608 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
609 OpenMPDefaultmapClauseKind Kind,
610 SourceLocation Loc) {
611 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
612 DMI.ImplicitBehavior = M;
613 DMI.SLoc = Loc;
614 }
615 /// Check whether the implicit-behavior has been set in defaultmap
616 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
617 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
618 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000619 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620
621 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000622 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000623 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000624 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000625 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000626 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000627 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000628 }
cchene06f3e02019-11-15 13:02:06 -0500629 OpenMPDefaultmapClauseModifier
630 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
631 return isStackEmpty()
632 ? OMPC_DEFAULTMAP_MODIFIER_unknown
633 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000634 }
cchene06f3e02019-11-15 13:02:06 -0500635 OpenMPDefaultmapClauseModifier
636 getDefaultmapModifierAtLevel(unsigned Level,
637 OpenMPDefaultmapClauseKind Kind) const {
638 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000639 }
cchene06f3e02019-11-15 13:02:06 -0500640 bool isDefaultmapCapturedByRef(unsigned Level,
641 OpenMPDefaultmapClauseKind Kind) const {
642 OpenMPDefaultmapClauseModifier M =
643 getDefaultmapModifierAtLevel(Level, Kind);
644 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
645 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
646 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
647 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
648 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
649 }
650 return true;
651 }
652 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
653 OpenMPDefaultmapClauseKind Kind) {
654 switch (Kind) {
655 case OMPC_DEFAULTMAP_scalar:
656 case OMPC_DEFAULTMAP_pointer:
657 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
658 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
659 (M == OMPC_DEFAULTMAP_MODIFIER_default);
660 case OMPC_DEFAULTMAP_aggregate:
661 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000662 default:
663 break;
cchene06f3e02019-11-15 13:02:06 -0500664 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000665 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500666 }
667 bool mustBeFirstprivateAtLevel(unsigned Level,
668 OpenMPDefaultmapClauseKind Kind) const {
669 OpenMPDefaultmapClauseModifier M =
670 getDefaultmapModifierAtLevel(Level, Kind);
671 return mustBeFirstprivateBase(M, Kind);
672 }
673 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
674 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
675 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000676 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000678 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000679 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000680 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000681 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000682 }
683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000684 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000685 void setOrderedRegion(bool IsOrdered, const Expr *Param,
686 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000687 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000688 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000689 else
Richard Smith375dec52019-05-30 23:21:14 +0000690 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000691 }
692 /// Returns true, if region is ordered (has associated 'ordered' clause),
693 /// false - otherwise.
694 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000695 if (const SharingMapTy *Top = getTopOfStackOrNull())
696 return Top->OrderedRegion.hasValue();
697 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000698 }
699 /// Returns optional parameter for the ordered region.
700 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000701 if (const SharingMapTy *Top = getTopOfStackOrNull())
702 if (Top->OrderedRegion.hasValue())
703 return Top->OrderedRegion.getValue();
704 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000705 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000706 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000707 /// 'ordered' clause), false - otherwise.
708 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000709 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
710 return Parent->OrderedRegion.hasValue();
711 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000712 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000713 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000714 std::pair<const Expr *, OMPOrderedClause *>
715 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000716 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
717 if (Parent->OrderedRegion.hasValue())
718 return Parent->OrderedRegion.getValue();
719 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000720 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000721 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000722 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000723 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000724 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000725 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000726 /// 'nowait' clause), false - otherwise.
727 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000728 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
729 return Parent->NowaitRegion;
730 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000731 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000732 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000733 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000734 if (SharingMapTy *Parent = getSecondOnStackOrNull())
735 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000736 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000737 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000738 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000739 const SharingMapTy *Top = getTopOfStackOrNull();
740 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000741 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000742
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000743 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000744 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000745 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000746 if (Val > 1)
747 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000748 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000749 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000750 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000751 const SharingMapTy *Top = getTopOfStackOrNull();
752 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000753 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000754 /// Returns true if the construct is associated with multiple loops.
755 bool hasMutipleLoops() const {
756 const SharingMapTy *Top = getTopOfStackOrNull();
757 return Top ? Top->HasMutipleLoops : false;
758 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000760 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000761 /// region.
762 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000763 if (SharingMapTy *Parent = getSecondOnStackOrNull())
764 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000765 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000766 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000767 bool hasInnerTeamsRegion() const {
768 return getInnerTeamsRegionLoc().isValid();
769 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000770 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000771 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000772 const SharingMapTy *Top = getTopOfStackOrNull();
773 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000774 }
775
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000776 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000777 const SharingMapTy *Top = getTopOfStackOrNull();
778 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000779 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000780 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000781 const SharingMapTy *Top = getTopOfStackOrNull();
782 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000783 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000784
Samuel Antao4c8035b2016-12-12 18:00:20 +0000785 /// Do the check specified in \a Check to all component lists and return true
786 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000787 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000788 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000789 const llvm::function_ref<
790 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000791 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000792 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000793 if (isStackEmpty())
794 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000795 auto SI = begin();
796 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000797
798 if (SI == SE)
799 return false;
800
Alexey Bataeve3727102018-04-18 15:57:46 +0000801 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000802 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000803 else
804 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000805
806 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000807 auto MI = SI->MappedExprComponents.find(VD);
808 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000809 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
810 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000811 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000812 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000813 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000814 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000815 }
816
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000817 /// Do the check specified in \a Check to all component lists at a given level
818 /// and return true if any issue is found.
819 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000820 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000821 const llvm::function_ref<
822 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000823 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000824 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000825 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000826 return false;
827
Richard Smith375dec52019-05-30 23:21:14 +0000828 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
829 auto MI = StackElem.MappedExprComponents.find(VD);
830 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000831 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
832 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000833 if (Check(L, MI->second.Kind))
834 return true;
835 return false;
836 }
837
Samuel Antao4c8035b2016-12-12 18:00:20 +0000838 /// Create a new mappable expression component list associated with a given
839 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000840 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000841 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000842 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
843 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000844 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000845 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000846 MEC.Components.resize(MEC.Components.size() + 1);
847 MEC.Components.back().append(Components.begin(), Components.end());
848 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000849 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000850
851 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000852 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000853 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000854 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000855 void addDoacrossDependClause(OMPDependClause *C,
856 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000857 SharingMapTy *Parent = getSecondOnStackOrNull();
858 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
859 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000860 }
861 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
862 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000863 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000864 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000865 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000866 return llvm::make_range(Ref.begin(), Ref.end());
867 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000868 return llvm::make_range(StackElem.DoacrossDepends.end(),
869 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000870 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000871
872 // Store types of classes which have been explicitly mapped
873 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000874 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000875 StackElem.MappedClassesQualTypes.insert(QT);
876 }
877
878 // Return set of mapped classes types
879 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000880 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000881 return StackElem.MappedClassesQualTypes.count(QT) != 0;
882 }
883
Alexey Bataeva495c642019-03-11 19:51:42 +0000884 /// Adds global declare target to the parent target region.
885 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
886 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
887 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
888 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000889 for (auto &Elem : *this) {
890 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
891 Elem.DeclareTargetLinkVarDecls.push_back(E);
892 return;
893 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000894 }
895 }
896
897 /// Returns the list of globals with declare target link if current directive
898 /// is target.
899 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
900 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
901 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000902 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000903 }
Alexey Bataevf3c508f2020-01-23 10:47:16 -0500904
905 /// Adds list of allocators expressions.
906 void addInnerAllocatorExpr(Expr *E) {
907 getTopOfStack().InnerUsedAllocators.push_back(E);
908 }
909 /// Return list of used allocators.
910 ArrayRef<Expr *> getInnerAllocators() const {
911 return getTopOfStack().InnerUsedAllocators;
912 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000913};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000914
915bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
916 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
917}
918
919bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000920 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
921 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000922}
Alexey Bataeve3727102018-04-18 15:57:46 +0000923
Alexey Bataeved09d242014-05-28 05:53:51 +0000924} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000925
Alexey Bataeve3727102018-04-18 15:57:46 +0000926static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000927 if (const auto *FE = dyn_cast<FullExpr>(E))
928 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000929
Alexey Bataeve3727102018-04-18 15:57:46 +0000930 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100931 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000932
Alexey Bataeve3727102018-04-18 15:57:46 +0000933 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000934 E = Binder->getSubExpr();
935
Alexey Bataeve3727102018-04-18 15:57:46 +0000936 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000937 E = ICE->getSubExprAsWritten();
938 return E->IgnoreParens();
939}
940
Alexey Bataeve3727102018-04-18 15:57:46 +0000941static Expr *getExprAsWritten(Expr *E) {
942 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
943}
944
945static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
946 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
947 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000948 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000949 const auto *VD = dyn_cast<VarDecl>(D);
950 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000951 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000952 VD = VD->getCanonicalDecl();
953 D = VD;
954 } else {
955 assert(FD);
956 FD = FD->getCanonicalDecl();
957 D = FD;
958 }
959 return D;
960}
961
Alexey Bataeve3727102018-04-18 15:57:46 +0000962static ValueDecl *getCanonicalDecl(ValueDecl *D) {
963 return const_cast<ValueDecl *>(
964 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
965}
966
Richard Smith375dec52019-05-30 23:21:14 +0000967DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000968 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000969 D = getCanonicalDecl(D);
970 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000971 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000972 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000973 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000974 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
975 // in a region but not in construct]
976 // File-scope or namespace-scope variables referenced in called routines
977 // in the region are shared unless they appear in a threadprivate
978 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000979 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000980 DVar.CKind = OMPC_shared;
981
982 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
983 // in a region but not in construct]
984 // Variables with static storage duration that are declared in called
985 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000986 if (VD && VD->hasGlobalStorage())
987 DVar.CKind = OMPC_shared;
988
989 // Non-static data members are shared by default.
990 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000991 DVar.CKind = OMPC_shared;
992
Alexey Bataev758e55e2013-09-06 18:03:48 +0000993 return DVar;
994 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000995
Alexey Bataevec3da872014-01-31 05:15:34 +0000996 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
997 // in a Construct, C/C++, predetermined, p.1]
998 // Variables with automatic storage duration that are declared in a scope
999 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001000 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1001 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001002 DVar.CKind = OMPC_private;
1003 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +00001004 }
1005
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001006 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001007 // Explicitly specified attributes and local variables with predetermined
1008 // attributes.
1009 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001010 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1011 DVar.RefExpr = Data.RefExpr.getPointer();
1012 DVar.PrivateCopy = Data.PrivateCopy;
1013 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001014 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001015 return DVar;
1016 }
1017
1018 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1019 // in a Construct, C/C++, implicitly determined, p.1]
1020 // In a parallel or task construct, the data-sharing attributes of these
1021 // variables are determined by the default clause, if present.
1022 switch (Iter->DefaultAttr) {
1023 case DSA_shared:
1024 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001025 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001026 return DVar;
1027 case DSA_none:
1028 return DVar;
1029 case DSA_unspecified:
1030 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1031 // in a Construct, implicitly determined, p.2]
1032 // In a parallel construct, if no default clause is present, these
1033 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001034 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001035 if ((isOpenMPParallelDirective(DVar.DKind) &&
1036 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001037 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001038 DVar.CKind = OMPC_shared;
1039 return DVar;
1040 }
1041
1042 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1043 // in a Construct, implicitly determined, p.4]
1044 // In a task construct, if no default clause is present, a variable that in
1045 // the enclosing context is determined to be shared by all implicit tasks
1046 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001047 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001049 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001050 do {
1051 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001052 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001053 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 // In a task construct, if no default clause is present, a variable
1055 // whose data-sharing attribute is not determined by the rules above is
1056 // firstprivate.
1057 DVarTemp = getDSA(I, D);
1058 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001059 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001060 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001061 return DVar;
1062 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001063 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001065 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001066 return DVar;
1067 }
1068 }
1069 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1070 // in a Construct, implicitly determined, p.3]
1071 // For constructs other than task, if no default clause is present, these
1072 // variables inherit their data-sharing attributes from the enclosing
1073 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001074 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001075}
1076
Alexey Bataeve3727102018-04-18 15:57:46 +00001077const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1078 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001079 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001080 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001081 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001082 auto It = StackElem.AlignedMap.find(D);
1083 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001084 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001085 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001086 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001087 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001088 assert(It->second && "Unexpected nullptr expr in the aligned map");
1089 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001090}
1091
Alexey Bataevb6e70842019-12-16 15:54:17 -05001092const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1093 const Expr *NewDE) {
1094 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1095 D = getCanonicalDecl(D);
1096 SharingMapTy &StackElem = getTopOfStack();
1097 auto It = StackElem.NontemporalMap.find(D);
1098 if (It == StackElem.NontemporalMap.end()) {
1099 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1100 StackElem.NontemporalMap[D] = NewDE;
1101 return nullptr;
1102 }
1103 assert(It->second && "Unexpected nullptr expr in the aligned map");
1104 return It->second;
1105}
1106
Alexey Bataeve3727102018-04-18 15:57:46 +00001107void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001108 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001109 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001110 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001111 StackElem.LCVMap.try_emplace(
1112 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001113}
1114
Alexey Bataeve3727102018-04-18 15:57:46 +00001115const DSAStackTy::LCDeclInfo
1116DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001117 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001118 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001119 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001120 auto It = StackElem.LCVMap.find(D);
1121 if (It != StackElem.LCVMap.end())
1122 return It->second;
1123 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001124}
1125
Alexey Bataeve3727102018-04-18 15:57:46 +00001126const DSAStackTy::LCDeclInfo
1127DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001128 const SharingMapTy *Parent = getSecondOnStackOrNull();
1129 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001130 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001131 auto It = Parent->LCVMap.find(D);
1132 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001133 return It->second;
1134 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001135}
1136
Alexey Bataeve3727102018-04-18 15:57:46 +00001137const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001138 const SharingMapTy *Parent = getSecondOnStackOrNull();
1139 assert(Parent && "Data-sharing attributes stack is empty");
1140 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001141 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001142 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001143 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001144 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001145 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001146}
1147
Alexey Bataeve3727102018-04-18 15:57:46 +00001148void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001149 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001150 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001151 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001152 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001153 Data.Attributes = A;
1154 Data.RefExpr.setPointer(E);
1155 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001156 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001157 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001158 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1159 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1160 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1161 (isLoopControlVariable(D).first && A == OMPC_private));
1162 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1163 Data.RefExpr.setInt(/*IntVal=*/true);
1164 return;
1165 }
1166 const bool IsLastprivate =
1167 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1168 Data.Attributes = A;
1169 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1170 Data.PrivateCopy = PrivateCopy;
1171 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001172 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001173 Data.Attributes = A;
1174 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1175 Data.PrivateCopy = nullptr;
1176 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001177 }
1178}
1179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001180/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001181static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001182 StringRef Name, const AttrVec *Attrs = nullptr,
1183 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001184 DeclContext *DC = SemaRef.CurContext;
1185 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1186 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001187 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001188 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1189 if (Attrs) {
1190 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1191 I != E; ++I)
1192 Decl->addAttr(*I);
1193 }
1194 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001195 if (OrigRef) {
1196 Decl->addAttr(
1197 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1198 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001199 return Decl;
1200}
1201
1202static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1203 SourceLocation Loc,
1204 bool RefersToCapture = false) {
1205 D->setReferenced();
1206 D->markUsed(S.Context);
1207 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1208 SourceLocation(), D, RefersToCapture, Loc, Ty,
1209 VK_LValue);
1210}
1211
Alexey Bataeve3727102018-04-18 15:57:46 +00001212void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001213 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001214 D = getCanonicalDecl(D);
1215 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001216 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001217 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001218 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001219 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001220 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001221 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001222 "Additional reduction info may be specified only once for reduction "
1223 "items.");
1224 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001225 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001226 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001227 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001228 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1229 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001230 TaskgroupReductionRef =
1231 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001232 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001233}
1234
Alexey Bataeve3727102018-04-18 15:57:46 +00001235void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001236 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001237 D = getCanonicalDecl(D);
1238 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001239 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001240 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001241 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001242 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001243 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001244 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001245 "Additional reduction info may be specified only once for reduction "
1246 "items.");
1247 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001248 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001249 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001250 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001251 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1252 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001253 TaskgroupReductionRef =
1254 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001255 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001256}
1257
Alexey Bataeve3727102018-04-18 15:57:46 +00001258const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1259 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1260 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001261 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001262 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001263 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001264 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001265 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001266 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001267 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001268 if (!ReductionData.ReductionOp ||
1269 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001270 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001271 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001272 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001273 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1274 "expression for the descriptor is not "
1275 "set.");
1276 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001277 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1278 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001279 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001280 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001281}
1282
Alexey Bataeve3727102018-04-18 15:57:46 +00001283const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1284 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1285 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001286 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001287 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001288 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001289 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001290 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001291 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001292 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001293 if (!ReductionData.ReductionOp ||
1294 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001295 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001296 SR = ReductionData.ReductionRange;
1297 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001298 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1299 "expression for the descriptor is not "
1300 "set.");
1301 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001302 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1303 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001304 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001305 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001306}
1307
Richard Smith375dec52019-05-30 23:21:14 +00001308bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001309 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001310 for (const_iterator E = end(); I != E; ++I) {
1311 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1312 isOpenMPTargetExecutionDirective(I->Directive)) {
1313 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1314 Scope *CurScope = getCurScope();
1315 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1316 CurScope = CurScope->getParent();
1317 return CurScope != TopScope;
1318 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001319 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001320 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001321}
1322
Joel E. Dennyd2649292019-01-04 22:11:56 +00001323static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1324 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001325 bool *IsClassType = nullptr) {
1326 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001327 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001328 bool IsConstant = Type.isConstant(Context);
1329 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001330 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1331 ? Type->getAsCXXRecordDecl()
1332 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001333 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1334 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1335 RD = CTD->getTemplatedDecl();
1336 if (IsClassType)
1337 *IsClassType = RD;
1338 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1339 RD->hasDefinition() && RD->hasMutableFields());
1340}
1341
Joel E. Dennyd2649292019-01-04 22:11:56 +00001342static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1343 QualType Type, OpenMPClauseKind CKind,
1344 SourceLocation ELoc,
1345 bool AcceptIfMutable = true,
1346 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001347 ASTContext &Context = SemaRef.getASTContext();
1348 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001349 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1350 unsigned Diag = ListItemNotVar
1351 ? diag::err_omp_const_list_item
1352 : IsClassType ? diag::err_omp_const_not_mutable_variable
1353 : diag::err_omp_const_variable;
1354 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1355 if (!ListItemNotVar && D) {
1356 const VarDecl *VD = dyn_cast<VarDecl>(D);
1357 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1358 VarDecl::DeclarationOnly;
1359 SemaRef.Diag(D->getLocation(),
1360 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1361 << D;
1362 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001363 return true;
1364 }
1365 return false;
1366}
1367
Alexey Bataeve3727102018-04-18 15:57:46 +00001368const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1369 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001370 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001371 DSAVarData DVar;
1372
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001373 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001374 auto TI = Threadprivates.find(D);
1375 if (TI != Threadprivates.end()) {
1376 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001377 DVar.CKind = OMPC_threadprivate;
1378 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001379 }
1380 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001381 DVar.RefExpr = buildDeclRefExpr(
1382 SemaRef, VD, D->getType().getNonReferenceType(),
1383 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1384 DVar.CKind = OMPC_threadprivate;
1385 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001386 return DVar;
1387 }
1388 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1389 // in a Construct, C/C++, predetermined, p.1]
1390 // Variables appearing in threadprivate directives are threadprivate.
1391 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1392 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1393 SemaRef.getLangOpts().OpenMPUseTLS &&
1394 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1395 (VD && VD->getStorageClass() == SC_Register &&
1396 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1397 DVar.RefExpr = buildDeclRefExpr(
1398 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1399 DVar.CKind = OMPC_threadprivate;
1400 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1401 return DVar;
1402 }
1403 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1404 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1405 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001406 const_iterator IterTarget =
1407 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1408 return isOpenMPTargetExecutionDirective(Data.Directive);
1409 });
1410 if (IterTarget != end()) {
1411 const_iterator ParentIterTarget = IterTarget + 1;
1412 for (const_iterator Iter = begin();
1413 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001414 if (isOpenMPLocal(VD, Iter)) {
1415 DVar.RefExpr =
1416 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1417 D->getLocation());
1418 DVar.CKind = OMPC_threadprivate;
1419 return DVar;
1420 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001421 }
Richard Smith375dec52019-05-30 23:21:14 +00001422 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001423 auto DSAIter = IterTarget->SharingMap.find(D);
1424 if (DSAIter != IterTarget->SharingMap.end() &&
1425 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1426 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1427 DVar.CKind = OMPC_threadprivate;
1428 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001429 }
Richard Smith375dec52019-05-30 23:21:14 +00001430 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001431 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001432 D, std::distance(ParentIterTarget, End),
1433 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001434 DVar.RefExpr =
1435 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1436 IterTarget->ConstructLoc);
1437 DVar.CKind = OMPC_threadprivate;
1438 return DVar;
1439 }
1440 }
1441 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001442 }
1443
Alexey Bataev4b465392017-04-26 15:06:24 +00001444 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001445 // Not in OpenMP execution region and top scope was already checked.
1446 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001447
Alexey Bataev758e55e2013-09-06 18:03:48 +00001448 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001449 // in a Construct, C/C++, predetermined, p.4]
1450 // Static data members are shared.
1451 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1452 // in a Construct, C/C++, predetermined, p.7]
1453 // Variables with static storage duration that are declared in a scope
1454 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001455 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001456 // Check for explicitly specified attributes.
1457 const_iterator I = begin();
1458 const_iterator EndI = end();
1459 if (FromParent && I != EndI)
1460 ++I;
1461 auto It = I->SharingMap.find(D);
1462 if (It != I->SharingMap.end()) {
1463 const DSAInfo &Data = It->getSecond();
1464 DVar.RefExpr = Data.RefExpr.getPointer();
1465 DVar.PrivateCopy = Data.PrivateCopy;
1466 DVar.CKind = Data.Attributes;
1467 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1468 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001469 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001470 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001471
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001472 DVar.CKind = OMPC_shared;
1473 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001474 }
1475
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001476 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001477 // The predetermined shared attribute for const-qualified types having no
1478 // mutable members was removed after OpenMP 3.1.
1479 if (SemaRef.LangOpts.OpenMP <= 31) {
1480 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1481 // in a Construct, C/C++, predetermined, p.6]
1482 // Variables with const qualified type having no mutable member are
1483 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001484 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001485 // Variables with const-qualified type having no mutable member may be
1486 // listed in a firstprivate clause, even if they are static data members.
1487 DSAVarData DVarTemp = hasInnermostDSA(
1488 D,
1489 [](OpenMPClauseKind C) {
1490 return C == OMPC_firstprivate || C == OMPC_shared;
1491 },
1492 MatchesAlways, FromParent);
1493 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1494 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001495
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001496 DVar.CKind = OMPC_shared;
1497 return DVar;
1498 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001499 }
1500
Alexey Bataev758e55e2013-09-06 18:03:48 +00001501 // Explicitly specified attributes and local variables with predetermined
1502 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001503 const_iterator I = begin();
1504 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001505 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001506 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001507 auto It = I->SharingMap.find(D);
1508 if (It != I->SharingMap.end()) {
1509 const DSAInfo &Data = It->getSecond();
1510 DVar.RefExpr = Data.RefExpr.getPointer();
1511 DVar.PrivateCopy = Data.PrivateCopy;
1512 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001513 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001514 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001515 }
1516
1517 return DVar;
1518}
1519
Alexey Bataeve3727102018-04-18 15:57:46 +00001520const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1521 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001522 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001523 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001524 return getDSA(I, D);
1525 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001526 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001527 const_iterator StartI = begin();
1528 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001529 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001530 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001531 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001532}
1533
Alexey Bataeve3727102018-04-18 15:57:46 +00001534const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001535DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001536 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1537 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001538 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001539 if (isStackEmpty())
1540 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001541 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001542 const_iterator I = begin();
1543 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001544 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001545 ++I;
1546 for (; I != EndI; ++I) {
1547 if (!DPred(I->Directive) &&
1548 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001549 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001550 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001551 DSAVarData DVar = getDSA(NewI, D);
1552 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001553 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001554 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001555 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001556}
1557
Alexey Bataeve3727102018-04-18 15:57:46 +00001558const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001559 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1560 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001561 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001562 if (isStackEmpty())
1563 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001564 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001565 const_iterator StartI = begin();
1566 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001567 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001568 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001569 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001570 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001571 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001572 DSAVarData DVar = getDSA(NewI, D);
1573 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001574}
1575
Alexey Bataevaac108a2015-06-23 04:51:00 +00001576bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001577 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1578 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001579 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001580 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001581 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001582 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1583 auto I = StackElem.SharingMap.find(D);
1584 if (I != StackElem.SharingMap.end() &&
1585 I->getSecond().RefExpr.getPointer() &&
1586 CPred(I->getSecond().Attributes) &&
1587 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001588 return true;
1589 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001590 auto LI = StackElem.LCVMap.find(D);
1591 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001592 return CPred(OMPC_private);
1593 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001594}
1595
Samuel Antao4be30e92015-10-02 17:14:03 +00001596bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001597 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1598 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001599 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001600 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001601 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1602 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001603}
1604
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001605bool DSAStackTy::hasDirective(
1606 const llvm::function_ref<bool(OpenMPDirectiveKind,
1607 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001608 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001609 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001610 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001611 size_t Skip = FromParent ? 2 : 1;
1612 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1613 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001614 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1615 return true;
1616 }
1617 return false;
1618}
1619
Alexey Bataev758e55e2013-09-06 18:03:48 +00001620void Sema::InitDataSharingAttributesStack() {
1621 VarDataSharingAttributesStack = new DSAStackTy(*this);
1622}
1623
1624#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1625
Alexey Bataev4b465392017-04-26 15:06:24 +00001626void Sema::pushOpenMPFunctionRegion() {
1627 DSAStack->pushFunction();
1628}
1629
1630void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1631 DSAStack->popFunction(OldFSI);
1632}
1633
Alexey Bataevc416e642019-02-08 18:02:25 +00001634static bool isOpenMPDeviceDelayedContext(Sema &S) {
1635 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1636 "Expected OpenMP device compilation.");
1637 return !S.isInOpenMPTargetExecutionDirective() &&
1638 !S.isInOpenMPDeclareTargetContext();
1639}
1640
Alexey Bataev729e2422019-08-23 16:11:14 +00001641namespace {
1642/// Status of the function emission on the host/device.
1643enum class FunctionEmissionStatus {
1644 Emitted,
1645 Discarded,
1646 Unknown,
1647};
1648} // anonymous namespace
1649
Alexey Bataevc416e642019-02-08 18:02:25 +00001650Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1651 unsigned DiagID) {
1652 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1653 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001654 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001655 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1656 switch (FES) {
1657 case FunctionEmissionStatus::Emitted:
1658 Kind = DeviceDiagBuilder::K_Immediate;
1659 break;
1660 case FunctionEmissionStatus::Unknown:
1661 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1662 : DeviceDiagBuilder::K_Immediate;
1663 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001664 case FunctionEmissionStatus::TemplateDiscarded:
1665 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001666 Kind = DeviceDiagBuilder::K_Nop;
1667 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001668 case FunctionEmissionStatus::CUDADiscarded:
1669 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1670 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001671 }
1672
1673 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1674}
1675
Alexey Bataev729e2422019-08-23 16:11:14 +00001676Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1677 unsigned DiagID) {
1678 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1679 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001680 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001681 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1682 switch (FES) {
1683 case FunctionEmissionStatus::Emitted:
1684 Kind = DeviceDiagBuilder::K_Immediate;
1685 break;
1686 case FunctionEmissionStatus::Unknown:
1687 Kind = DeviceDiagBuilder::K_Deferred;
1688 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001689 case FunctionEmissionStatus::TemplateDiscarded:
1690 case FunctionEmissionStatus::OMPDiscarded:
1691 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001692 Kind = DeviceDiagBuilder::K_Nop;
1693 break;
1694 }
1695
1696 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001697}
1698
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001699void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1700 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001701 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1702 "Expected OpenMP device compilation.");
1703 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001704 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001705 FunctionDecl *Caller = getCurFunctionDecl();
1706
Alexey Bataev729e2422019-08-23 16:11:14 +00001707 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001708 if (Caller) {
1709 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1710 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1711 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1712 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1713 "CUDADiscarded unexpected in OpenMP device function check");
1714 if ((CallerS == FunctionEmissionStatus::Emitted ||
1715 (!isOpenMPDeviceDelayedContext(*this) &&
1716 CallerS == FunctionEmissionStatus::Unknown)) &&
1717 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1718 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1719 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1720 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1721 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1722 diag::note_omp_marked_device_type_here)
1723 << HostDevTy;
1724 return;
1725 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001726 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001727 // If the caller is known-emitted, mark the callee as known-emitted.
1728 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001729 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1730 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001731 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001732 markKnownEmitted(*this, Caller, Callee, Loc,
1733 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001734 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001735 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001736 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001737 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001738 else if (Caller)
1739 DeviceCallGraph[Caller].insert({Callee, Loc});
1740}
1741
Alexey Bataev729e2422019-08-23 16:11:14 +00001742void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1743 bool CheckCaller) {
1744 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1745 "Expected OpenMP host compilation.");
1746 assert(Callee && "Callee may not be null.");
1747 Callee = Callee->getMostRecentDecl();
1748 FunctionDecl *Caller = getCurFunctionDecl();
1749
1750 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001751 if (Caller) {
1752 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1753 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1754 assert(
1755 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1756 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1757 "CUDADiscarded unexpected in OpenMP host function check");
1758 if (CallerS == FunctionEmissionStatus::Emitted &&
1759 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1760 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1761 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1762 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1763 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1764 diag::note_omp_marked_device_type_here)
1765 << NoHostDevTy;
1766 return;
1767 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001768 }
1769 // If the caller is known-emitted, mark the callee as known-emitted.
1770 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001771 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1772 if ((!CheckCaller && !Caller) ||
1773 (Caller &&
1774 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1775 markKnownEmitted(
1776 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1777 return CheckCaller &&
1778 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1779 });
1780 else if (Caller)
1781 DeviceCallGraph[Caller].insert({Callee, Loc});
1782 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001783}
1784
Alexey Bataev123ad192019-02-27 20:29:45 +00001785void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1786 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1787 "OpenMP device compilation mode is expected.");
1788 QualType Ty = E->getType();
1789 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001790 ((Ty->isFloat128Type() ||
1791 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1792 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001793 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1794 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001795 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1796 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1797 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001798}
1799
cchene06f3e02019-11-15 13:02:06 -05001800static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001801getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1802 if (LO.OpenMP <= 45) {
1803 if (VD->getType().getNonReferenceType()->isScalarType())
1804 return OMPC_DEFAULTMAP_scalar;
1805 return OMPC_DEFAULTMAP_aggregate;
1806 }
cchene06f3e02019-11-15 13:02:06 -05001807 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1808 return OMPC_DEFAULTMAP_pointer;
1809 if (VD->getType().getNonReferenceType()->isScalarType())
1810 return OMPC_DEFAULTMAP_scalar;
1811 return OMPC_DEFAULTMAP_aggregate;
1812}
1813
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001814bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1815 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001816 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1817
Alexey Bataeve3727102018-04-18 15:57:46 +00001818 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001819 bool IsByRef = true;
1820
1821 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001822 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001823 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001824
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001825 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001826 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001827 // This table summarizes how a given variable should be passed to the device
1828 // given its type and the clauses where it appears. This table is based on
1829 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1830 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1831 //
1832 // =========================================================================
1833 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1834 // | |(tofrom:scalar)| | pvt | | | |
1835 // =========================================================================
1836 // | scl | | | | - | | bycopy|
1837 // | scl | | - | x | - | - | bycopy|
1838 // | scl | | x | - | - | - | null |
1839 // | scl | x | | | - | | byref |
1840 // | scl | x | - | x | - | - | bycopy|
1841 // | scl | x | x | - | - | - | null |
1842 // | scl | | - | - | - | x | byref |
1843 // | scl | x | - | - | - | x | byref |
1844 //
1845 // | agg | n.a. | | | - | | byref |
1846 // | agg | n.a. | - | x | - | - | byref |
1847 // | agg | n.a. | x | - | - | - | null |
1848 // | agg | n.a. | - | - | - | x | byref |
1849 // | agg | n.a. | - | - | - | x[] | byref |
1850 //
1851 // | ptr | n.a. | | | - | | bycopy|
1852 // | ptr | n.a. | - | x | - | - | bycopy|
1853 // | ptr | n.a. | x | - | - | - | null |
1854 // | ptr | n.a. | - | - | - | x | byref |
1855 // | ptr | n.a. | - | - | - | x[] | bycopy|
1856 // | ptr | n.a. | - | - | x | | bycopy|
1857 // | ptr | n.a. | - | - | x | x | bycopy|
1858 // | ptr | n.a. | - | - | x | x[] | bycopy|
1859 // =========================================================================
1860 // Legend:
1861 // scl - scalar
1862 // ptr - pointer
1863 // agg - aggregate
1864 // x - applies
1865 // - - invalid in this combination
1866 // [] - mapped with an array section
1867 // byref - should be mapped by reference
1868 // byval - should be mapped by value
1869 // null - initialize a local variable to null on the device
1870 //
1871 // Observations:
1872 // - All scalar declarations that show up in a map clause have to be passed
1873 // by reference, because they may have been mapped in the enclosing data
1874 // environment.
1875 // - If the scalar value does not fit the size of uintptr, it has to be
1876 // passed by reference, regardless the result in the table above.
1877 // - For pointers mapped by value that have either an implicit map or an
1878 // array section, the runtime library may pass the NULL value to the
1879 // device instead of the value passed to it by the compiler.
1880
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001881 if (Ty->isReferenceType())
1882 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001883
1884 // Locate map clauses and see if the variable being captured is referred to
1885 // in any of those clauses. Here we only care about variables, not fields,
1886 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001887 bool IsVariableAssociatedWithSection = false;
1888
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001889 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001890 D, Level,
1891 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1892 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001893 MapExprComponents,
1894 OpenMPClauseKind WhereFoundClauseKind) {
1895 // Only the map clause information influences how a variable is
1896 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001897 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001898 if (WhereFoundClauseKind != OMPC_map)
1899 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001900
1901 auto EI = MapExprComponents.rbegin();
1902 auto EE = MapExprComponents.rend();
1903
1904 assert(EI != EE && "Invalid map expression!");
1905
1906 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1907 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1908
1909 ++EI;
1910 if (EI == EE)
1911 return false;
1912
1913 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1914 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1915 isa<MemberExpr>(EI->getAssociatedExpression())) {
1916 IsVariableAssociatedWithSection = true;
1917 // There is nothing more we need to know about this variable.
1918 return true;
1919 }
1920
1921 // Keep looking for more map info.
1922 return false;
1923 });
1924
1925 if (IsVariableUsedInMapClause) {
1926 // If variable is identified in a map clause it is always captured by
1927 // reference except if it is a pointer that is dereferenced somehow.
1928 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1929 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001930 // By default, all the data that has a scalar type is mapped by copy
1931 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001932 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001933 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001934 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1935 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001936 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001937 DSAStack->isDefaultmapCapturedByRef(
1938 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001939 DSAStack->hasExplicitDSA(
1940 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001941 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001942 }
1943
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001944 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001945 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001946 ((IsVariableUsedInMapClause &&
1947 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1948 OMPD_target) ||
1949 !DSAStack->hasExplicitDSA(
1950 D,
1951 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1952 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001953 // If the variable is artificial and must be captured by value - try to
1954 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001955 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1956 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001957 }
1958
Samuel Antao86ace552016-04-27 22:40:57 +00001959 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001960 // and alignment, because the runtime library only deals with uintptr types.
1961 // If it does not fit the uintptr size, we need to pass the data by reference
1962 // instead.
1963 if (!IsByRef &&
1964 (Ctx.getTypeSizeInChars(Ty) >
1965 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001966 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001967 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001968 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001969
1970 return IsByRef;
1971}
1972
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001973unsigned Sema::getOpenMPNestingLevel() const {
1974 assert(getLangOpts().OpenMP);
1975 return DSAStack->getNestingLevel();
1976}
1977
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001978bool Sema::isInOpenMPTargetExecutionDirective() const {
1979 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1980 !DSAStack->isClauseParsingMode()) ||
1981 DSAStack->hasDirective(
1982 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1983 SourceLocation) -> bool {
1984 return isOpenMPTargetExecutionDirective(K);
1985 },
1986 false);
1987}
1988
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001989VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1990 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001991 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001992 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001993
Alexey Bataev7c860692019-10-25 16:35:32 -04001994 auto *VD = dyn_cast<VarDecl>(D);
1995 // Do not capture constexpr variables.
1996 if (VD && VD->isConstexpr())
1997 return nullptr;
1998
Richard Smith0621a8f2019-05-31 00:45:10 +00001999 // If we want to determine whether the variable should be captured from the
2000 // perspective of the current capturing scope, and we've already left all the
2001 // capturing scopes of the top directive on the stack, check from the
2002 // perspective of its parent directive (if any) instead.
2003 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2004 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2005
Samuel Antao4be30e92015-10-02 17:14:03 +00002006 // If we are attempting to capture a global variable in a directive with
2007 // 'target' we return true so that this global is also mapped to the device.
2008 //
Richard Smith0621a8f2019-05-31 00:45:10 +00002009 if (VD && !VD->hasLocalStorage() &&
2010 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2011 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002012 // Try to mark variable as declare target if it is used in capturing
2013 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00002014 if (LangOpts.OpenMP <= 45 &&
2015 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002016 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002017 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002018 } else if (isInOpenMPTargetExecutionDirective()) {
2019 // If the declaration is enclosed in a 'declare target' directive,
2020 // then it should not be captured.
2021 //
Alexey Bataev97b72212018-08-14 18:31:20 +00002022 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002023 return nullptr;
Alexey Bataev36635632020-01-17 20:39:04 -05002024 CapturedRegionScopeInfo *CSI = nullptr;
2025 for (FunctionScopeInfo *FSI : llvm::drop_begin(
2026 llvm::reverse(FunctionScopes),
2027 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2028 if (!isa<CapturingScopeInfo>(FSI))
2029 return nullptr;
2030 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2031 if (RSI->CapRegionKind == CR_OpenMP) {
2032 CSI = RSI;
2033 break;
2034 }
2035 }
2036 SmallVector<OpenMPDirectiveKind, 4> Regions;
2037 getOpenMPCaptureRegions(Regions,
2038 DSAStack->getDirective(CSI->OpenMPLevel));
2039 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2040 return VD;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002041 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002042 }
Samuel Antao4be30e92015-10-02 17:14:03 +00002043
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002044 if (CheckScopeInfo) {
2045 bool OpenMPFound = false;
2046 for (unsigned I = StopAt + 1; I > 0; --I) {
2047 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2048 if(!isa<CapturingScopeInfo>(FSI))
2049 return nullptr;
2050 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2051 if (RSI->CapRegionKind == CR_OpenMP) {
2052 OpenMPFound = true;
2053 break;
2054 }
2055 }
2056 if (!OpenMPFound)
2057 return nullptr;
2058 }
2059
Alexey Bataev48977c32015-08-04 08:10:48 +00002060 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2061 (!DSAStack->isClauseParsingMode() ||
2062 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002063 auto &&Info = DSAStack->isLoopControlVariable(D);
2064 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002065 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002066 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002067 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002068 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002069 DSAStackTy::DSAVarData DVarPrivate =
2070 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002071 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002072 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002073 // Threadprivate variables must not be captured.
2074 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2075 return nullptr;
2076 // The variable is not private or it is the variable in the directive with
2077 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002078 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2079 [](OpenMPDirectiveKind) { return true; },
2080 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002081 if (DVarPrivate.CKind != OMPC_unknown ||
2082 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002083 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002084 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002085 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002086}
2087
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002088void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2089 unsigned Level) const {
2090 SmallVector<OpenMPDirectiveKind, 4> Regions;
2091 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2092 FunctionScopesIndex -= Regions.size();
2093}
2094
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002095void Sema::startOpenMPLoop() {
2096 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2097 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2098 DSAStack->loopInit();
2099}
2100
Alexey Bataevbef93a92019-10-07 18:54:57 +00002101void Sema::startOpenMPCXXRangeFor() {
2102 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2103 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2104 DSAStack->resetPossibleLoopCounter();
2105 DSAStack->loopStart();
2106 }
2107}
2108
Alexey Bataeve3727102018-04-18 15:57:46 +00002109bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002110 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002111 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2112 if (DSAStack->getAssociatedLoops() > 0 &&
2113 !DSAStack->isLoopStarted()) {
2114 DSAStack->resetPossibleLoopCounter(D);
2115 DSAStack->loopStart();
2116 return true;
2117 }
2118 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2119 DSAStack->isLoopControlVariable(D).first) &&
2120 !DSAStack->hasExplicitDSA(
2121 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2122 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2123 return true;
2124 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002125 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2126 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2127 DSAStack->isForceVarCapturing() &&
2128 !DSAStack->hasExplicitDSA(
2129 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2130 return true;
2131 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002132 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002133 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002134 (DSAStack->isClauseParsingMode() &&
2135 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002136 // Consider taskgroup reduction descriptor variable a private to avoid
2137 // possible capture in the region.
2138 (DSAStack->hasExplicitDirective(
2139 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2140 Level) &&
2141 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002142}
2143
Alexey Bataeve3727102018-04-18 15:57:46 +00002144void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2145 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002146 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2147 D = getCanonicalDecl(D);
2148 OpenMPClauseKind OMPC = OMPC_unknown;
2149 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2150 const unsigned NewLevel = I - 1;
2151 if (DSAStack->hasExplicitDSA(D,
2152 [&OMPC](const OpenMPClauseKind K) {
2153 if (isOpenMPPrivate(K)) {
2154 OMPC = K;
2155 return true;
2156 }
2157 return false;
2158 },
2159 NewLevel))
2160 break;
2161 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2162 D, NewLevel,
2163 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2164 OpenMPClauseKind) { return true; })) {
2165 OMPC = OMPC_map;
2166 break;
2167 }
2168 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2169 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002170 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002171 if (DSAStack->mustBeFirstprivateAtLevel(
2172 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002173 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002174 break;
2175 }
2176 }
2177 if (OMPC != OMPC_unknown)
2178 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2179}
2180
Alexey Bataev36635632020-01-17 20:39:04 -05002181bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2182 unsigned CaptureLevel) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002183 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2184 // Return true if the current level is no longer enclosed in a target region.
2185
Alexey Bataev36635632020-01-17 20:39:04 -05002186 SmallVector<OpenMPDirectiveKind, 4> Regions;
2187 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
Alexey Bataeve3727102018-04-18 15:57:46 +00002188 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002189 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002190 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
Alexey Bataev36635632020-01-17 20:39:04 -05002191 Level) &&
2192 Regions[CaptureLevel] != OMPD_task;
Samuel Antao4be30e92015-10-02 17:14:03 +00002193}
2194
Alexey Bataeved09d242014-05-28 05:53:51 +00002195void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002196
Alexey Bataev729e2422019-08-23 16:11:14 +00002197void Sema::finalizeOpenMPDelayedAnalysis() {
2198 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2199 // Diagnose implicit declare target functions and their callees.
2200 for (const auto &CallerCallees : DeviceCallGraph) {
2201 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2202 OMPDeclareTargetDeclAttr::getDeviceType(
2203 CallerCallees.getFirst()->getMostRecentDecl());
2204 // Ignore host functions during device analyzis.
2205 if (LangOpts.OpenMPIsDevice && DevTy &&
2206 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2207 continue;
2208 // Ignore nohost functions during host analyzis.
2209 if (!LangOpts.OpenMPIsDevice && DevTy &&
2210 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2211 continue;
2212 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2213 &Callee : CallerCallees.getSecond()) {
2214 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2215 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2216 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2217 if (LangOpts.OpenMPIsDevice && DevTy &&
2218 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2219 // Diagnose host function called during device codegen.
2220 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2221 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2222 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2223 << HostDevTy << 0;
2224 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2225 diag::note_omp_marked_device_type_here)
2226 << HostDevTy;
2227 continue;
2228 }
2229 if (!LangOpts.OpenMPIsDevice && DevTy &&
2230 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2231 // Diagnose nohost function called during host codegen.
2232 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2233 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2234 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2235 << NoHostDevTy << 1;
2236 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2237 diag::note_omp_marked_device_type_here)
2238 << NoHostDevTy;
2239 continue;
2240 }
2241 }
2242 }
2243}
2244
Alexey Bataev758e55e2013-09-06 18:03:48 +00002245void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2246 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002247 Scope *CurScope, SourceLocation Loc) {
2248 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002249 PushExpressionEvaluationContext(
2250 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002251}
2252
Alexey Bataevaac108a2015-06-23 04:51:00 +00002253void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2254 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002255}
2256
Alexey Bataevaac108a2015-06-23 04:51:00 +00002257void Sema::EndOpenMPClause() {
2258 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002259}
2260
Alexey Bataeve106f252019-04-01 14:25:31 +00002261static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2262 ArrayRef<OMPClause *> Clauses);
Alexey Bataev0860db92019-12-19 10:01:10 -05002263static std::pair<ValueDecl *, bool>
2264getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2265 SourceRange &ERange, bool AllowArraySection = false);
2266static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2267 bool WithInit);
Alexey Bataeve106f252019-04-01 14:25:31 +00002268
Alexey Bataev758e55e2013-09-06 18:03:48 +00002269void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002270 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2271 // A variable of class type (or array thereof) that appears in a lastprivate
2272 // clause requires an accessible, unambiguous default constructor for the
2273 // class type, unless the list item is also specified in a firstprivate
2274 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002275 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2276 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002277 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2278 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002279 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002280 if (DE->isValueDependent() || DE->isTypeDependent()) {
2281 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002282 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002283 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002284 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002285 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002286 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002287 const DSAStackTy::DSAVarData DVar =
2288 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002289 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002290 // Generate helper private variable and initialize it with the
2291 // default value. The address of the original variable is replaced
2292 // by the address of the new private variable in CodeGen. This new
2293 // variable is not added to IdResolver, so the code in the OpenMP
2294 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002295 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002296 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002297 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002298 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002299 if (VDPrivate->isInvalidDecl()) {
2300 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002301 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002302 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002303 PrivateCopies.push_back(buildDeclRefExpr(
2304 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002305 } else {
2306 // The variable is also a firstprivate, so initialization sequence
2307 // for private copy is generated already.
2308 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002309 }
2310 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002311 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataev0860db92019-12-19 10:01:10 -05002312 continue;
2313 }
2314 // Finalize nontemporal clause by handling private copies, if any.
2315 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2316 SmallVector<Expr *, 8> PrivateRefs;
2317 for (Expr *RefExpr : Clause->varlists()) {
2318 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2319 SourceLocation ELoc;
2320 SourceRange ERange;
2321 Expr *SimpleRefExpr = RefExpr;
2322 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2323 if (Res.second)
2324 // It will be analyzed later.
2325 PrivateRefs.push_back(RefExpr);
2326 ValueDecl *D = Res.first;
2327 if (!D)
2328 continue;
2329
2330 const DSAStackTy::DSAVarData DVar =
2331 DSAStack->getTopDSA(D, /*FromParent=*/false);
2332 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2333 : SimpleRefExpr);
2334 }
2335 Clause->setPrivateRefs(PrivateRefs);
2336 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002337 }
2338 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002339 // Check allocate clauses.
2340 if (!CurContext->isDependentContext())
2341 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002342 }
2343
Alexey Bataev758e55e2013-09-06 18:03:48 +00002344 DSAStack->pop();
2345 DiscardCleanupsInEvaluationContext();
2346 PopExpressionEvaluationContext();
2347}
2348
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002349static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2350 Expr *NumIterations, Sema &SemaRef,
2351 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002352
Alexey Bataeva769e072013-03-22 06:34:35 +00002353namespace {
2354
Alexey Bataeve3727102018-04-18 15:57:46 +00002355class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002356private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002357 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002358
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002359public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002360 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002361 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002362 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002363 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002364 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002365 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2366 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002367 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002368 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002369 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002370
2371 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002372 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002373 }
2374
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002375};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002376
Alexey Bataeve3727102018-04-18 15:57:46 +00002377class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002378private:
2379 Sema &SemaRef;
2380
2381public:
2382 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2383 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2384 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002385 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2386 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002387 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2388 SemaRef.getCurScope());
2389 }
2390 return false;
2391 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002392
2393 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002394 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002395 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002396};
2397
Alexey Bataeved09d242014-05-28 05:53:51 +00002398} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002399
2400ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2401 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002402 const DeclarationNameInfo &Id,
2403 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002404 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2405 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2406
2407 if (Lookup.isAmbiguous())
2408 return ExprError();
2409
2410 VarDecl *VD;
2411 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002412 VarDeclFilterCCC CCC(*this);
2413 if (TypoCorrection Corrected =
2414 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2415 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002416 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002417 PDiag(Lookup.empty()
2418 ? diag::err_undeclared_var_use_suggest
2419 : diag::err_omp_expected_var_arg_suggest)
2420 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002421 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002422 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002423 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2424 : diag::err_omp_expected_var_arg)
2425 << Id.getName();
2426 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002427 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002428 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2429 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2430 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2431 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002432 }
2433 Lookup.suppressDiagnostics();
2434
2435 // OpenMP [2.9.2, Syntax, C/C++]
2436 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002437 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002438 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002439 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002440 bool IsDecl =
2441 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002442 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002443 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2444 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002445 return ExprError();
2446 }
2447
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002448 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002449 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002450 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2451 // A threadprivate directive for file-scope variables must appear outside
2452 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002453 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2454 !getCurLexicalContext()->isTranslationUnit()) {
2455 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002456 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002457 bool IsDecl =
2458 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2459 Diag(VD->getLocation(),
2460 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2461 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002462 return ExprError();
2463 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002464 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2465 // A threadprivate directive for static class member variables must appear
2466 // in the class definition, in the same scope in which the member
2467 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002468 if (CanonicalVD->isStaticDataMember() &&
2469 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2470 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002471 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002472 bool IsDecl =
2473 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2474 Diag(VD->getLocation(),
2475 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2476 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002477 return ExprError();
2478 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002479 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2480 // A threadprivate directive for namespace-scope variables must appear
2481 // outside any definition or declaration other than the namespace
2482 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002483 if (CanonicalVD->getDeclContext()->isNamespace() &&
2484 (!getCurLexicalContext()->isFileContext() ||
2485 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2486 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002487 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002488 bool IsDecl =
2489 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2490 Diag(VD->getLocation(),
2491 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2492 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002493 return ExprError();
2494 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002495 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2496 // A threadprivate directive for static block-scope variables must appear
2497 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002498 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002499 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002500 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002501 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002502 bool IsDecl =
2503 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2504 Diag(VD->getLocation(),
2505 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2506 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002507 return ExprError();
2508 }
2509
2510 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2511 // A threadprivate directive must lexically precede all references to any
2512 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002513 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2514 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002515 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002516 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002517 return ExprError();
2518 }
2519
2520 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002521 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2522 SourceLocation(), VD,
2523 /*RefersToEnclosingVariableOrCapture=*/false,
2524 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002525}
2526
Alexey Bataeved09d242014-05-28 05:53:51 +00002527Sema::DeclGroupPtrTy
2528Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2529 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002530 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002531 CurContext->addDecl(D);
2532 return DeclGroupPtrTy::make(DeclGroupRef(D));
2533 }
David Blaikie0403cb12016-01-15 23:43:25 +00002534 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002535}
2536
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002537namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002538class LocalVarRefChecker final
2539 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002540 Sema &SemaRef;
2541
2542public:
2543 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002544 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002545 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002546 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002547 diag::err_omp_local_var_in_threadprivate_init)
2548 << E->getSourceRange();
2549 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2550 << VD << VD->getSourceRange();
2551 return true;
2552 }
2553 }
2554 return false;
2555 }
2556 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002557 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002558 if (Child && Visit(Child))
2559 return true;
2560 }
2561 return false;
2562 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002563 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002564};
2565} // namespace
2566
Alexey Bataeved09d242014-05-28 05:53:51 +00002567OMPThreadPrivateDecl *
2568Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002569 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002570 for (Expr *RefExpr : VarList) {
2571 auto *DE = cast<DeclRefExpr>(RefExpr);
2572 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002573 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002574
Alexey Bataev376b4a42016-02-09 09:41:09 +00002575 // Mark variable as used.
2576 VD->setReferenced();
2577 VD->markUsed(Context);
2578
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002579 QualType QType = VD->getType();
2580 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2581 // It will be analyzed later.
2582 Vars.push_back(DE);
2583 continue;
2584 }
2585
Alexey Bataeva769e072013-03-22 06:34:35 +00002586 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2587 // A threadprivate variable must not have an incomplete type.
2588 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002589 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002590 continue;
2591 }
2592
2593 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2594 // A threadprivate variable must not have a reference type.
2595 if (VD->getType()->isReferenceType()) {
2596 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002597 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2598 bool IsDecl =
2599 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2600 Diag(VD->getLocation(),
2601 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2602 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002603 continue;
2604 }
2605
Samuel Antaof8b50122015-07-13 22:54:53 +00002606 // Check if this is a TLS variable. If TLS is not being supported, produce
2607 // the corresponding diagnostic.
2608 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2609 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2610 getLangOpts().OpenMPUseTLS &&
2611 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002612 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2613 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002614 Diag(ILoc, diag::err_omp_var_thread_local)
2615 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002616 bool IsDecl =
2617 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2618 Diag(VD->getLocation(),
2619 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2620 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002621 continue;
2622 }
2623
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002624 // Check if initial value of threadprivate variable reference variable with
2625 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002626 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002627 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002628 if (Checker.Visit(Init))
2629 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002630 }
2631
Alexey Bataeved09d242014-05-28 05:53:51 +00002632 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002633 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002634 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2635 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002636 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002637 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002638 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002639 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002640 if (!Vars.empty()) {
2641 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2642 Vars);
2643 D->setAccess(AS_public);
2644 }
2645 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002646}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002647
Alexey Bataev27ef9512019-03-20 20:14:22 +00002648static OMPAllocateDeclAttr::AllocatorTypeTy
2649getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2650 if (!Allocator)
2651 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2652 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2653 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002654 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002655 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002656 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002657 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002658 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2659 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2660 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002661 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002662 llvm::FoldingSetNodeID AEId, DAEId;
2663 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2664 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2665 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002666 AllocatorKindRes = AllocatorKind;
2667 break;
2668 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002669 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002670 return AllocatorKindRes;
2671}
2672
Alexey Bataeve106f252019-04-01 14:25:31 +00002673static bool checkPreviousOMPAllocateAttribute(
2674 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2675 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2676 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2677 return false;
2678 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2679 Expr *PrevAllocator = A->getAllocator();
2680 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2681 getAllocatorKind(S, Stack, PrevAllocator);
2682 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2683 if (AllocatorsMatch &&
2684 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2685 Allocator && PrevAllocator) {
2686 const Expr *AE = Allocator->IgnoreParenImpCasts();
2687 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2688 llvm::FoldingSetNodeID AEId, PAEId;
2689 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2690 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2691 AllocatorsMatch = AEId == PAEId;
2692 }
2693 if (!AllocatorsMatch) {
2694 SmallString<256> AllocatorBuffer;
2695 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2696 if (Allocator)
2697 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2698 SmallString<256> PrevAllocatorBuffer;
2699 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2700 if (PrevAllocator)
2701 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2702 S.getPrintingPolicy());
2703
2704 SourceLocation AllocatorLoc =
2705 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2706 SourceRange AllocatorRange =
2707 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2708 SourceLocation PrevAllocatorLoc =
2709 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2710 SourceRange PrevAllocatorRange =
2711 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2712 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2713 << (Allocator ? 1 : 0) << AllocatorStream.str()
2714 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2715 << AllocatorRange;
2716 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2717 << PrevAllocatorRange;
2718 return true;
2719 }
2720 return false;
2721}
2722
2723static void
2724applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2725 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2726 Expr *Allocator, SourceRange SR) {
2727 if (VD->hasAttr<OMPAllocateDeclAttr>())
2728 return;
2729 if (Allocator &&
2730 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2731 Allocator->isInstantiationDependent() ||
2732 Allocator->containsUnexpandedParameterPack()))
2733 return;
2734 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2735 Allocator, SR);
2736 VD->addAttr(A);
2737 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2738 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2739}
2740
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002741Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2742 SourceLocation Loc, ArrayRef<Expr *> VarList,
2743 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2744 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2745 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002746 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002747 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2748 // allocate directives that appear in a target region must specify an
2749 // allocator clause unless a requires directive with the dynamic_allocators
2750 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002751 if (LangOpts.OpenMPIsDevice &&
2752 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002753 targetDiag(Loc, diag::err_expected_allocator_clause);
2754 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002755 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002756 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002757 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2758 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002759 SmallVector<Expr *, 8> Vars;
2760 for (Expr *RefExpr : VarList) {
2761 auto *DE = cast<DeclRefExpr>(RefExpr);
2762 auto *VD = cast<VarDecl>(DE->getDecl());
2763
2764 // Check if this is a TLS variable or global register.
2765 if (VD->getTLSKind() != VarDecl::TLS_None ||
2766 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2767 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2768 !VD->isLocalVarDecl()))
2769 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002770
Alexey Bataev282555a2019-03-19 20:33:44 +00002771 // If the used several times in the allocate directive, the same allocator
2772 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002773 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2774 AllocatorKind, Allocator))
2775 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002776
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002777 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2778 // If a list item has a static storage type, the allocator expression in the
2779 // allocator clause must be a constant expression that evaluates to one of
2780 // the predefined memory allocator values.
2781 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002782 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002783 Diag(Allocator->getExprLoc(),
2784 diag::err_omp_expected_predefined_allocator)
2785 << Allocator->getSourceRange();
2786 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2787 VarDecl::DeclarationOnly;
2788 Diag(VD->getLocation(),
2789 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2790 << VD;
2791 continue;
2792 }
2793 }
2794
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002795 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002796 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2797 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002798 }
2799 if (Vars.empty())
2800 return nullptr;
2801 if (!Owner)
2802 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002803 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002804 D->setAccess(AS_public);
2805 Owner->addDecl(D);
2806 return DeclGroupPtrTy::make(DeclGroupRef(D));
2807}
2808
2809Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002810Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2811 ArrayRef<OMPClause *> ClauseList) {
2812 OMPRequiresDecl *D = nullptr;
2813 if (!CurContext->isFileContext()) {
2814 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2815 } else {
2816 D = CheckOMPRequiresDecl(Loc, ClauseList);
2817 if (D) {
2818 CurContext->addDecl(D);
2819 DSAStack->addRequiresDecl(D);
2820 }
2821 }
2822 return DeclGroupPtrTy::make(DeclGroupRef(D));
2823}
2824
2825OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2826 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002827 /// For target specific clauses, the requires directive cannot be
2828 /// specified after the handling of any of the target regions in the
2829 /// current compilation unit.
2830 ArrayRef<SourceLocation> TargetLocations =
2831 DSAStack->getEncounteredTargetLocs();
2832 if (!TargetLocations.empty()) {
2833 for (const OMPClause *CNew : ClauseList) {
2834 // Check if any of the requires clauses affect target regions.
2835 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2836 isa<OMPUnifiedAddressClause>(CNew) ||
2837 isa<OMPReverseOffloadClause>(CNew) ||
2838 isa<OMPDynamicAllocatorsClause>(CNew)) {
2839 Diag(Loc, diag::err_omp_target_before_requires)
2840 << getOpenMPClauseName(CNew->getClauseKind());
2841 for (SourceLocation TargetLoc : TargetLocations) {
2842 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2843 }
2844 }
2845 }
2846 }
2847
Kelvin Li1408f912018-09-26 04:28:39 +00002848 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2849 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2850 ClauseList);
2851 return nullptr;
2852}
2853
Alexey Bataeve3727102018-04-18 15:57:46 +00002854static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2855 const ValueDecl *D,
2856 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002857 bool IsLoopIterVar = false) {
2858 if (DVar.RefExpr) {
2859 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2860 << getOpenMPClauseName(DVar.CKind);
2861 return;
2862 }
2863 enum {
2864 PDSA_StaticMemberShared,
2865 PDSA_StaticLocalVarShared,
2866 PDSA_LoopIterVarPrivate,
2867 PDSA_LoopIterVarLinear,
2868 PDSA_LoopIterVarLastprivate,
2869 PDSA_ConstVarShared,
2870 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002871 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002872 PDSA_LocalVarPrivate,
2873 PDSA_Implicit
2874 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002875 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002876 auto ReportLoc = D->getLocation();
2877 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002878 if (IsLoopIterVar) {
2879 if (DVar.CKind == OMPC_private)
2880 Reason = PDSA_LoopIterVarPrivate;
2881 else if (DVar.CKind == OMPC_lastprivate)
2882 Reason = PDSA_LoopIterVarLastprivate;
2883 else
2884 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002885 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2886 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002887 Reason = PDSA_TaskVarFirstprivate;
2888 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002889 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002890 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002891 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002892 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002893 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002894 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002895 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002896 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002897 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002898 ReportHint = true;
2899 Reason = PDSA_LocalVarPrivate;
2900 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002901 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002902 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002903 << Reason << ReportHint
2904 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2905 } else if (DVar.ImplicitDSALoc.isValid()) {
2906 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2907 << getOpenMPClauseName(DVar.CKind);
2908 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002909}
2910
cchene06f3e02019-11-15 13:02:06 -05002911static OpenMPMapClauseKind
2912getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2913 bool IsAggregateOrDeclareTarget) {
2914 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2915 switch (M) {
2916 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2917 Kind = OMPC_MAP_alloc;
2918 break;
2919 case OMPC_DEFAULTMAP_MODIFIER_to:
2920 Kind = OMPC_MAP_to;
2921 break;
2922 case OMPC_DEFAULTMAP_MODIFIER_from:
2923 Kind = OMPC_MAP_from;
2924 break;
2925 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2926 Kind = OMPC_MAP_tofrom;
2927 break;
2928 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2929 case OMPC_DEFAULTMAP_MODIFIER_last:
2930 llvm_unreachable("Unexpected defaultmap implicit behavior");
2931 case OMPC_DEFAULTMAP_MODIFIER_none:
2932 case OMPC_DEFAULTMAP_MODIFIER_default:
2933 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2934 // IsAggregateOrDeclareTarget could be true if:
2935 // 1. the implicit behavior for aggregate is tofrom
2936 // 2. it's a declare target link
2937 if (IsAggregateOrDeclareTarget) {
2938 Kind = OMPC_MAP_tofrom;
2939 break;
2940 }
2941 llvm_unreachable("Unexpected defaultmap implicit behavior");
2942 }
2943 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2944 return Kind;
2945}
2946
Alexey Bataev758e55e2013-09-06 18:03:48 +00002947namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002948class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002949 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002950 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002951 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002952 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002953 CapturedStmt *CS = nullptr;
2954 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002955 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002956 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2957 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002958
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002959 void VisitSubCaptures(OMPExecutableDirective *S) {
2960 // Check implicitly captured variables.
2961 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2962 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002963 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002964 // Try to capture inner this->member references to generate correct mappings
2965 // and diagnostics.
2966 if (TryCaptureCXXThisMembers ||
2967 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2968 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2969 [](const CapturedStmt::Capture &C) {
2970 return C.capturesThis();
2971 }))) {
2972 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2973 TryCaptureCXXThisMembers = true;
2974 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2975 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2976 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002977 }
2978
Alexey Bataev758e55e2013-09-06 18:03:48 +00002979public:
2980 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002981 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2982 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2983 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002984 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002985 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002986 // Check the datasharing rules for the expressions in the clauses.
2987 if (!CS) {
2988 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2989 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2990 Visit(CED->getInit());
2991 return;
2992 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002993 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2994 // Do not analyze internal variables and do not enclose them into
2995 // implicit clauses.
2996 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002997 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002998 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002999 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00003000 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003001
Alexey Bataeve3727102018-04-18 15:57:46 +00003002 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003003 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003004 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00003005 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003006
Alexey Bataevafe50572017-10-06 17:00:28 +00003007 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00003008 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00003009 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00003010 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00003011 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3012 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00003013 return;
3014
Alexey Bataeve3727102018-04-18 15:57:46 +00003015 SourceLocation ELoc = E->getExprLoc();
3016 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003017 // The default(none) clause requires that each variable that is referenced
3018 // in the construct, and does not have a predetermined data-sharing
3019 // attribute, must have its data-sharing attribute explicitly determined
3020 // by being listed in a data-sharing attribute clause.
3021 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00003022 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00003023 VarsWithInheritedDSA.count(VD) == 0) {
3024 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003025 return;
3026 }
3027
cchene06f3e02019-11-15 13:02:06 -05003028 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3029 // If implicit-behavior is none, each variable referenced in the
3030 // construct that does not have a predetermined data-sharing attribute
3031 // and does not appear in a to or link clause on a declare target
3032 // directive must be listed in a data-mapping attribute clause, a
3033 // data-haring attribute clause (including a data-sharing attribute
3034 // clause on a combined construct where target. is one of the
3035 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05003036 OpenMPDefaultmapClauseKind ClauseKind =
3037 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05003038 if (SemaRef.getLangOpts().OpenMP >= 50) {
3039 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3040 OMPC_DEFAULTMAP_MODIFIER_none;
3041 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3042 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3043 // Only check for data-mapping attribute and is_device_ptr here
3044 // since we have already make sure that the declaration does not
3045 // have a data-sharing attribute above
3046 if (!Stack->checkMappableExprComponentListsForDecl(
3047 VD, /*CurrentRegionOnly=*/true,
3048 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3049 MapExprComponents,
3050 OpenMPClauseKind) {
3051 auto MI = MapExprComponents.rbegin();
3052 auto ME = MapExprComponents.rend();
3053 return MI != ME && MI->getAssociatedDeclaration() == VD;
3054 })) {
3055 VarsWithInheritedDSA[VD] = E;
3056 return;
3057 }
3058 }
3059 }
3060
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003061 if (isOpenMPTargetExecutionDirective(DKind) &&
3062 !Stack->isLoopControlVariable(VD).first) {
3063 if (!Stack->checkMappableExprComponentListsForDecl(
3064 VD, /*CurrentRegionOnly=*/true,
3065 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3066 StackComponents,
3067 OpenMPClauseKind) {
3068 // Variable is used if it has been marked as an array, array
3069 // section or the variable iself.
3070 return StackComponents.size() == 1 ||
3071 std::all_of(
3072 std::next(StackComponents.rbegin()),
3073 StackComponents.rend(),
3074 [](const OMPClauseMappableExprCommon::
3075 MappableComponent &MC) {
3076 return MC.getAssociatedDeclaration() ==
3077 nullptr &&
3078 (isa<OMPArraySectionExpr>(
3079 MC.getAssociatedExpression()) ||
3080 isa<ArraySubscriptExpr>(
3081 MC.getAssociatedExpression()));
3082 });
3083 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003084 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003085 // By default lambdas are captured as firstprivates.
3086 if (const auto *RD =
3087 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003088 IsFirstprivate = RD->isLambda();
3089 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003090 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3091 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003092 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003093 } else {
3094 OpenMPDefaultmapClauseModifier M =
3095 Stack->getDefaultmapModifier(ClauseKind);
3096 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3097 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3098 ImplicitMap[Kind].emplace_back(E);
3099 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003100 return;
3101 }
3102 }
3103
Alexey Bataev758e55e2013-09-06 18:03:48 +00003104 // OpenMP [2.9.3.6, Restrictions, p.2]
3105 // A list item that appears in a reduction clause of the innermost
3106 // enclosing worksharing or parallel construct may not be accessed in an
3107 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003108 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003109 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3110 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003111 return isOpenMPParallelDirective(K) ||
3112 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3113 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003114 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003115 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003116 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003117 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003118 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003119 return;
3120 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003121
3122 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003123 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003124 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003125 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003126 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003127 return;
3128 }
3129
3130 // Store implicitly used globals with declare target link for parent
3131 // target.
3132 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3133 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3134 Stack->addToParentTargetRegionLinkGlobals(E);
3135 return;
3136 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003137 }
3138 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003139 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003140 if (E->isTypeDependent() || E->isValueDependent() ||
3141 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3142 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003143 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003144 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003145 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003146 if (!FD)
3147 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003148 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003149 // Check if the variable has explicit DSA set and stop analysis if it
3150 // so.
3151 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3152 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003153
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003154 if (isOpenMPTargetExecutionDirective(DKind) &&
3155 !Stack->isLoopControlVariable(FD).first &&
3156 !Stack->checkMappableExprComponentListsForDecl(
3157 FD, /*CurrentRegionOnly=*/true,
3158 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3159 StackComponents,
3160 OpenMPClauseKind) {
3161 return isa<CXXThisExpr>(
3162 cast<MemberExpr>(
3163 StackComponents.back().getAssociatedExpression())
3164 ->getBase()
3165 ->IgnoreParens());
3166 })) {
3167 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3168 // A bit-field cannot appear in a map clause.
3169 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003170 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003171 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003172
3173 // Check to see if the member expression is referencing a class that
3174 // has already been explicitly mapped
3175 if (Stack->isClassPreviouslyMapped(TE->getType()))
3176 return;
3177
cchene06f3e02019-11-15 13:02:06 -05003178 OpenMPDefaultmapClauseModifier Modifier =
3179 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3180 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3181 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3182 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003183 return;
3184 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003185
Alexey Bataeve3727102018-04-18 15:57:46 +00003186 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003187 // OpenMP [2.9.3.6, Restrictions, p.2]
3188 // A list item that appears in a reduction clause of the innermost
3189 // enclosing worksharing or parallel construct may not be accessed in
3190 // an explicit task.
3191 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003192 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3193 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003194 return isOpenMPParallelDirective(K) ||
3195 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3196 },
3197 /*FromParent=*/true);
3198 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3199 ErrorFound = true;
3200 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003201 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003202 return;
3203 }
3204
3205 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003206 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003207 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003208 !Stack->isLoopControlVariable(FD).first) {
3209 // Check if there is a captured expression for the current field in the
3210 // region. Do not mark it as firstprivate unless there is no captured
3211 // expression.
3212 // TODO: try to make it firstprivate.
3213 if (DVar.CKind != OMPC_unknown)
3214 ImplicitFirstprivate.push_back(E);
3215 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003216 return;
3217 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003218 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003219 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003220 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003221 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003222 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003223 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003224 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3225 if (!Stack->checkMappableExprComponentListsForDecl(
3226 VD, /*CurrentRegionOnly=*/true,
3227 [&CurComponents](
3228 OMPClauseMappableExprCommon::MappableExprComponentListRef
3229 StackComponents,
3230 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003231 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003232 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003233 for (const auto &SC : llvm::reverse(StackComponents)) {
3234 // Do both expressions have the same kind?
3235 if (CCI->getAssociatedExpression()->getStmtClass() !=
3236 SC.getAssociatedExpression()->getStmtClass())
3237 if (!(isa<OMPArraySectionExpr>(
3238 SC.getAssociatedExpression()) &&
3239 isa<ArraySubscriptExpr>(
3240 CCI->getAssociatedExpression())))
3241 return false;
3242
Alexey Bataeve3727102018-04-18 15:57:46 +00003243 const Decl *CCD = CCI->getAssociatedDeclaration();
3244 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003245 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3246 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3247 if (SCD != CCD)
3248 return false;
3249 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003250 if (CCI == CCE)
3251 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003252 }
3253 return true;
3254 })) {
3255 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003256 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003257 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003258 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003259 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003260 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003261 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003262 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003263 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003264 // for task|target directives.
3265 // Skip analysis of arguments of implicitly defined map clause for target
3266 // directives.
3267 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3268 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003269 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003270 if (CC)
3271 Visit(CC);
3272 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003273 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003274 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003275 // Check implicitly captured variables.
3276 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003277 }
3278 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003279 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003280 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003281 // Check implicitly captured variables in the task-based directives to
3282 // check if they must be firstprivatized.
3283 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003284 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003285 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003286 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003287
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003288 void visitSubCaptures(CapturedStmt *S) {
3289 for (const CapturedStmt::Capture &Cap : S->captures()) {
3290 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3291 continue;
3292 VarDecl *VD = Cap.getCapturedVar();
3293 // Do not try to map the variable if it or its sub-component was mapped
3294 // already.
3295 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3296 Stack->checkMappableExprComponentListsForDecl(
3297 VD, /*CurrentRegionOnly=*/true,
3298 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3299 OpenMPClauseKind) { return true; }))
3300 continue;
3301 DeclRefExpr *DRE = buildDeclRefExpr(
3302 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3303 Cap.getLocation(), /*RefersToCapture=*/true);
3304 Visit(DRE);
3305 }
3306 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003307 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003308 ArrayRef<Expr *> getImplicitFirstprivate() const {
3309 return ImplicitFirstprivate;
3310 }
cchene06f3e02019-11-15 13:02:06 -05003311 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3312 return ImplicitMap[Kind];
3313 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003314 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003315 return VarsWithInheritedDSA;
3316 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003317
Alexey Bataev7ff55242014-06-19 09:13:45 +00003318 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003319 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3320 // Process declare target link variables for the target directives.
3321 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3322 for (DeclRefExpr *E : Stack->getLinkGlobals())
3323 Visit(E);
3324 }
3325 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003326};
Alexey Bataeved09d242014-05-28 05:53:51 +00003327} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003328
Alexey Bataevbae9a792014-06-27 10:37:06 +00003329void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003330 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003331 case OMPD_parallel:
3332 case OMPD_parallel_for:
3333 case OMPD_parallel_for_simd:
3334 case OMPD_parallel_sections:
cchen47d60942019-12-05 13:43:48 -05003335 case OMPD_parallel_master:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003336 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003337 case OMPD_teams_distribute:
3338 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003339 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003340 QualType KmpInt32PtrTy =
3341 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003342 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003343 std::make_pair(".global_tid.", KmpInt32PtrTy),
3344 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3345 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003346 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003347 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3348 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003349 break;
3350 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003351 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003352 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003353 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003354 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003355 case OMPD_target_teams_distribute:
3356 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003357 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3358 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3359 QualType KmpInt32PtrTy =
3360 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3361 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003362 FunctionProtoType::ExtProtoInfo EPI;
3363 EPI.Variadic = true;
3364 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3365 Sema::CapturedParamNameType Params[] = {
3366 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003367 std::make_pair(".part_id.", KmpInt32PtrTy),
3368 std::make_pair(".privates.", VoidPtrTy),
3369 std::make_pair(
3370 ".copy_fn.",
3371 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003372 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3373 std::make_pair(StringRef(), QualType()) // __context with shared vars
3374 };
3375 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003376 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003377 // Mark this captured region as inlined, because we don't use outlined
3378 // function directly.
3379 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3380 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003381 Context, {}, AttributeCommonInfo::AS_Keyword,
3382 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003383 Sema::CapturedParamNameType ParamsTarget[] = {
3384 std::make_pair(StringRef(), QualType()) // __context with shared vars
3385 };
3386 // Start a captured region for 'target' with no implicit parameters.
3387 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003388 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003389 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003390 std::make_pair(".global_tid.", KmpInt32PtrTy),
3391 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3392 std::make_pair(StringRef(), QualType()) // __context with shared vars
3393 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003394 // Start a captured region for 'teams' or 'parallel'. Both regions have
3395 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003396 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003397 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003398 break;
3399 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003400 case OMPD_target:
3401 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003402 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3403 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3404 QualType KmpInt32PtrTy =
3405 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3406 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003407 FunctionProtoType::ExtProtoInfo EPI;
3408 EPI.Variadic = true;
3409 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3410 Sema::CapturedParamNameType Params[] = {
3411 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003412 std::make_pair(".part_id.", KmpInt32PtrTy),
3413 std::make_pair(".privates.", VoidPtrTy),
3414 std::make_pair(
3415 ".copy_fn.",
3416 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003417 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3418 std::make_pair(StringRef(), QualType()) // __context with shared vars
3419 };
3420 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003421 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003422 // Mark this captured region as inlined, because we don't use outlined
3423 // function directly.
3424 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3425 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003426 Context, {}, AttributeCommonInfo::AS_Keyword,
3427 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003428 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003429 std::make_pair(StringRef(), QualType()),
3430 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003431 break;
3432 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003433 case OMPD_simd:
3434 case OMPD_for:
3435 case OMPD_for_simd:
3436 case OMPD_sections:
3437 case OMPD_section:
3438 case OMPD_single:
3439 case OMPD_master:
3440 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003441 case OMPD_taskgroup:
3442 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003443 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003444 case OMPD_ordered:
3445 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003446 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003447 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003448 std::make_pair(StringRef(), QualType()) // __context with shared vars
3449 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003450 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3451 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003452 break;
3453 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003454 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003455 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3456 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3457 QualType KmpInt32PtrTy =
3458 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3459 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003460 FunctionProtoType::ExtProtoInfo EPI;
3461 EPI.Variadic = true;
3462 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003463 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003464 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003465 std::make_pair(".part_id.", KmpInt32PtrTy),
3466 std::make_pair(".privates.", VoidPtrTy),
3467 std::make_pair(
3468 ".copy_fn.",
3469 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003470 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003471 std::make_pair(StringRef(), QualType()) // __context with shared vars
3472 };
3473 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3474 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003475 // Mark this captured region as inlined, because we don't use outlined
3476 // function directly.
3477 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3478 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003479 Context, {}, AttributeCommonInfo::AS_Keyword,
3480 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003481 break;
3482 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003483 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003484 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003485 case OMPD_master_taskloop:
3486 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003487 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003488 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3489 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003490 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003491 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3492 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003493 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003494 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3495 .withConst();
3496 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3497 QualType KmpInt32PtrTy =
3498 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3499 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003500 FunctionProtoType::ExtProtoInfo EPI;
3501 EPI.Variadic = true;
3502 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003503 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003504 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003505 std::make_pair(".part_id.", KmpInt32PtrTy),
3506 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003507 std::make_pair(
3508 ".copy_fn.",
3509 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3510 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3511 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003512 std::make_pair(".ub.", KmpUInt64Ty),
3513 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003514 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003515 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003516 std::make_pair(StringRef(), QualType()) // __context with shared vars
3517 };
3518 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3519 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003520 // Mark this captured region as inlined, because we don't use outlined
3521 // function directly.
3522 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3523 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003524 Context, {}, AttributeCommonInfo::AS_Keyword,
3525 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003526 break;
3527 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003528 case OMPD_parallel_master_taskloop:
3529 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003530 QualType KmpInt32Ty =
3531 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3532 .withConst();
3533 QualType KmpUInt64Ty =
3534 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3535 .withConst();
3536 QualType KmpInt64Ty =
3537 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3538 .withConst();
3539 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3540 QualType KmpInt32PtrTy =
3541 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3542 Sema::CapturedParamNameType ParamsParallel[] = {
3543 std::make_pair(".global_tid.", KmpInt32PtrTy),
3544 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3545 std::make_pair(StringRef(), QualType()) // __context with shared vars
3546 };
3547 // Start a captured region for 'parallel'.
3548 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3549 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3550 QualType Args[] = {VoidPtrTy};
3551 FunctionProtoType::ExtProtoInfo EPI;
3552 EPI.Variadic = true;
3553 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3554 Sema::CapturedParamNameType Params[] = {
3555 std::make_pair(".global_tid.", KmpInt32Ty),
3556 std::make_pair(".part_id.", KmpInt32PtrTy),
3557 std::make_pair(".privates.", VoidPtrTy),
3558 std::make_pair(
3559 ".copy_fn.",
3560 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3561 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3562 std::make_pair(".lb.", KmpUInt64Ty),
3563 std::make_pair(".ub.", KmpUInt64Ty),
3564 std::make_pair(".st.", KmpInt64Ty),
3565 std::make_pair(".liter.", KmpInt32Ty),
3566 std::make_pair(".reductions.", VoidPtrTy),
3567 std::make_pair(StringRef(), QualType()) // __context with shared vars
3568 };
3569 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3570 Params, /*OpenMPCaptureLevel=*/2);
3571 // Mark this captured region as inlined, because we don't use outlined
3572 // function directly.
3573 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3574 AlwaysInlineAttr::CreateImplicit(
3575 Context, {}, AttributeCommonInfo::AS_Keyword,
3576 AlwaysInlineAttr::Keyword_forceinline));
3577 break;
3578 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003579 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003580 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003581 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003582 QualType KmpInt32PtrTy =
3583 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3584 Sema::CapturedParamNameType Params[] = {
3585 std::make_pair(".global_tid.", KmpInt32PtrTy),
3586 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003587 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3588 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003589 std::make_pair(StringRef(), QualType()) // __context with shared vars
3590 };
3591 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3592 Params);
3593 break;
3594 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003595 case OMPD_target_teams_distribute_parallel_for:
3596 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003597 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003598 QualType KmpInt32PtrTy =
3599 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003600 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003601
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003602 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003603 FunctionProtoType::ExtProtoInfo EPI;
3604 EPI.Variadic = true;
3605 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3606 Sema::CapturedParamNameType Params[] = {
3607 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003608 std::make_pair(".part_id.", KmpInt32PtrTy),
3609 std::make_pair(".privates.", VoidPtrTy),
3610 std::make_pair(
3611 ".copy_fn.",
3612 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003613 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3614 std::make_pair(StringRef(), QualType()) // __context with shared vars
3615 };
3616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003617 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003618 // Mark this captured region as inlined, because we don't use outlined
3619 // function directly.
3620 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3621 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003622 Context, {}, AttributeCommonInfo::AS_Keyword,
3623 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003624 Sema::CapturedParamNameType ParamsTarget[] = {
3625 std::make_pair(StringRef(), QualType()) // __context with shared vars
3626 };
3627 // Start a captured region for 'target' with no implicit parameters.
3628 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003629 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003630
3631 Sema::CapturedParamNameType ParamsTeams[] = {
3632 std::make_pair(".global_tid.", KmpInt32PtrTy),
3633 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3634 std::make_pair(StringRef(), QualType()) // __context with shared vars
3635 };
3636 // Start a captured region for 'target' with no implicit parameters.
3637 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003638 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003639
3640 Sema::CapturedParamNameType ParamsParallel[] = {
3641 std::make_pair(".global_tid.", KmpInt32PtrTy),
3642 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003643 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3644 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003645 std::make_pair(StringRef(), QualType()) // __context with shared vars
3646 };
3647 // Start a captured region for 'teams' or 'parallel'. Both regions have
3648 // the same implicit parameters.
3649 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003650 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003651 break;
3652 }
3653
Alexey Bataev46506272017-12-05 17:41:34 +00003654 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003655 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003656 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003657 QualType KmpInt32PtrTy =
3658 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3659
3660 Sema::CapturedParamNameType ParamsTeams[] = {
3661 std::make_pair(".global_tid.", KmpInt32PtrTy),
3662 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3663 std::make_pair(StringRef(), QualType()) // __context with shared vars
3664 };
3665 // Start a captured region for 'target' with no implicit parameters.
3666 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003667 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003668
3669 Sema::CapturedParamNameType ParamsParallel[] = {
3670 std::make_pair(".global_tid.", KmpInt32PtrTy),
3671 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003672 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3673 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003674 std::make_pair(StringRef(), QualType()) // __context with shared vars
3675 };
3676 // Start a captured region for 'teams' or 'parallel'. Both regions have
3677 // the same implicit parameters.
3678 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003679 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003680 break;
3681 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003682 case OMPD_target_update:
3683 case OMPD_target_enter_data:
3684 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003685 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3686 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3687 QualType KmpInt32PtrTy =
3688 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3689 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003690 FunctionProtoType::ExtProtoInfo EPI;
3691 EPI.Variadic = true;
3692 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3693 Sema::CapturedParamNameType Params[] = {
3694 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003695 std::make_pair(".part_id.", KmpInt32PtrTy),
3696 std::make_pair(".privates.", VoidPtrTy),
3697 std::make_pair(
3698 ".copy_fn.",
3699 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003700 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3701 std::make_pair(StringRef(), QualType()) // __context with shared vars
3702 };
3703 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3704 Params);
3705 // Mark this captured region as inlined, because we don't use outlined
3706 // function directly.
3707 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3708 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003709 Context, {}, AttributeCommonInfo::AS_Keyword,
3710 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003711 break;
3712 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003713 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003714 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003715 case OMPD_taskyield:
3716 case OMPD_barrier:
3717 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003718 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003719 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003720 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003721 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003722 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003723 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003724 case OMPD_declare_target:
3725 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003726 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003727 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003728 llvm_unreachable("OpenMP Directive is not allowed");
3729 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003730 llvm_unreachable("Unknown OpenMP directive");
3731 }
3732}
3733
Alexey Bataev0e100032019-10-14 16:44:01 +00003734int Sema::getNumberOfConstructScopes(unsigned Level) const {
3735 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3736}
3737
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003738int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3739 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3740 getOpenMPCaptureRegions(CaptureRegions, DKind);
3741 return CaptureRegions.size();
3742}
3743
Alexey Bataev3392d762016-02-16 11:18:12 +00003744static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003745 Expr *CaptureExpr, bool WithInit,
3746 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003747 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003748 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003749 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003750 QualType Ty = Init->getType();
3751 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003752 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003753 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003754 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003755 Ty = C.getPointerType(Ty);
3756 ExprResult Res =
3757 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3758 if (!Res.isUsable())
3759 return nullptr;
3760 Init = Res.get();
3761 }
Alexey Bataev61205072016-03-02 04:57:40 +00003762 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003763 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003764 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003765 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003766 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003767 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003768 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003769 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003770 return CED;
3771}
3772
Alexey Bataev61205072016-03-02 04:57:40 +00003773static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3774 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003775 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003776 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003777 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003778 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003779 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3780 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003781 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003782 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003783}
3784
Alexey Bataev5a3af132016-03-29 08:58:54 +00003785static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003786 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003787 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003788 OMPCapturedExprDecl *CD = buildCaptureDecl(
3789 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3790 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003791 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3792 CaptureExpr->getExprLoc());
3793 }
3794 ExprResult Res = Ref;
3795 if (!S.getLangOpts().CPlusPlus &&
3796 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003797 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003798 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003799 if (!Res.isUsable())
3800 return ExprError();
3801 }
3802 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003803}
3804
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003805namespace {
3806// OpenMP directives parsed in this section are represented as a
3807// CapturedStatement with an associated statement. If a syntax error
3808// is detected during the parsing of the associated statement, the
3809// compiler must abort processing and close the CapturedStatement.
3810//
3811// Combined directives such as 'target parallel' have more than one
3812// nested CapturedStatements. This RAII ensures that we unwind out
3813// of all the nested CapturedStatements when an error is found.
3814class CaptureRegionUnwinderRAII {
3815private:
3816 Sema &S;
3817 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003818 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003819
3820public:
3821 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3822 OpenMPDirectiveKind DKind)
3823 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3824 ~CaptureRegionUnwinderRAII() {
3825 if (ErrorFound) {
3826 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3827 while (--ThisCaptureLevel >= 0)
3828 S.ActOnCapturedRegionError();
3829 }
3830 }
3831};
3832} // namespace
3833
Alexey Bataevb600ae32019-07-01 17:46:52 +00003834void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3835 // Capture variables captured by reference in lambdas for target-based
3836 // directives.
3837 if (!CurContext->isDependentContext() &&
3838 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3839 isOpenMPTargetDataManagementDirective(
3840 DSAStack->getCurrentDirective()))) {
3841 QualType Type = V->getType();
3842 if (const auto *RD = Type.getCanonicalType()
3843 .getNonReferenceType()
3844 ->getAsCXXRecordDecl()) {
3845 bool SavedForceCaptureByReferenceInTargetExecutable =
3846 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3847 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3848 /*V=*/true);
3849 if (RD->isLambda()) {
3850 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3851 FieldDecl *ThisCapture;
3852 RD->getCaptureFields(Captures, ThisCapture);
3853 for (const LambdaCapture &LC : RD->captures()) {
3854 if (LC.getCaptureKind() == LCK_ByRef) {
3855 VarDecl *VD = LC.getCapturedVar();
3856 DeclContext *VDC = VD->getDeclContext();
3857 if (!VDC->Encloses(CurContext))
3858 continue;
3859 MarkVariableReferenced(LC.getLocation(), VD);
3860 } else if (LC.getCaptureKind() == LCK_This) {
3861 QualType ThisTy = getCurrentThisType();
3862 if (!ThisTy.isNull() &&
3863 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3864 CheckCXXThisCapture(LC.getLocation());
3865 }
3866 }
3867 }
3868 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3869 SavedForceCaptureByReferenceInTargetExecutable);
3870 }
3871 }
3872}
3873
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003874StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3875 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003876 bool ErrorFound = false;
3877 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3878 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003879 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003880 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003881 return StmtError();
3882 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003883
Alexey Bataev2ba67042017-11-28 21:11:44 +00003884 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3885 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003886 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003887 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003888 SmallVector<const OMPLinearClause *, 4> LCs;
3889 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003890 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003891 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003892 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3893 Clause->getClauseKind() == OMPC_in_reduction) {
3894 // Capture taskgroup task_reduction descriptors inside the tasking regions
3895 // with the corresponding in_reduction items.
3896 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003897 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003898 if (E)
3899 MarkDeclarationsReferencedInExpr(E);
3900 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003901 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003902 Clause->getClauseKind() == OMPC_copyprivate ||
3903 (getLangOpts().OpenMPUseTLS &&
3904 getASTContext().getTargetInfo().isTLSSupported() &&
3905 Clause->getClauseKind() == OMPC_copyin)) {
3906 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003907 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003908 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003909 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003910 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003911 }
3912 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003913 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003914 } else if (CaptureRegions.size() > 1 ||
3915 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003916 if (auto *C = OMPClauseWithPreInit::get(Clause))
3917 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003918 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003919 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003920 MarkDeclarationsReferencedInExpr(E);
3921 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003922 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003923 if (Clause->getClauseKind() == OMPC_schedule)
3924 SC = cast<OMPScheduleClause>(Clause);
3925 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003926 OC = cast<OMPOrderedClause>(Clause);
3927 else if (Clause->getClauseKind() == OMPC_linear)
3928 LCs.push_back(cast<OMPLinearClause>(Clause));
3929 }
Alexey Bataevf3c508f2020-01-23 10:47:16 -05003930 // Capture allocator expressions if used.
3931 for (Expr *E : DSAStack->getInnerAllocators())
3932 MarkDeclarationsReferencedInExpr(E);
Alexey Bataev6402bca2015-12-28 07:25:51 +00003933 // OpenMP, 2.7.1 Loop Construct, Restrictions
3934 // The nonmonotonic modifier cannot be specified if an ordered clause is
3935 // specified.
3936 if (SC &&
3937 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3938 SC->getSecondScheduleModifier() ==
3939 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3940 OC) {
3941 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3942 ? SC->getFirstScheduleModifierLoc()
3943 : SC->getSecondScheduleModifierLoc(),
3944 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003945 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003946 ErrorFound = true;
3947 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003948 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003949 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003950 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003951 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003952 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003953 ErrorFound = true;
3954 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003955 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3956 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3957 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003958 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003959 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3960 ErrorFound = true;
3961 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003962 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003963 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003964 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003965 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003966 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003967 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003968 // Mark all variables in private list clauses as used in inner region.
3969 // Required for proper codegen of combined directives.
3970 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003971 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003972 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003973 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3974 // Find the particular capture region for the clause if the
3975 // directive is a combined one with multiple capture regions.
3976 // If the directive is not a combined one, the capture region
3977 // associated with the clause is OMPD_unknown and is generated
3978 // only once.
3979 if (CaptureRegion == ThisCaptureRegion ||
3980 CaptureRegion == OMPD_unknown) {
3981 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003982 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003983 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3984 }
3985 }
3986 }
3987 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003988 if (++CompletedRegions == CaptureRegions.size())
3989 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003990 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003991 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003992 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003993}
3994
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003995static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3996 OpenMPDirectiveKind CancelRegion,
3997 SourceLocation StartLoc) {
3998 // CancelRegion is only needed for cancel and cancellation_point.
3999 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4000 return false;
4001
4002 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4003 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4004 return false;
4005
4006 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4007 << getOpenMPDirectiveName(CancelRegion);
4008 return true;
4009}
4010
Alexey Bataeve3727102018-04-18 15:57:46 +00004011static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004012 OpenMPDirectiveKind CurrentRegion,
4013 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004014 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004015 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004016 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004017 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4018 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004019 bool NestingProhibited = false;
4020 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00004021 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004022 enum {
4023 NoRecommend,
4024 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00004025 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004026 ShouldBeInTargetRegion,
4027 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004028 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004029 if (isOpenMPSimdDirective(ParentRegion) &&
4030 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4031 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4032 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004033 // OpenMP [2.16, Nesting of Regions]
4034 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004035 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00004036 // An ordered construct with the simd clause is the only OpenMP
4037 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00004038 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00004039 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4040 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004041 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4042 // The only OpenMP constructs that can be encountered during execution of
4043 // a simd region are the atomic construct, the loop construct, the simd
4044 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00004045 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4046 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004047 : diag::warn_omp_nesting_simd)
4048 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00004049 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00004050 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004051 if (ParentRegion == OMPD_atomic) {
4052 // OpenMP [2.16, Nesting of Regions]
4053 // OpenMP constructs may not be nested inside an atomic region.
4054 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4055 return true;
4056 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004057 if (CurrentRegion == OMPD_section) {
4058 // OpenMP [2.7.2, sections Construct, Restrictions]
4059 // Orphaned section directives are prohibited. That is, the section
4060 // directives must appear within the sections construct and must not be
4061 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004062 if (ParentRegion != OMPD_sections &&
4063 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004064 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4065 << (ParentRegion != OMPD_unknown)
4066 << getOpenMPDirectiveName(ParentRegion);
4067 return true;
4068 }
4069 return false;
4070 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00004071 // Allow some constructs (except teams and cancellation constructs) to be
4072 // orphaned (they could be used in functions, called from OpenMP regions
4073 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00004074 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00004075 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4076 CurrentRegion != OMPD_cancellation_point &&
4077 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004078 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00004079 if (CurrentRegion == OMPD_cancellation_point ||
4080 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004081 // OpenMP [2.16, Nesting of Regions]
4082 // A cancellation point construct for which construct-type-clause is
4083 // taskgroup must be nested inside a task construct. A cancellation
4084 // point construct for which construct-type-clause is not taskgroup must
4085 // be closely nested inside an OpenMP construct that matches the type
4086 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00004087 // A cancel construct for which construct-type-clause is taskgroup must be
4088 // nested inside a task construct. A cancel construct for which
4089 // construct-type-clause is not taskgroup must be closely nested inside an
4090 // OpenMP construct that matches the type specified in
4091 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004092 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004093 !((CancelRegion == OMPD_parallel &&
4094 (ParentRegion == OMPD_parallel ||
4095 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004096 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004097 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004098 ParentRegion == OMPD_target_parallel_for ||
4099 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004100 ParentRegion == OMPD_teams_distribute_parallel_for ||
4101 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004102 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4103 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004104 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4105 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004106 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004107 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004108 // OpenMP [2.16, Nesting of Regions]
4109 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004110 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004111 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004112 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004113 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4114 // OpenMP [2.16, Nesting of Regions]
4115 // A critical region may not be nested (closely or otherwise) inside a
4116 // critical region with the same name. Note that this restriction is not
4117 // sufficient to prevent deadlock.
4118 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004119 bool DeadLock = Stack->hasDirective(
4120 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4121 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004122 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004123 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4124 PreviousCriticalLoc = Loc;
4125 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004126 }
4127 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004128 },
4129 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004130 if (DeadLock) {
4131 SemaRef.Diag(StartLoc,
4132 diag::err_omp_prohibited_region_critical_same_name)
4133 << CurrentName.getName();
4134 if (PreviousCriticalLoc.isValid())
4135 SemaRef.Diag(PreviousCriticalLoc,
4136 diag::note_omp_previous_critical_region);
4137 return true;
4138 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004139 } else if (CurrentRegion == OMPD_barrier) {
4140 // OpenMP [2.16, Nesting of Regions]
4141 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004142 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004143 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4144 isOpenMPTaskingDirective(ParentRegion) ||
4145 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004146 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004147 ParentRegion == OMPD_critical ||
4148 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004149 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004150 !isOpenMPParallelDirective(CurrentRegion) &&
4151 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004152 // OpenMP [2.16, Nesting of Regions]
4153 // A worksharing region may not be closely nested inside a worksharing,
4154 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004155 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4156 isOpenMPTaskingDirective(ParentRegion) ||
4157 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004158 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004159 ParentRegion == OMPD_critical ||
4160 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004161 Recommend = ShouldBeInParallelRegion;
4162 } else if (CurrentRegion == OMPD_ordered) {
4163 // OpenMP [2.16, Nesting of Regions]
4164 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004165 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004166 // An ordered region must be closely nested inside a loop region (or
4167 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004168 // OpenMP [2.8.1,simd Construct, Restrictions]
4169 // An ordered construct with the simd clause is the only OpenMP construct
4170 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004171 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004172 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004173 !(isOpenMPSimdDirective(ParentRegion) ||
4174 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004175 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004176 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004177 // OpenMP [2.16, Nesting of Regions]
4178 // If specified, a teams construct must be contained within a target
4179 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004180 NestingProhibited =
4181 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4182 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4183 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004184 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004185 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004186 }
Kelvin Libf594a52016-12-17 05:48:59 +00004187 if (!NestingProhibited &&
4188 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4189 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4190 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004191 // OpenMP [2.16, Nesting of Regions]
4192 // distribute, parallel, parallel sections, parallel workshare, and the
4193 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4194 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004195 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4196 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004197 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004198 }
David Majnemer9d168222016-08-05 17:44:54 +00004199 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004200 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004201 // OpenMP 4.5 [2.17 Nesting of Regions]
4202 // The region associated with the distribute construct must be strictly
4203 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004204 NestingProhibited =
4205 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004206 Recommend = ShouldBeInTeamsRegion;
4207 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004208 if (!NestingProhibited &&
4209 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4210 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4211 // OpenMP 4.5 [2.17 Nesting of Regions]
4212 // If a target, target update, target data, target enter data, or
4213 // target exit data construct is encountered during execution of a
4214 // target region, the behavior is unspecified.
4215 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004216 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004217 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004218 if (isOpenMPTargetExecutionDirective(K)) {
4219 OffendingRegion = K;
4220 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004221 }
4222 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004223 },
4224 false /* don't skip top directive */);
4225 CloseNesting = false;
4226 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004227 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004228 if (OrphanSeen) {
4229 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4230 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4231 } else {
4232 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4233 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4234 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4235 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004236 return true;
4237 }
4238 }
4239 return false;
4240}
4241
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004242struct Kind2Unsigned {
4243 using argument_type = OpenMPDirectiveKind;
4244 unsigned operator()(argument_type DK) { return unsigned(DK); }
4245};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004246static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4247 ArrayRef<OMPClause *> Clauses,
4248 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4249 bool ErrorFound = false;
4250 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004251 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4252 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004253 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004254 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004255 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4256 // At most one if clause without a directive-name-modifier can appear on
4257 // the directive.
4258 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4259 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004260 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004261 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4262 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4263 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004264 } else if (CurNM != OMPD_unknown) {
4265 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004266 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004267 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004268 FoundNameModifiers[CurNM] = IC;
4269 if (CurNM == OMPD_unknown)
4270 continue;
4271 // Check if the specified name modifier is allowed for the current
4272 // directive.
4273 // At most one if clause with the particular directive-name-modifier can
4274 // appear on the directive.
4275 bool MatchFound = false;
4276 for (auto NM : AllowedNameModifiers) {
4277 if (CurNM == NM) {
4278 MatchFound = true;
4279 break;
4280 }
4281 }
4282 if (!MatchFound) {
4283 S.Diag(IC->getNameModifierLoc(),
4284 diag::err_omp_wrong_if_directive_name_modifier)
4285 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4286 ErrorFound = true;
4287 }
4288 }
4289 }
4290 // If any if clause on the directive includes a directive-name-modifier then
4291 // all if clauses on the directive must include a directive-name-modifier.
4292 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4293 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004294 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004295 diag::err_omp_no_more_if_clause);
4296 } else {
4297 std::string Values;
4298 std::string Sep(", ");
4299 unsigned AllowedCnt = 0;
4300 unsigned TotalAllowedNum =
4301 AllowedNameModifiers.size() - NamedModifiersNumber;
4302 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4303 ++Cnt) {
4304 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4305 if (!FoundNameModifiers[NM]) {
4306 Values += "'";
4307 Values += getOpenMPDirectiveName(NM);
4308 Values += "'";
4309 if (AllowedCnt + 2 == TotalAllowedNum)
4310 Values += " or ";
4311 else if (AllowedCnt + 1 != TotalAllowedNum)
4312 Values += Sep;
4313 ++AllowedCnt;
4314 }
4315 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004316 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004317 diag::err_omp_unnamed_if_clause)
4318 << (TotalAllowedNum > 1) << Values;
4319 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004320 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004321 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4322 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004323 ErrorFound = true;
4324 }
4325 return ErrorFound;
4326}
4327
Alexey Bataev0860db92019-12-19 10:01:10 -05004328static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4329 SourceLocation &ELoc,
4330 SourceRange &ERange,
4331 bool AllowArraySection) {
Alexey Bataeve106f252019-04-01 14:25:31 +00004332 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4333 RefExpr->containsUnexpandedParameterPack())
4334 return std::make_pair(nullptr, true);
4335
4336 // OpenMP [3.1, C/C++]
4337 // A list item is a variable name.
4338 // OpenMP [2.9.3.3, Restrictions, p.1]
4339 // A variable that is part of another variable (as an array or
4340 // structure element) cannot appear in a private clause.
4341 RefExpr = RefExpr->IgnoreParens();
4342 enum {
4343 NoArrayExpr = -1,
4344 ArraySubscript = 0,
4345 OMPArraySection = 1
4346 } IsArrayExpr = NoArrayExpr;
4347 if (AllowArraySection) {
4348 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4349 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4350 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4351 Base = TempASE->getBase()->IgnoreParenImpCasts();
4352 RefExpr = Base;
4353 IsArrayExpr = ArraySubscript;
4354 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4355 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4356 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4357 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4358 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4359 Base = TempASE->getBase()->IgnoreParenImpCasts();
4360 RefExpr = Base;
4361 IsArrayExpr = OMPArraySection;
4362 }
4363 }
4364 ELoc = RefExpr->getExprLoc();
4365 ERange = RefExpr->getSourceRange();
4366 RefExpr = RefExpr->IgnoreParenImpCasts();
4367 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4368 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4369 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4370 (S.getCurrentThisType().isNull() || !ME ||
4371 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4372 !isa<FieldDecl>(ME->getMemberDecl()))) {
4373 if (IsArrayExpr != NoArrayExpr) {
4374 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4375 << ERange;
4376 } else {
4377 S.Diag(ELoc,
4378 AllowArraySection
4379 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4380 : diag::err_omp_expected_var_name_member_expr)
4381 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4382 }
4383 return std::make_pair(nullptr, false);
4384 }
4385 return std::make_pair(
4386 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4387}
4388
4389static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004390 ArrayRef<OMPClause *> Clauses) {
4391 assert(!S.CurContext->isDependentContext() &&
4392 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004393 auto AllocateRange =
4394 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004395 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4396 DeclToCopy;
4397 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4398 return isOpenMPPrivate(C->getClauseKind());
4399 });
4400 for (OMPClause *Cl : PrivateRange) {
4401 MutableArrayRef<Expr *>::iterator I, It, Et;
4402 if (Cl->getClauseKind() == OMPC_private) {
4403 auto *PC = cast<OMPPrivateClause>(Cl);
4404 I = PC->private_copies().begin();
4405 It = PC->varlist_begin();
4406 Et = PC->varlist_end();
4407 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4408 auto *PC = cast<OMPFirstprivateClause>(Cl);
4409 I = PC->private_copies().begin();
4410 It = PC->varlist_begin();
4411 Et = PC->varlist_end();
4412 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4413 auto *PC = cast<OMPLastprivateClause>(Cl);
4414 I = PC->private_copies().begin();
4415 It = PC->varlist_begin();
4416 Et = PC->varlist_end();
4417 } else if (Cl->getClauseKind() == OMPC_linear) {
4418 auto *PC = cast<OMPLinearClause>(Cl);
4419 I = PC->privates().begin();
4420 It = PC->varlist_begin();
4421 Et = PC->varlist_end();
4422 } else if (Cl->getClauseKind() == OMPC_reduction) {
4423 auto *PC = cast<OMPReductionClause>(Cl);
4424 I = PC->privates().begin();
4425 It = PC->varlist_begin();
4426 Et = PC->varlist_end();
4427 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4428 auto *PC = cast<OMPTaskReductionClause>(Cl);
4429 I = PC->privates().begin();
4430 It = PC->varlist_begin();
4431 Et = PC->varlist_end();
4432 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4433 auto *PC = cast<OMPInReductionClause>(Cl);
4434 I = PC->privates().begin();
4435 It = PC->varlist_begin();
4436 Et = PC->varlist_end();
4437 } else {
4438 llvm_unreachable("Expected private clause.");
4439 }
4440 for (Expr *E : llvm::make_range(It, Et)) {
4441 if (!*I) {
4442 ++I;
4443 continue;
4444 }
4445 SourceLocation ELoc;
4446 SourceRange ERange;
4447 Expr *SimpleRefExpr = E;
4448 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4449 /*AllowArraySection=*/true);
4450 DeclToCopy.try_emplace(Res.first,
4451 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4452 ++I;
4453 }
4454 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004455 for (OMPClause *C : AllocateRange) {
4456 auto *AC = cast<OMPAllocateClause>(C);
4457 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4458 getAllocatorKind(S, Stack, AC->getAllocator());
4459 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4460 // For task, taskloop or target directives, allocation requests to memory
4461 // allocators with the trait access set to thread result in unspecified
4462 // behavior.
4463 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4464 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4465 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4466 S.Diag(AC->getAllocator()->getExprLoc(),
4467 diag::warn_omp_allocate_thread_on_task_target_directive)
4468 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004469 }
4470 for (Expr *E : AC->varlists()) {
4471 SourceLocation ELoc;
4472 SourceRange ERange;
4473 Expr *SimpleRefExpr = E;
4474 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4475 ValueDecl *VD = Res.first;
4476 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4477 if (!isOpenMPPrivate(Data.CKind)) {
4478 S.Diag(E->getExprLoc(),
4479 diag::err_omp_expected_private_copy_for_allocate);
4480 continue;
4481 }
4482 VarDecl *PrivateVD = DeclToCopy[VD];
4483 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4484 AllocatorKind, AC->getAllocator()))
4485 continue;
4486 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4487 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004488 }
4489 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004490}
4491
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004492StmtResult Sema::ActOnOpenMPExecutableDirective(
4493 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4494 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4495 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004496 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004497 // First check CancelRegion which is then used in checkNestingOfRegions.
4498 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4499 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004500 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004501 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004502
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004503 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004504 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004505 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004506 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004507 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004508 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4509
4510 // Check default data sharing attributes for referenced variables.
4511 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004512 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4513 Stmt *S = AStmt;
4514 while (--ThisCaptureLevel >= 0)
4515 S = cast<CapturedStmt>(S)->getCapturedStmt();
4516 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004517 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4518 !isOpenMPTaskingDirective(Kind)) {
4519 // Visit subcaptures to generate implicit clauses for captured vars.
4520 auto *CS = cast<CapturedStmt>(AStmt);
4521 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4522 getOpenMPCaptureRegions(CaptureRegions, Kind);
4523 // Ignore outer tasking regions for target directives.
4524 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4525 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4526 DSAChecker.visitSubCaptures(CS);
4527 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004528 if (DSAChecker.isErrorFound())
4529 return StmtError();
4530 // Generate list of implicitly defined firstprivate variables.
4531 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004532
Alexey Bataev88202be2017-07-27 13:20:36 +00004533 SmallVector<Expr *, 4> ImplicitFirstprivates(
4534 DSAChecker.getImplicitFirstprivate().begin(),
4535 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004536 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4537 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4538 ArrayRef<Expr *> ImplicitMap =
4539 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4540 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4541 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004542 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004543 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004544 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004545 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004546 if (E)
4547 ImplicitFirstprivates.emplace_back(E);
4548 }
4549 }
4550 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004551 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004552 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4553 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004554 ClausesWithImplicit.push_back(Implicit);
4555 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004556 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004557 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004558 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004559 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004560 }
cchene06f3e02019-11-15 13:02:06 -05004561 int ClauseKindCnt = -1;
4562 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4563 ++ClauseKindCnt;
4564 if (ImplicitMap.empty())
4565 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004566 CXXScopeSpec MapperIdScopeSpec;
4567 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004568 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004569 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004570 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4571 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4572 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004573 ClausesWithImplicit.emplace_back(Implicit);
4574 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004575 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004576 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004577 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004578 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004579 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004580 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004581
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004582 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004583 switch (Kind) {
4584 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004585 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4586 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004587 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004588 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004589 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004590 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4591 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004592 if (LangOpts.OpenMP >= 50)
4593 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004594 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004595 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004596 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4597 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004598 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004599 case OMPD_for_simd:
4600 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4601 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004602 if (LangOpts.OpenMP >= 50)
4603 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004604 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004605 case OMPD_sections:
4606 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4607 EndLoc);
4608 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004609 case OMPD_section:
4610 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004611 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004612 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4613 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004614 case OMPD_single:
4615 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4616 EndLoc);
4617 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004618 case OMPD_master:
4619 assert(ClausesWithImplicit.empty() &&
4620 "No clauses are allowed for 'omp master' directive");
4621 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4622 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004623 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004624 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4625 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004626 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004627 case OMPD_parallel_for:
4628 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4629 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004630 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004631 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004632 case OMPD_parallel_for_simd:
4633 Res = ActOnOpenMPParallelForSimdDirective(
4634 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004635 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004636 if (LangOpts.OpenMP >= 50)
4637 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004638 break;
cchen47d60942019-12-05 13:43:48 -05004639 case OMPD_parallel_master:
4640 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4641 StartLoc, EndLoc);
4642 AllowedNameModifiers.push_back(OMPD_parallel);
4643 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004644 case OMPD_parallel_sections:
4645 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4646 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004647 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004648 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004649 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004650 Res =
4651 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004652 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004653 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004654 case OMPD_taskyield:
4655 assert(ClausesWithImplicit.empty() &&
4656 "No clauses are allowed for 'omp taskyield' directive");
4657 assert(AStmt == nullptr &&
4658 "No associated statement allowed for 'omp taskyield' directive");
4659 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4660 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004661 case OMPD_barrier:
4662 assert(ClausesWithImplicit.empty() &&
4663 "No clauses are allowed for 'omp barrier' directive");
4664 assert(AStmt == nullptr &&
4665 "No associated statement allowed for 'omp barrier' directive");
4666 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4667 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004668 case OMPD_taskwait:
4669 assert(ClausesWithImplicit.empty() &&
4670 "No clauses are allowed for 'omp taskwait' directive");
4671 assert(AStmt == nullptr &&
4672 "No associated statement allowed for 'omp taskwait' directive");
4673 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4674 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004675 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004676 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4677 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004678 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004679 case OMPD_flush:
4680 assert(AStmt == nullptr &&
4681 "No associated statement allowed for 'omp flush' directive");
4682 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4683 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004684 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004685 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4686 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004687 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004688 case OMPD_atomic:
4689 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4690 EndLoc);
4691 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004692 case OMPD_teams:
4693 Res =
4694 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4695 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004696 case OMPD_target:
4697 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4698 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004699 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004700 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004701 case OMPD_target_parallel:
4702 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4703 StartLoc, EndLoc);
4704 AllowedNameModifiers.push_back(OMPD_target);
4705 AllowedNameModifiers.push_back(OMPD_parallel);
4706 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004707 case OMPD_target_parallel_for:
4708 Res = ActOnOpenMPTargetParallelForDirective(
4709 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4710 AllowedNameModifiers.push_back(OMPD_target);
4711 AllowedNameModifiers.push_back(OMPD_parallel);
4712 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004713 case OMPD_cancellation_point:
4714 assert(ClausesWithImplicit.empty() &&
4715 "No clauses are allowed for 'omp cancellation point' directive");
4716 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4717 "cancellation point' directive");
4718 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4719 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004720 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004721 assert(AStmt == nullptr &&
4722 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004723 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4724 CancelRegion);
4725 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004726 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004727 case OMPD_target_data:
4728 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4729 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004730 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004731 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004732 case OMPD_target_enter_data:
4733 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004734 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004735 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4736 break;
Samuel Antao72590762016-01-19 20:04:50 +00004737 case OMPD_target_exit_data:
4738 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004739 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004740 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4741 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004742 case OMPD_taskloop:
4743 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4744 EndLoc, VarsWithInheritedDSA);
4745 AllowedNameModifiers.push_back(OMPD_taskloop);
4746 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004747 case OMPD_taskloop_simd:
4748 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4749 EndLoc, VarsWithInheritedDSA);
4750 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004751 if (LangOpts.OpenMP >= 50)
4752 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004753 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004754 case OMPD_master_taskloop:
4755 Res = ActOnOpenMPMasterTaskLoopDirective(
4756 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4757 AllowedNameModifiers.push_back(OMPD_taskloop);
4758 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004759 case OMPD_master_taskloop_simd:
4760 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4761 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4762 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004763 if (LangOpts.OpenMP >= 50)
4764 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004765 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004766 case OMPD_parallel_master_taskloop:
4767 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4768 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4769 AllowedNameModifiers.push_back(OMPD_taskloop);
4770 AllowedNameModifiers.push_back(OMPD_parallel);
4771 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004772 case OMPD_parallel_master_taskloop_simd:
4773 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4774 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4775 AllowedNameModifiers.push_back(OMPD_taskloop);
4776 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004777 if (LangOpts.OpenMP >= 50)
4778 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004779 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004780 case OMPD_distribute:
4781 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4782 EndLoc, VarsWithInheritedDSA);
4783 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004784 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004785 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4786 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004787 AllowedNameModifiers.push_back(OMPD_target_update);
4788 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004789 case OMPD_distribute_parallel_for:
4790 Res = ActOnOpenMPDistributeParallelForDirective(
4791 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4792 AllowedNameModifiers.push_back(OMPD_parallel);
4793 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004794 case OMPD_distribute_parallel_for_simd:
4795 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4796 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4797 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004798 if (LangOpts.OpenMP >= 50)
4799 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004800 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004801 case OMPD_distribute_simd:
4802 Res = ActOnOpenMPDistributeSimdDirective(
4803 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004804 if (LangOpts.OpenMP >= 50)
4805 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004806 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004807 case OMPD_target_parallel_for_simd:
4808 Res = ActOnOpenMPTargetParallelForSimdDirective(
4809 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4810 AllowedNameModifiers.push_back(OMPD_target);
4811 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004812 if (LangOpts.OpenMP >= 50)
4813 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004814 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004815 case OMPD_target_simd:
4816 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4817 EndLoc, VarsWithInheritedDSA);
4818 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004819 if (LangOpts.OpenMP >= 50)
4820 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004821 break;
Kelvin Li02532872016-08-05 14:37:37 +00004822 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004823 Res = ActOnOpenMPTeamsDistributeDirective(
4824 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004825 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004826 case OMPD_teams_distribute_simd:
4827 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4828 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004829 if (LangOpts.OpenMP >= 50)
4830 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004831 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004832 case OMPD_teams_distribute_parallel_for_simd:
4833 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4834 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4835 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004836 if (LangOpts.OpenMP >= 50)
4837 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004838 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004839 case OMPD_teams_distribute_parallel_for:
4840 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4841 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4842 AllowedNameModifiers.push_back(OMPD_parallel);
4843 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004844 case OMPD_target_teams:
4845 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4846 EndLoc);
4847 AllowedNameModifiers.push_back(OMPD_target);
4848 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004849 case OMPD_target_teams_distribute:
4850 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4851 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4852 AllowedNameModifiers.push_back(OMPD_target);
4853 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004854 case OMPD_target_teams_distribute_parallel_for:
4855 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4856 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4857 AllowedNameModifiers.push_back(OMPD_target);
4858 AllowedNameModifiers.push_back(OMPD_parallel);
4859 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004860 case OMPD_target_teams_distribute_parallel_for_simd:
4861 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4862 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4863 AllowedNameModifiers.push_back(OMPD_target);
4864 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004865 if (LangOpts.OpenMP >= 50)
4866 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004867 break;
Kelvin Lida681182017-01-10 18:08:18 +00004868 case OMPD_target_teams_distribute_simd:
4869 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4870 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4871 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev411e81a2019-12-16 11:16:46 -05004872 if (LangOpts.OpenMP >= 50)
4873 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lida681182017-01-10 18:08:18 +00004874 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004875 case OMPD_declare_target:
4876 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004877 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004878 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004879 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004880 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004881 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004882 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004883 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004884 llvm_unreachable("OpenMP Directive is not allowed");
4885 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004886 llvm_unreachable("Unknown OpenMP directive");
4887 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004888
Roman Lebedevb5700602019-03-20 16:32:36 +00004889 ErrorFound = Res.isInvalid() || ErrorFound;
4890
Alexey Bataev412254a2019-05-09 18:44:53 +00004891 // Check variables in the clauses if default(none) was specified.
4892 if (DSAStack->getDefaultDSA() == DSA_none) {
4893 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4894 for (OMPClause *C : Clauses) {
4895 switch (C->getClauseKind()) {
4896 case OMPC_num_threads:
4897 case OMPC_dist_schedule:
4898 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004899 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004900 break;
4901 continue;
4902 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004903 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004904 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4905 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004906 if (isOpenMPParallelDirective(Kind) &&
4907 isOpenMPTaskLoopDirective(Kind) &&
4908 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4909 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004910 continue;
4911 case OMPC_schedule:
4912 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004913 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004914 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004915 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004916 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004917 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004918 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004919 break;
4920 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004921 case OMPC_ordered:
4922 case OMPC_device:
4923 case OMPC_num_teams:
4924 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004925 case OMPC_hint:
4926 case OMPC_collapse:
4927 case OMPC_safelen:
4928 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004929 case OMPC_default:
4930 case OMPC_proc_bind:
4931 case OMPC_private:
4932 case OMPC_firstprivate:
4933 case OMPC_lastprivate:
4934 case OMPC_shared:
4935 case OMPC_reduction:
4936 case OMPC_task_reduction:
4937 case OMPC_in_reduction:
4938 case OMPC_linear:
4939 case OMPC_aligned:
4940 case OMPC_copyin:
4941 case OMPC_copyprivate:
4942 case OMPC_nowait:
4943 case OMPC_untied:
4944 case OMPC_mergeable:
4945 case OMPC_allocate:
4946 case OMPC_read:
4947 case OMPC_write:
4948 case OMPC_update:
4949 case OMPC_capture:
4950 case OMPC_seq_cst:
4951 case OMPC_depend:
4952 case OMPC_threads:
4953 case OMPC_simd:
4954 case OMPC_map:
4955 case OMPC_nogroup:
4956 case OMPC_defaultmap:
4957 case OMPC_to:
4958 case OMPC_from:
4959 case OMPC_use_device_ptr:
4960 case OMPC_is_device_ptr:
Alexey Bataevb6e70842019-12-16 15:54:17 -05004961 case OMPC_nontemporal:
Alexey Bataev412254a2019-05-09 18:44:53 +00004962 continue;
4963 case OMPC_allocator:
4964 case OMPC_flush:
4965 case OMPC_threadprivate:
4966 case OMPC_uniform:
4967 case OMPC_unknown:
4968 case OMPC_unified_address:
4969 case OMPC_unified_shared_memory:
4970 case OMPC_reverse_offload:
4971 case OMPC_dynamic_allocators:
4972 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004973 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004974 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004975 llvm_unreachable("Unexpected clause");
4976 }
4977 for (Stmt *CC : C->children()) {
4978 if (CC)
4979 DSAChecker.Visit(CC);
4980 }
4981 }
4982 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4983 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4984 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004985 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004986 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4987 continue;
4988 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004989 if (DSAStack->getDefaultDSA() == DSA_none) {
4990 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4991 << P.first << P.second->getSourceRange();
4992 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4993 } else if (getLangOpts().OpenMP >= 50) {
4994 Diag(P.second->getExprLoc(),
4995 diag::err_omp_defaultmap_no_attr_for_variable)
4996 << P.first << P.second->getSourceRange();
4997 Diag(DSAStack->getDefaultDSALocation(),
4998 diag::note_omp_defaultmap_attr_none);
4999 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00005000 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005001
5002 if (!AllowedNameModifiers.empty())
5003 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5004 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00005005
Alexey Bataeved09d242014-05-28 05:53:51 +00005006 if (ErrorFound)
5007 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00005008
5009 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
5010 Res.getAs<OMPExecutableDirective>()
5011 ->getStructuredBlock()
5012 ->setIsOMPStructuredBlock(true);
5013 }
5014
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00005015 if (!CurContext->isDependentContext() &&
5016 isOpenMPTargetExecutionDirective(Kind) &&
5017 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5018 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5019 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5020 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5021 // Register target to DSA Stack.
5022 DSAStack->addTargetDirLocation(StartLoc);
5023 }
5024
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005025 return Res;
5026}
5027
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005028Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5029 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00005030 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00005031 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5032 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005033 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00005034 assert(Linears.size() == LinModifiers.size());
5035 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00005036 if (!DG || DG.get().isNull())
5037 return DeclGroupPtrTy();
5038
Alexey Bataevd158cf62019-09-13 20:18:17 +00005039 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005040 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005041 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5042 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005043 return DG;
5044 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005045 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00005046 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5047 ADecl = FTD->getTemplatedDecl();
5048
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005049 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5050 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005051 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005052 return DeclGroupPtrTy();
5053 }
5054
Alexey Bataev2af33e32016-04-07 12:45:37 +00005055 // OpenMP [2.8.2, declare simd construct, Description]
5056 // The parameter of the simdlen clause must be a constant positive integer
5057 // expression.
5058 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005059 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00005060 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005061 // OpenMP [2.8.2, declare simd construct, Description]
5062 // The special this pointer can be used as if was one of the arguments to the
5063 // function in any of the linear, aligned, or uniform clauses.
5064 // The uniform clause declares one or more arguments to have an invariant
5065 // value for all concurrent invocations of the function in the execution of a
5066 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00005067 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5068 const Expr *UniformedLinearThis = nullptr;
5069 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005070 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005071 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5072 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005073 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5074 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00005075 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00005076 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005077 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005078 }
5079 if (isa<CXXThisExpr>(E)) {
5080 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005081 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005082 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005083 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5084 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00005085 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00005086 // OpenMP [2.8.2, declare simd construct, Description]
5087 // The aligned clause declares that the object to which each list item points
5088 // is aligned to the number of bytes expressed in the optional parameter of
5089 // the aligned clause.
5090 // The special this pointer can be used as if was one of the arguments to the
5091 // function in any of the linear, aligned, or uniform clauses.
5092 // The type of list items appearing in the aligned clause must be array,
5093 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005094 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5095 const Expr *AlignedThis = nullptr;
5096 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005097 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005098 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5099 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5100 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005101 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5102 FD->getParamDecl(PVD->getFunctionScopeIndex())
5103 ->getCanonicalDecl() == CanonPVD) {
5104 // OpenMP [2.8.1, simd construct, Restrictions]
5105 // A list-item cannot appear in more than one aligned clause.
5106 if (AlignedArgs.count(CanonPVD) > 0) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005107 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5108 << 1 << getOpenMPClauseName(OMPC_aligned)
5109 << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005110 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5111 diag::note_omp_explicit_dsa)
5112 << getOpenMPClauseName(OMPC_aligned);
5113 continue;
5114 }
5115 AlignedArgs[CanonPVD] = E;
5116 QualType QTy = PVD->getType()
5117 .getNonReferenceType()
5118 .getUnqualifiedType()
5119 .getCanonicalType();
5120 const Type *Ty = QTy.getTypePtrOrNull();
5121 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5122 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5123 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5124 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5125 }
5126 continue;
5127 }
5128 }
5129 if (isa<CXXThisExpr>(E)) {
5130 if (AlignedThis) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005131 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5132 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005133 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5134 << getOpenMPClauseName(OMPC_aligned);
5135 }
5136 AlignedThis = E;
5137 continue;
5138 }
5139 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5140 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5141 }
5142 // The optional parameter of the aligned clause, alignment, must be a constant
5143 // positive integer expression. If no optional parameter is specified,
5144 // implementation-defined default alignments for SIMD instructions on the
5145 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005146 SmallVector<const Expr *, 4> NewAligns;
5147 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005148 ExprResult Align;
5149 if (E)
5150 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5151 NewAligns.push_back(Align.get());
5152 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005153 // OpenMP [2.8.2, declare simd construct, Description]
5154 // The linear clause declares one or more list items to be private to a SIMD
5155 // lane and to have a linear relationship with respect to the iteration space
5156 // of a loop.
5157 // The special this pointer can be used as if was one of the arguments to the
5158 // function in any of the linear, aligned, or uniform clauses.
5159 // When a linear-step expression is specified in a linear clause it must be
5160 // either a constant integer expression or an integer-typed parameter that is
5161 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005162 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005163 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5164 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005165 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005166 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5167 ++MI;
5168 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005169 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5170 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5171 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005172 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5173 FD->getParamDecl(PVD->getFunctionScopeIndex())
5174 ->getCanonicalDecl() == CanonPVD) {
5175 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5176 // A list-item cannot appear in more than one linear clause.
5177 if (LinearArgs.count(CanonPVD) > 0) {
5178 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5179 << getOpenMPClauseName(OMPC_linear)
5180 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5181 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5182 diag::note_omp_explicit_dsa)
5183 << getOpenMPClauseName(OMPC_linear);
5184 continue;
5185 }
5186 // Each argument can appear in at most one uniform or linear clause.
5187 if (UniformedArgs.count(CanonPVD) > 0) {
5188 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5189 << getOpenMPClauseName(OMPC_linear)
5190 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5191 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5192 diag::note_omp_explicit_dsa)
5193 << getOpenMPClauseName(OMPC_uniform);
5194 continue;
5195 }
5196 LinearArgs[CanonPVD] = E;
5197 if (E->isValueDependent() || E->isTypeDependent() ||
5198 E->isInstantiationDependent() ||
5199 E->containsUnexpandedParameterPack())
5200 continue;
5201 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5202 PVD->getOriginalType());
5203 continue;
5204 }
5205 }
5206 if (isa<CXXThisExpr>(E)) {
5207 if (UniformedLinearThis) {
5208 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5209 << getOpenMPClauseName(OMPC_linear)
5210 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5211 << E->getSourceRange();
5212 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5213 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5214 : OMPC_linear);
5215 continue;
5216 }
5217 UniformedLinearThis = E;
5218 if (E->isValueDependent() || E->isTypeDependent() ||
5219 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5220 continue;
5221 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5222 E->getType());
5223 continue;
5224 }
5225 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5226 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5227 }
5228 Expr *Step = nullptr;
5229 Expr *NewStep = nullptr;
5230 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005231 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005232 // Skip the same step expression, it was checked already.
5233 if (Step == E || !E) {
5234 NewSteps.push_back(E ? NewStep : nullptr);
5235 continue;
5236 }
5237 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005238 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5239 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5240 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005241 if (UniformedArgs.count(CanonPVD) == 0) {
5242 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5243 << Step->getSourceRange();
5244 } else if (E->isValueDependent() || E->isTypeDependent() ||
5245 E->isInstantiationDependent() ||
5246 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005247 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005248 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005249 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005250 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5251 << Step->getSourceRange();
5252 }
5253 continue;
5254 }
5255 NewStep = Step;
5256 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5257 !Step->isInstantiationDependent() &&
5258 !Step->containsUnexpandedParameterPack()) {
5259 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5260 .get();
5261 if (NewStep)
5262 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5263 }
5264 NewSteps.push_back(NewStep);
5265 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005266 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5267 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005268 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005269 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5270 const_cast<Expr **>(Linears.data()), Linears.size(),
5271 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5272 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005273 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005274 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005275}
5276
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005277static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5278 QualType NewType) {
5279 assert(NewType->isFunctionProtoType() &&
5280 "Expected function type with prototype.");
5281 assert(FD->getType()->isFunctionNoProtoType() &&
5282 "Expected function with type with no prototype.");
5283 assert(FDWithProto->getType()->isFunctionProtoType() &&
5284 "Expected function with prototype.");
5285 // Synthesize parameters with the same types.
5286 FD->setType(NewType);
5287 SmallVector<ParmVarDecl *, 16> Params;
5288 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5289 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5290 SourceLocation(), nullptr, P->getType(),
5291 /*TInfo=*/nullptr, SC_None, nullptr);
5292 Param->setScopeInfo(0, Params.size());
5293 Param->setImplicit();
5294 Params.push_back(Param);
5295 }
5296
5297 FD->setParams(Params);
5298}
5299
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005300Optional<std::pair<FunctionDecl *, Expr *>>
5301Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5302 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005303 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005304 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005305
5306 const int VariantId = 1;
5307 // Must be applied only to single decl.
5308 if (!DG.get().isSingleDecl()) {
5309 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5310 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005311 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005312 }
5313 Decl *ADecl = DG.get().getSingleDecl();
5314 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5315 ADecl = FTD->getTemplatedDecl();
5316
5317 // Decl must be a function.
5318 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5319 if (!FD) {
5320 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5321 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005322 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005323 }
5324
5325 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5326 return FD->hasAttrs() &&
5327 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5328 FD->hasAttr<TargetAttr>());
5329 };
5330 // OpenMP is not compatible with CPU-specific attributes.
5331 if (HasMultiVersionAttributes(FD)) {
5332 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5333 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005334 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005335 }
5336
5337 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005338 if (FD->isUsed(false))
5339 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005340 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005341
5342 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005343 const FunctionDecl *Definition;
5344 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5345 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005346 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5347 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005348
5349 // The VariantRef must point to function.
5350 if (!VariantRef) {
5351 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005352 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005353 }
5354
5355 // Do not check templates, wait until instantiation.
5356 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5357 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005358 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5359 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005360
5361 // Convert VariantRef expression to the type of the original function to
5362 // resolve possible conflicts.
5363 ExprResult VariantRefCast;
5364 if (LangOpts.CPlusPlus) {
5365 QualType FnPtrType;
5366 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5367 if (Method && !Method->isStatic()) {
5368 const Type *ClassType =
5369 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5370 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5371 ExprResult ER;
5372 {
5373 // Build adrr_of unary op to correctly handle type checks for member
5374 // functions.
5375 Sema::TentativeAnalysisScope Trap(*this);
5376 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5377 VariantRef);
5378 }
5379 if (!ER.isUsable()) {
5380 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5381 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005382 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005383 }
5384 VariantRef = ER.get();
5385 } else {
5386 FnPtrType = Context.getPointerType(FD->getType());
5387 }
5388 ImplicitConversionSequence ICS =
5389 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5390 /*SuppressUserConversions=*/false,
5391 /*AllowExplicit=*/false,
5392 /*InOverloadResolution=*/false,
5393 /*CStyle=*/false,
5394 /*AllowObjCWritebackConversion=*/false);
5395 if (ICS.isFailure()) {
5396 Diag(VariantRef->getExprLoc(),
5397 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005398 << VariantRef->getType()
5399 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5400 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005401 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005402 }
5403 VariantRefCast = PerformImplicitConversion(
5404 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5405 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005406 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005407 // Drop previously built artificial addr_of unary op for member functions.
5408 if (Method && !Method->isStatic()) {
5409 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5410 if (auto *UO = dyn_cast<UnaryOperator>(
5411 PossibleAddrOfVariantRef->IgnoreImplicit()))
5412 VariantRefCast = UO->getSubExpr();
5413 }
5414 } else {
5415 VariantRefCast = VariantRef;
5416 }
5417
5418 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5419 if (!ER.isUsable() ||
5420 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5421 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5422 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005423 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005424 }
5425
5426 // The VariantRef must point to function.
5427 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5428 if (!DRE) {
5429 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5430 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005431 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005432 }
5433 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5434 if (!NewFD) {
5435 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5436 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005437 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005438 }
5439
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005440 // Check if function types are compatible in C.
5441 if (!LangOpts.CPlusPlus) {
5442 QualType NewType =
5443 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5444 if (NewType.isNull()) {
5445 Diag(VariantRef->getExprLoc(),
5446 diag::err_omp_declare_variant_incompat_types)
5447 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5448 return None;
5449 }
5450 if (NewType->isFunctionProtoType()) {
5451 if (FD->getType()->isFunctionNoProtoType())
5452 setPrototype(*this, FD, NewFD, NewType);
5453 else if (NewFD->getType()->isFunctionNoProtoType())
5454 setPrototype(*this, NewFD, FD, NewType);
5455 }
5456 }
5457
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005458 // Check if variant function is not marked with declare variant directive.
5459 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5460 Diag(VariantRef->getExprLoc(),
5461 diag::warn_omp_declare_variant_marked_as_declare_variant)
5462 << VariantRef->getSourceRange();
5463 SourceRange SR =
5464 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5465 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005466 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005467 }
5468
Alexey Bataevd158cf62019-09-13 20:18:17 +00005469 enum DoesntSupport {
5470 VirtFuncs = 1,
5471 Constructors = 3,
5472 Destructors = 4,
5473 DeletedFuncs = 5,
5474 DefaultedFuncs = 6,
5475 ConstexprFuncs = 7,
5476 ConstevalFuncs = 8,
5477 };
5478 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5479 if (CXXFD->isVirtual()) {
5480 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5481 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005482 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005483 }
5484
5485 if (isa<CXXConstructorDecl>(FD)) {
5486 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5487 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005488 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005489 }
5490
5491 if (isa<CXXDestructorDecl>(FD)) {
5492 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5493 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005494 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005495 }
5496 }
5497
5498 if (FD->isDeleted()) {
5499 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5500 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005501 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005502 }
5503
5504 if (FD->isDefaulted()) {
5505 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5506 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005507 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005508 }
5509
5510 if (FD->isConstexpr()) {
5511 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5512 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005513 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005514 }
5515
5516 // Check general compatibility.
5517 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005518 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5519 PartialDiagnosticAt(SourceLocation(),
5520 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005521 PartialDiagnosticAt(
5522 VariantRef->getExprLoc(),
5523 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5524 PartialDiagnosticAt(VariantRef->getExprLoc(),
5525 PDiag(diag::err_omp_declare_variant_diff)
5526 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005527 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5528 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005529 return None;
5530 return std::make_pair(FD, cast<Expr>(DRE));
5531}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005532
Alexey Bataev9ff34742019-09-25 19:43:37 +00005533void Sema::ActOnOpenMPDeclareVariantDirective(
5534 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005535 ArrayRef<OMPCtxSelectorData> Data) {
5536 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005537 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005538 SmallVector<Expr *, 4> CtxScores;
5539 SmallVector<unsigned, 4> CtxSets;
5540 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005541 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005542 bool IsError = false;
5543 for (const OMPCtxSelectorData &D : Data) {
5544 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5545 OpenMPContextSelectorKind Ctx = D.Ctx;
5546 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5547 return;
5548 Expr *Score = nullptr;
5549 if (D.Score.isUsable()) {
5550 Score = D.Score.get();
5551 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5552 !Score->isInstantiationDependent() &&
5553 !Score->containsUnexpandedParameterPack()) {
5554 Score =
5555 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5556 .get();
5557 if (Score)
5558 Score = VerifyIntegerConstantExpression(Score).get();
5559 }
5560 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005561 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5562 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5563 // 2^(l+2), respectively, where l is the number of traits in the construct
5564 // set.
5565 // TODO: implement correct logic for isa and arch traits.
5566 // TODO: take the construct context set into account when it is
5567 // implemented.
5568 int L = 0; // Currently set the number of traits in construct set to 0,
5569 // since the construct trait set in not supported yet.
5570 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5571 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5572 else
5573 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005574 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005575 switch (Ctx) {
5576 case OMP_CTX_vendor:
5577 assert(CtxSet == OMP_CTX_SET_implementation &&
5578 "Expected implementation context selector set.");
5579 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005580 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005581 case OMP_CTX_kind:
5582 assert(CtxSet == OMP_CTX_SET_device &&
5583 "Expected device context selector set.");
5584 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005585 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005586 case OMP_CTX_unknown:
5587 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005588 }
5589 IsError = IsError || !Score;
5590 CtxSets.push_back(CtxSet);
5591 Ctxs.push_back(Ctx);
5592 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005593 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005594 if (!IsError) {
5595 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5596 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5597 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005598 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5599 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005600 FD->addAttr(NewAttr);
5601 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005602}
5603
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005604void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5605 FunctionDecl *Func,
5606 bool MightBeOdrUse) {
5607 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5608
5609 if (!Func->isDependentContext() && Func->hasAttrs()) {
5610 for (OMPDeclareVariantAttr *A :
5611 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5612 // TODO: add checks for active OpenMP context where possible.
5613 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005614 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005615 auto *F = cast<FunctionDecl>(DRE->getDecl());
5616 if (!F->isDefined() && F->isTemplateInstantiation())
5617 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5618 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5619 }
5620 }
5621}
5622
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005623StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5624 Stmt *AStmt,
5625 SourceLocation StartLoc,
5626 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005627 if (!AStmt)
5628 return StmtError();
5629
Alexey Bataeve3727102018-04-18 15:57:46 +00005630 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005631 // 1.2.2 OpenMP Language Terminology
5632 // Structured block - An executable statement with a single entry at the
5633 // top and a single exit at the bottom.
5634 // The point of exit cannot be a branch out of the structured block.
5635 // longjmp() and throw() must not violate the entry/exit criteria.
5636 CS->getCapturedDecl()->setNothrow();
5637
Reid Kleckner87a31802018-03-12 21:43:02 +00005638 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005639
Alexey Bataev25e5b442015-09-15 12:52:43 +00005640 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5641 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005642}
5643
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005644namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005645/// Iteration space of a single for loop.
5646struct LoopIterationSpace final {
5647 /// True if the condition operator is the strict compare operator (<, > or
5648 /// !=).
5649 bool IsStrictCompare = false;
5650 /// Condition of the loop.
5651 Expr *PreCond = nullptr;
5652 /// This expression calculates the number of iterations in the loop.
5653 /// It is always possible to calculate it before starting the loop.
5654 Expr *NumIterations = nullptr;
5655 /// The loop counter variable.
5656 Expr *CounterVar = nullptr;
5657 /// Private loop counter variable.
5658 Expr *PrivateCounterVar = nullptr;
5659 /// This is initializer for the initial value of #CounterVar.
5660 Expr *CounterInit = nullptr;
5661 /// This is step for the #CounterVar used to generate its update:
5662 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5663 Expr *CounterStep = nullptr;
5664 /// Should step be subtracted?
5665 bool Subtract = false;
5666 /// Source range of the loop init.
5667 SourceRange InitSrcRange;
5668 /// Source range of the loop condition.
5669 SourceRange CondSrcRange;
5670 /// Source range of the loop increment.
5671 SourceRange IncSrcRange;
5672 /// Minimum value that can have the loop control variable. Used to support
5673 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5674 /// since only such variables can be used in non-loop invariant expressions.
5675 Expr *MinValue = nullptr;
5676 /// Maximum value that can have the loop control variable. Used to support
5677 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5678 /// since only such variables can be used in non-loop invariant expressions.
5679 Expr *MaxValue = nullptr;
5680 /// true, if the lower bound depends on the outer loop control var.
5681 bool IsNonRectangularLB = false;
5682 /// true, if the upper bound depends on the outer loop control var.
5683 bool IsNonRectangularUB = false;
5684 /// Index of the loop this loop depends on and forms non-rectangular loop
5685 /// nest.
5686 unsigned LoopDependentIdx = 0;
5687 /// Final condition for the non-rectangular loop nest support. It is used to
5688 /// check that the number of iterations for this particular counter must be
5689 /// finished.
5690 Expr *FinalCondition = nullptr;
5691};
5692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005693/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005694/// extracting iteration space of each loop in the loop nest, that will be used
5695/// for IR generation.
5696class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005697 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005698 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005699 /// Data-sharing stack.
5700 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005701 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005702 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005703 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005704 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005705 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005706 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005707 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005708 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005709 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005710 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005711 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005712 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005713 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005714 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005715 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005716 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005717 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005718 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005719 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005720 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005721 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005722 /// Var < UB
5723 /// Var <= UB
5724 /// UB > Var
5725 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005726 /// This will have no value when the condition is !=
5727 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005728 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005729 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005730 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005731 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005732 /// The outer loop counter this loop depends on (if any).
5733 const ValueDecl *DepDecl = nullptr;
5734 /// Contains number of loop (starts from 1) on which loop counter init
5735 /// expression of this loop depends on.
5736 Optional<unsigned> InitDependOnLC;
5737 /// Contains number of loop (starts from 1) on which loop counter condition
5738 /// expression of this loop depends on.
5739 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005740 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005741 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005742 /// Original condition required for checking of the exit condition for
5743 /// non-rectangular loop.
5744 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005745
5746public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005747 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5748 SourceLocation DefaultLoc)
5749 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5750 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005751 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005752 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005753 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005754 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005755 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005756 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005757 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005758 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005759 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005760 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005761 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005762 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005763 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005764 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005765 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005766 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005767 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005768 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005769 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005770 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005771 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005772 /// True, if the compare operator is strict (<, > or !=).
5773 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005774 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005775 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005776 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005777 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005778 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005779 Expr *
5780 buildPreCond(Scope *S, Expr *Cond,
5781 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005782 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005783 DeclRefExpr *
5784 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5785 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005786 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005787 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005788 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005789 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005790 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005791 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005792 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005793 /// Build loop data with counter value for depend clauses in ordered
5794 /// directives.
5795 Expr *
5796 buildOrderedLoopData(Scope *S, Expr *Counter,
5797 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5798 SourceLocation Loc, Expr *Inc = nullptr,
5799 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005800 /// Builds the minimum value for the loop counter.
5801 std::pair<Expr *, Expr *> buildMinMaxValues(
5802 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5803 /// Builds final condition for the non-rectangular loops.
5804 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005805 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005806 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005807 /// Returns true if the initializer forms non-rectangular loop.
5808 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5809 /// Returns true if the condition forms non-rectangular loop.
5810 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5811 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5812 unsigned getLoopDependentIdx() const {
5813 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5814 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005815
5816private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005817 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005818 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005819 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005820 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005821 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5822 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005823 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005824 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5825 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005826 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005827 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005828};
5829
Alexey Bataeve3727102018-04-18 15:57:46 +00005830bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005831 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005832 assert(!LB && !UB && !Step);
5833 return false;
5834 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005835 return LCDecl->getType()->isDependentType() ||
5836 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5837 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005838}
5839
Alexey Bataeve3727102018-04-18 15:57:46 +00005840bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005841 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005842 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005843 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005844 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005845 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005846 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005847 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005848 LCDecl = getCanonicalDecl(NewLCDecl);
5849 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005850 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5851 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005852 if ((Ctor->isCopyOrMoveConstructor() ||
5853 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5854 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005855 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005856 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005857 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005858 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005859 return false;
5860}
5861
Alexey Bataev316ccf62019-01-29 18:51:58 +00005862bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5863 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005864 bool StrictOp, SourceRange SR,
5865 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005866 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005867 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5868 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005869 if (!NewUB)
5870 return true;
5871 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005872 if (LessOp)
5873 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005874 TestIsStrictOp = StrictOp;
5875 ConditionSrcRange = SR;
5876 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005877 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005878 return false;
5879}
5880
Alexey Bataeve3727102018-04-18 15:57:46 +00005881bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005882 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005883 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005884 if (!NewStep)
5885 return true;
5886 if (!NewStep->isValueDependent()) {
5887 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005888 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005889 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5890 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005891 if (Val.isInvalid())
5892 return true;
5893 NewStep = Val.get();
5894
5895 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5896 // If test-expr is of form var relational-op b and relational-op is < or
5897 // <= then incr-expr must cause var to increase on each iteration of the
5898 // loop. If test-expr is of form var relational-op b and relational-op is
5899 // > or >= then incr-expr must cause var to decrease on each iteration of
5900 // the loop.
5901 // If test-expr is of form b relational-op var and relational-op is < or
5902 // <= then incr-expr must cause var to decrease on each iteration of the
5903 // loop. If test-expr is of form b relational-op var and relational-op is
5904 // > or >= then incr-expr must cause var to increase on each iteration of
5905 // the loop.
5906 llvm::APSInt Result;
5907 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5908 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5909 bool IsConstNeg =
5910 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005911 bool IsConstPos =
5912 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005913 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005914
5915 // != with increment is treated as <; != with decrement is treated as >
5916 if (!TestIsLessOp.hasValue())
5917 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005918 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005919 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005920 (IsConstNeg || (IsUnsigned && Subtract)) :
5921 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005922 SemaRef.Diag(NewStep->getExprLoc(),
5923 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005924 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005925 SemaRef.Diag(ConditionLoc,
5926 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005927 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005928 return true;
5929 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005930 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005931 NewStep =
5932 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5933 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005934 Subtract = !Subtract;
5935 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005936 }
5937
5938 Step = NewStep;
5939 SubtractStep = Subtract;
5940 return false;
5941}
5942
Alexey Bataev622af1d2019-04-24 19:58:30 +00005943namespace {
5944/// Checker for the non-rectangular loops. Checks if the initializer or
5945/// condition expression references loop counter variable.
5946class LoopCounterRefChecker final
5947 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5948 Sema &SemaRef;
5949 DSAStackTy &Stack;
5950 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005951 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005952 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005953 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005954 unsigned BaseLoopId = 0;
5955 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5956 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5957 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5958 << (IsInitializer ? 0 : 1);
5959 return false;
5960 }
5961 const auto &&Data = Stack.isLoopControlVariable(VD);
5962 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5963 // The type of the loop iterator on which we depend may not have a random
5964 // access iterator type.
5965 if (Data.first && VD->getType()->isRecordType()) {
5966 SmallString<128> Name;
5967 llvm::raw_svector_ostream OS(Name);
5968 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5969 /*Qualified=*/true);
5970 SemaRef.Diag(E->getExprLoc(),
5971 diag::err_omp_wrong_dependency_iterator_type)
5972 << OS.str();
5973 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5974 return false;
5975 }
5976 if (Data.first &&
5977 (DepDecl || (PrevDepDecl &&
5978 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5979 if (!DepDecl && PrevDepDecl)
5980 DepDecl = PrevDepDecl;
5981 SmallString<128> Name;
5982 llvm::raw_svector_ostream OS(Name);
5983 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5984 /*Qualified=*/true);
5985 SemaRef.Diag(E->getExprLoc(),
5986 diag::err_omp_invariant_or_linear_dependency)
5987 << OS.str();
5988 return false;
5989 }
5990 if (Data.first) {
5991 DepDecl = VD;
5992 BaseLoopId = Data.first;
5993 }
5994 return Data.first;
5995 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005996
5997public:
5998 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5999 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006000 if (isa<VarDecl>(VD))
6001 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006002 return false;
6003 }
6004 bool VisitMemberExpr(const MemberExpr *E) {
6005 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6006 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00006007 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6008 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006009 }
6010 return false;
6011 }
6012 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006013 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006014 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00006015 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006016 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006017 }
6018 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006019 const ValueDecl *CurLCDecl, bool IsInitializer,
6020 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00006021 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006022 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6023 unsigned getBaseLoopId() const {
6024 assert(CurLCDecl && "Expected loop dependency.");
6025 return BaseLoopId;
6026 }
6027 const ValueDecl *getDepDecl() const {
6028 assert(CurLCDecl && "Expected loop dependency.");
6029 return DepDecl;
6030 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006031};
6032} // namespace
6033
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006034Optional<unsigned>
6035OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6036 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00006037 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006038 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6039 DepDecl);
6040 if (LoopStmtChecker.Visit(S)) {
6041 DepDecl = LoopStmtChecker.getDepDecl();
6042 return LoopStmtChecker.getBaseLoopId();
6043 }
6044 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006045}
6046
Alexey Bataeve3727102018-04-18 15:57:46 +00006047bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006048 // Check init-expr for canonical loop form and save loop counter
6049 // variable - #Var and its initialization value - #LB.
6050 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6051 // var = lb
6052 // integer-type var = lb
6053 // random-access-iterator-type var = lb
6054 // pointer-type var = lb
6055 //
6056 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00006057 if (EmitDiags) {
6058 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6059 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006060 return true;
6061 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006062 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6063 if (!ExprTemp->cleanupsHaveSideEffects())
6064 S = ExprTemp->getSubExpr();
6065
Alexander Musmana5f070a2014-10-01 06:03:56 +00006066 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006067 if (Expr *E = dyn_cast<Expr>(S))
6068 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006069 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006070 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006071 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006072 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6073 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6074 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006075 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6076 EmitDiags);
6077 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006078 }
6079 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6080 if (ME->isArrow() &&
6081 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006082 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6083 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006084 }
6085 }
David Majnemer9d168222016-08-05 17:44:54 +00006086 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006087 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006088 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006089 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006090 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006091 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006092 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006093 diag::ext_omp_loop_not_canonical_init)
6094 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006095 return setLCDeclAndLB(
6096 Var,
6097 buildDeclRefExpr(SemaRef, Var,
6098 Var->getType().getNonReferenceType(),
6099 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006100 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006101 }
6102 }
6103 }
David Majnemer9d168222016-08-05 17:44:54 +00006104 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006105 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006106 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006107 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006108 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6109 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006110 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6111 EmitDiags);
6112 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006113 }
6114 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6115 if (ME->isArrow() &&
6116 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006117 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6118 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006119 }
6120 }
6121 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006122
Alexey Bataeve3727102018-04-18 15:57:46 +00006123 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006124 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006125 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006126 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006127 << S->getSourceRange();
6128 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006129 return true;
6130}
6131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006132/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006133/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006134static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006135 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006136 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006137 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006138 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006139 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006140 if ((Ctor->isCopyOrMoveConstructor() ||
6141 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6142 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006143 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006144 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6145 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006146 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006147 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006148 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006149 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6150 return getCanonicalDecl(ME->getMemberDecl());
6151 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006152}
6153
Alexey Bataeve3727102018-04-18 15:57:46 +00006154bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006155 // Check test-expr for canonical form, save upper-bound UB, flags for
6156 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006157 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006158 // var relational-op b
6159 // b relational-op var
6160 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006161 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006162 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006163 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6164 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006165 return true;
6166 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006167 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006168 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006169 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006170 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006171 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006172 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6173 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006174 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6175 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6176 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006177 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6178 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006179 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6180 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6181 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006182 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6183 return setUB(
6184 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6185 /*LessOp=*/llvm::None,
6186 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006187 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006188 if (CE->getNumArgs() == 2) {
6189 auto Op = CE->getOperator();
6190 switch (Op) {
6191 case OO_Greater:
6192 case OO_GreaterEqual:
6193 case OO_Less:
6194 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006195 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6196 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006197 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6198 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006199 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6200 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006201 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6202 CE->getOperatorLoc());
6203 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006204 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006205 if (IneqCondIsCanonical)
6206 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6207 : CE->getArg(0),
6208 /*LessOp=*/llvm::None,
6209 /*StrictOp=*/true, CE->getSourceRange(),
6210 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006211 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006212 default:
6213 break;
6214 }
6215 }
6216 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006217 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006218 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006219 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006220 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006221 return true;
6222}
6223
Alexey Bataeve3727102018-04-18 15:57:46 +00006224bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006225 // RHS of canonical loop form increment can be:
6226 // var + incr
6227 // incr + var
6228 // var - incr
6229 //
6230 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006231 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006232 if (BO->isAdditiveOp()) {
6233 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006234 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6235 return setStep(BO->getRHS(), !IsAdd);
6236 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6237 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006238 }
David Majnemer9d168222016-08-05 17:44:54 +00006239 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006240 bool IsAdd = CE->getOperator() == OO_Plus;
6241 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006242 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6243 return setStep(CE->getArg(1), !IsAdd);
6244 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6245 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006246 }
6247 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006248 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006249 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006250 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006251 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006252 return true;
6253}
6254
Alexey Bataeve3727102018-04-18 15:57:46 +00006255bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006256 // Check incr-expr for canonical loop form and return true if it
6257 // does not conform.
6258 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6259 // ++var
6260 // var++
6261 // --var
6262 // var--
6263 // var += incr
6264 // var -= incr
6265 // var = var + incr
6266 // var = incr + var
6267 // var = var - incr
6268 //
6269 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006270 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006271 return true;
6272 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006273 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6274 if (!ExprTemp->cleanupsHaveSideEffects())
6275 S = ExprTemp->getSubExpr();
6276
Alexander Musmana5f070a2014-10-01 06:03:56 +00006277 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006278 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006279 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006280 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006281 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6282 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006283 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006284 (UO->isDecrementOp() ? -1 : 1))
6285 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006286 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006287 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006288 switch (BO->getOpcode()) {
6289 case BO_AddAssign:
6290 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006291 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6292 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006293 break;
6294 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006295 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6296 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006297 break;
6298 default:
6299 break;
6300 }
David Majnemer9d168222016-08-05 17:44:54 +00006301 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006302 switch (CE->getOperator()) {
6303 case OO_PlusPlus:
6304 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006305 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6306 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006307 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006308 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006309 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6310 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006311 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006312 break;
6313 case OO_PlusEqual:
6314 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006315 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6316 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006317 break;
6318 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006319 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6320 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006321 break;
6322 default:
6323 break;
6324 }
6325 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006326 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006327 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006328 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006329 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006330 return true;
6331}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006332
Alexey Bataev5a3af132016-03-29 08:58:54 +00006333static ExprResult
6334tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006335 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006336 if (SemaRef.CurContext->isDependentContext())
6337 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006338 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6339 return SemaRef.PerformImplicitConversion(
6340 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6341 /*AllowExplicit=*/true);
6342 auto I = Captures.find(Capture);
6343 if (I != Captures.end())
6344 return buildCapture(SemaRef, Capture, I->second);
6345 DeclRefExpr *Ref = nullptr;
6346 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6347 Captures[Capture] = Ref;
6348 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006349}
6350
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006351/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006352Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006353 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006354 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006355 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006356 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006357 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006358 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006359 Expr *LBVal = LB;
6360 Expr *UBVal = UB;
6361 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6362 // max(LB(MinVal), LB(MaxVal))
6363 if (InitDependOnLC) {
6364 const LoopIterationSpace &IS =
6365 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6366 InitDependOnLC.getValueOr(
6367 CondDependOnLC.getValueOr(0))];
6368 if (!IS.MinValue || !IS.MaxValue)
6369 return nullptr;
6370 // OuterVar = Min
6371 ExprResult MinValue =
6372 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6373 if (!MinValue.isUsable())
6374 return nullptr;
6375
6376 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6377 IS.CounterVar, MinValue.get());
6378 if (!LBMinVal.isUsable())
6379 return nullptr;
6380 // OuterVar = Min, LBVal
6381 LBMinVal =
6382 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6383 if (!LBMinVal.isUsable())
6384 return nullptr;
6385 // (OuterVar = Min, LBVal)
6386 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6387 if (!LBMinVal.isUsable())
6388 return nullptr;
6389
6390 // OuterVar = Max
6391 ExprResult MaxValue =
6392 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6393 if (!MaxValue.isUsable())
6394 return nullptr;
6395
6396 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6397 IS.CounterVar, MaxValue.get());
6398 if (!LBMaxVal.isUsable())
6399 return nullptr;
6400 // OuterVar = Max, LBVal
6401 LBMaxVal =
6402 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6403 if (!LBMaxVal.isUsable())
6404 return nullptr;
6405 // (OuterVar = Max, LBVal)
6406 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6407 if (!LBMaxVal.isUsable())
6408 return nullptr;
6409
6410 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6411 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6412 if (!LBMin || !LBMax)
6413 return nullptr;
6414 // LB(MinVal) < LB(MaxVal)
6415 ExprResult MinLessMaxRes =
6416 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6417 if (!MinLessMaxRes.isUsable())
6418 return nullptr;
6419 Expr *MinLessMax =
6420 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6421 if (!MinLessMax)
6422 return nullptr;
6423 if (TestIsLessOp.getValue()) {
6424 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6425 // LB(MaxVal))
6426 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6427 MinLessMax, LBMin, LBMax);
6428 if (!MinLB.isUsable())
6429 return nullptr;
6430 LBVal = MinLB.get();
6431 } else {
6432 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6433 // LB(MaxVal))
6434 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6435 MinLessMax, LBMax, LBMin);
6436 if (!MaxLB.isUsable())
6437 return nullptr;
6438 LBVal = MaxLB.get();
6439 }
6440 }
6441 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6442 // min(UB(MinVal), UB(MaxVal))
6443 if (CondDependOnLC) {
6444 const LoopIterationSpace &IS =
6445 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6446 InitDependOnLC.getValueOr(
6447 CondDependOnLC.getValueOr(0))];
6448 if (!IS.MinValue || !IS.MaxValue)
6449 return nullptr;
6450 // OuterVar = Min
6451 ExprResult MinValue =
6452 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6453 if (!MinValue.isUsable())
6454 return nullptr;
6455
6456 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6457 IS.CounterVar, MinValue.get());
6458 if (!UBMinVal.isUsable())
6459 return nullptr;
6460 // OuterVar = Min, UBVal
6461 UBMinVal =
6462 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6463 if (!UBMinVal.isUsable())
6464 return nullptr;
6465 // (OuterVar = Min, UBVal)
6466 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6467 if (!UBMinVal.isUsable())
6468 return nullptr;
6469
6470 // OuterVar = Max
6471 ExprResult MaxValue =
6472 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6473 if (!MaxValue.isUsable())
6474 return nullptr;
6475
6476 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6477 IS.CounterVar, MaxValue.get());
6478 if (!UBMaxVal.isUsable())
6479 return nullptr;
6480 // OuterVar = Max, UBVal
6481 UBMaxVal =
6482 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6483 if (!UBMaxVal.isUsable())
6484 return nullptr;
6485 // (OuterVar = Max, UBVal)
6486 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6487 if (!UBMaxVal.isUsable())
6488 return nullptr;
6489
6490 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6491 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6492 if (!UBMin || !UBMax)
6493 return nullptr;
6494 // UB(MinVal) > UB(MaxVal)
6495 ExprResult MinGreaterMaxRes =
6496 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6497 if (!MinGreaterMaxRes.isUsable())
6498 return nullptr;
6499 Expr *MinGreaterMax =
6500 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6501 if (!MinGreaterMax)
6502 return nullptr;
6503 if (TestIsLessOp.getValue()) {
6504 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6505 // UB(MaxVal))
6506 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6507 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6508 if (!MaxUB.isUsable())
6509 return nullptr;
6510 UBVal = MaxUB.get();
6511 } else {
6512 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6513 // UB(MaxVal))
6514 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6515 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6516 if (!MinUB.isUsable())
6517 return nullptr;
6518 UBVal = MinUB.get();
6519 }
6520 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006521 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006522 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6523 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006524 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6525 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006526 if (!Upper || !Lower)
6527 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006528
6529 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6530
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006531 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006532 // BuildBinOp already emitted error, this one is to point user to upper
6533 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006534 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006535 << Upper->getSourceRange() << Lower->getSourceRange();
6536 return nullptr;
6537 }
6538 }
6539
6540 if (!Diff.isUsable())
6541 return nullptr;
6542
6543 // Upper - Lower [- 1]
6544 if (TestIsStrictOp)
6545 Diff = SemaRef.BuildBinOp(
6546 S, DefaultLoc, BO_Sub, Diff.get(),
6547 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6548 if (!Diff.isUsable())
6549 return nullptr;
6550
6551 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006552 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006553 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006554 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006555 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006556 if (!Diff.isUsable())
6557 return nullptr;
6558
6559 // Parentheses (for dumping/debugging purposes only).
6560 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6561 if (!Diff.isUsable())
6562 return nullptr;
6563
6564 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006565 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006566 if (!Diff.isUsable())
6567 return nullptr;
6568
Alexander Musman174b3ca2014-10-06 11:16:29 +00006569 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006570 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006571 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006572 bool UseVarType = VarType->hasIntegerRepresentation() &&
6573 C.getTypeSize(Type) > C.getTypeSize(VarType);
6574 if (!Type->isIntegerType() || UseVarType) {
6575 unsigned NewSize =
6576 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6577 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6578 : Type->hasSignedIntegerRepresentation();
6579 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006580 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6581 Diff = SemaRef.PerformImplicitConversion(
6582 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6583 if (!Diff.isUsable())
6584 return nullptr;
6585 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006586 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006587 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006588 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6589 if (NewSize != C.getTypeSize(Type)) {
6590 if (NewSize < C.getTypeSize(Type)) {
6591 assert(NewSize == 64 && "incorrect loop var size");
6592 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6593 << InitSrcRange << ConditionSrcRange;
6594 }
6595 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006596 NewSize, Type->hasSignedIntegerRepresentation() ||
6597 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006598 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6599 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6600 Sema::AA_Converting, true);
6601 if (!Diff.isUsable())
6602 return nullptr;
6603 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006604 }
6605 }
6606
Alexander Musmana5f070a2014-10-01 06:03:56 +00006607 return Diff.get();
6608}
6609
Alexey Bataevf8be4762019-08-14 19:30:06 +00006610std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6611 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6612 // Do not build for iterators, they cannot be used in non-rectangular loop
6613 // nests.
6614 if (LCDecl->getType()->isRecordType())
6615 return std::make_pair(nullptr, nullptr);
6616 // If we subtract, the min is in the condition, otherwise the min is in the
6617 // init value.
6618 Expr *MinExpr = nullptr;
6619 Expr *MaxExpr = nullptr;
6620 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6621 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6622 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6623 : CondDependOnLC.hasValue();
6624 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6625 : InitDependOnLC.hasValue();
6626 Expr *Lower =
6627 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6628 Expr *Upper =
6629 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6630 if (!Upper || !Lower)
6631 return std::make_pair(nullptr, nullptr);
6632
6633 if (TestIsLessOp.getValue())
6634 MinExpr = Lower;
6635 else
6636 MaxExpr = Upper;
6637
6638 // Build minimum/maximum value based on number of iterations.
6639 ExprResult Diff;
6640 QualType VarType = LCDecl->getType().getNonReferenceType();
6641
6642 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6643 if (!Diff.isUsable())
6644 return std::make_pair(nullptr, nullptr);
6645
6646 // Upper - Lower [- 1]
6647 if (TestIsStrictOp)
6648 Diff = SemaRef.BuildBinOp(
6649 S, DefaultLoc, BO_Sub, Diff.get(),
6650 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6651 if (!Diff.isUsable())
6652 return std::make_pair(nullptr, nullptr);
6653
6654 // Upper - Lower [- 1] + Step
6655 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6656 if (!NewStep.isUsable())
6657 return std::make_pair(nullptr, nullptr);
6658
6659 // Parentheses (for dumping/debugging purposes only).
6660 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6661 if (!Diff.isUsable())
6662 return std::make_pair(nullptr, nullptr);
6663
6664 // (Upper - Lower [- 1]) / Step
6665 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6666 if (!Diff.isUsable())
6667 return std::make_pair(nullptr, nullptr);
6668
6669 // ((Upper - Lower [- 1]) / Step) * Step
6670 // Parentheses (for dumping/debugging purposes only).
6671 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6672 if (!Diff.isUsable())
6673 return std::make_pair(nullptr, nullptr);
6674
6675 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6676 if (!Diff.isUsable())
6677 return std::make_pair(nullptr, nullptr);
6678
6679 // Convert to the original type or ptrdiff_t, if original type is pointer.
6680 if (!VarType->isAnyPointerType() &&
6681 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6682 Diff = SemaRef.PerformImplicitConversion(
6683 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6684 } else if (VarType->isAnyPointerType() &&
6685 !SemaRef.Context.hasSameType(
6686 Diff.get()->getType(),
6687 SemaRef.Context.getUnsignedPointerDiffType())) {
6688 Diff = SemaRef.PerformImplicitConversion(
6689 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6690 Sema::AA_Converting, /*AllowExplicit=*/true);
6691 }
6692 if (!Diff.isUsable())
6693 return std::make_pair(nullptr, nullptr);
6694
6695 // Parentheses (for dumping/debugging purposes only).
6696 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6697 if (!Diff.isUsable())
6698 return std::make_pair(nullptr, nullptr);
6699
6700 if (TestIsLessOp.getValue()) {
6701 // MinExpr = Lower;
6702 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6703 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6704 if (!Diff.isUsable())
6705 return std::make_pair(nullptr, nullptr);
6706 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6707 if (!Diff.isUsable())
6708 return std::make_pair(nullptr, nullptr);
6709 MaxExpr = Diff.get();
6710 } else {
6711 // MaxExpr = Upper;
6712 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6713 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6714 if (!Diff.isUsable())
6715 return std::make_pair(nullptr, nullptr);
6716 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6717 if (!Diff.isUsable())
6718 return std::make_pair(nullptr, nullptr);
6719 MinExpr = Diff.get();
6720 }
6721
6722 return std::make_pair(MinExpr, MaxExpr);
6723}
6724
6725Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6726 if (InitDependOnLC || CondDependOnLC)
6727 return Condition;
6728 return nullptr;
6729}
6730
Alexey Bataeve3727102018-04-18 15:57:46 +00006731Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006732 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006733 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006734 // Do not build a precondition when the condition/initialization is dependent
6735 // to prevent pessimistic early loop exit.
6736 // TODO: this can be improved by calculating min/max values but not sure that
6737 // it will be very effective.
6738 if (CondDependOnLC || InitDependOnLC)
6739 return SemaRef.PerformImplicitConversion(
6740 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6741 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6742 /*AllowExplicit=*/true).get();
6743
Alexey Bataev62dbb972015-04-22 11:59:37 +00006744 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006745 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006746
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006747 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6748 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006749 if (!NewLB.isUsable() || !NewUB.isUsable())
6750 return nullptr;
6751
Alexey Bataeve3727102018-04-18 15:57:46 +00006752 ExprResult CondExpr =
6753 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006754 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006755 (TestIsStrictOp ? BO_LT : BO_LE) :
6756 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006757 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006758 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006759 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6760 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006761 CondExpr = SemaRef.PerformImplicitConversion(
6762 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6763 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006764 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006765
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006766 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006767 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6768}
6769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006770/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006771DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006772 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6773 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006774 auto *VD = dyn_cast<VarDecl>(LCDecl);
6775 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006776 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6777 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006778 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006779 const DSAStackTy::DSAVarData Data =
6780 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006781 // If the loop control decl is explicitly marked as private, do not mark it
6782 // as captured again.
6783 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6784 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006785 return Ref;
6786 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006787 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006788}
6789
Alexey Bataeve3727102018-04-18 15:57:46 +00006790Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006791 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006792 QualType Type = LCDecl->getType().getNonReferenceType();
6793 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006794 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6795 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6796 isa<VarDecl>(LCDecl)
6797 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6798 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006799 if (PrivateVar->isInvalidDecl())
6800 return nullptr;
6801 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6802 }
6803 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006804}
6805
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006806/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006807Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006808
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006809/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006810Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006811
Alexey Bataevf138fda2018-08-13 19:04:24 +00006812Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6813 Scope *S, Expr *Counter,
6814 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6815 Expr *Inc, OverloadedOperatorKind OOK) {
6816 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6817 if (!Cnt)
6818 return nullptr;
6819 if (Inc) {
6820 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6821 "Expected only + or - operations for depend clauses.");
6822 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6823 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6824 if (!Cnt)
6825 return nullptr;
6826 }
6827 ExprResult Diff;
6828 QualType VarType = LCDecl->getType().getNonReferenceType();
6829 if (VarType->isIntegerType() || VarType->isPointerType() ||
6830 SemaRef.getLangOpts().CPlusPlus) {
6831 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006832 Expr *Upper = TestIsLessOp.getValue()
6833 ? Cnt
6834 : tryBuildCapture(SemaRef, UB, Captures).get();
6835 Expr *Lower = TestIsLessOp.getValue()
6836 ? tryBuildCapture(SemaRef, LB, Captures).get()
6837 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006838 if (!Upper || !Lower)
6839 return nullptr;
6840
6841 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6842
6843 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6844 // BuildBinOp already emitted error, this one is to point user to upper
6845 // and lower bound, and to tell what is passed to 'operator-'.
6846 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6847 << Upper->getSourceRange() << Lower->getSourceRange();
6848 return nullptr;
6849 }
6850 }
6851
6852 if (!Diff.isUsable())
6853 return nullptr;
6854
6855 // Parentheses (for dumping/debugging purposes only).
6856 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6857 if (!Diff.isUsable())
6858 return nullptr;
6859
6860 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6861 if (!NewStep.isUsable())
6862 return nullptr;
6863 // (Upper - Lower) / Step
6864 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6865 if (!Diff.isUsable())
6866 return nullptr;
6867
6868 return Diff.get();
6869}
Alexey Bataev23b69422014-06-18 07:08:49 +00006870} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006871
Alexey Bataev9c821032015-04-30 04:23:23 +00006872void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6873 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6874 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006875 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6876 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006877 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006878 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006879 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006880 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6881 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006882 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006883 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006884 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006885 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006886 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006887 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006888 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6889 /*WithInit=*/false);
6890 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006891 }
6892 }
6893 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006894 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6895 if (LD != D->getCanonicalDecl()) {
6896 DSAStack->resetPossibleLoopCounter();
6897 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6898 MarkDeclarationsReferencedInExpr(
6899 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6900 Var->getType().getNonLValueExprType(Context),
6901 ForLoc, /*RefersToCapture=*/true));
6902 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006903 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6904 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6905 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6906 // associated for-loop of a simd construct with just one associated
6907 // for-loop may be listed in a linear clause with a constant-linear-step
6908 // that is the increment of the associated for-loop. The loop iteration
6909 // variable(s) in the associated for-loop(s) of a for or parallel for
6910 // construct may be listed in a private or lastprivate clause.
6911 DSAStackTy::DSAVarData DVar =
6912 DSAStack->getTopDSA(D, /*FromParent=*/false);
6913 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6914 // is declared in the loop and it is predetermined as a private.
6915 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6916 OpenMPClauseKind PredeterminedCKind =
6917 isOpenMPSimdDirective(DKind)
6918 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6919 : OMPC_private;
6920 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6921 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6922 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6923 DVar.CKind != OMPC_private))) ||
6924 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006925 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006926 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006927 isOpenMPDistributeDirective(DKind)) &&
6928 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6929 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6930 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6931 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6932 << getOpenMPClauseName(DVar.CKind)
6933 << getOpenMPDirectiveName(DKind)
6934 << getOpenMPClauseName(PredeterminedCKind);
6935 if (DVar.RefExpr == nullptr)
6936 DVar.CKind = PredeterminedCKind;
6937 reportOriginalDsa(*this, DSAStack, D, DVar,
6938 /*IsLoopIterVar=*/true);
6939 } else if (LoopDeclRefExpr) {
6940 // Make the loop iteration variable private (for worksharing
6941 // constructs), linear (for simd directives with the only one
6942 // associated loop) or lastprivate (for simd directives with several
6943 // collapsed or ordered loops).
6944 if (DVar.CKind == OMPC_unknown)
6945 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6946 PrivateRef);
6947 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006948 }
6949 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006950 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006951 }
6952}
6953
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006954/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006955/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006956static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006957 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6958 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006959 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6960 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006961 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006962 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006963 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006964 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006965 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006966 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006967 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006968 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6969 // Ranged for is supported only in OpenMP 5.0.
6970 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006971 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006972 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006973 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006974 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006975 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006976 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6977 SemaRef.Diag(DSA.getConstructLoc(),
6978 diag::note_omp_collapse_ordered_expr)
6979 << 2 << CollapseLoopCountExpr->getSourceRange()
6980 << OrderedLoopCountExpr->getSourceRange();
6981 else if (CollapseLoopCountExpr)
6982 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6983 diag::note_omp_collapse_ordered_expr)
6984 << 0 << CollapseLoopCountExpr->getSourceRange();
6985 else
6986 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6987 diag::note_omp_collapse_ordered_expr)
6988 << 1 << OrderedLoopCountExpr->getSourceRange();
6989 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006990 return true;
6991 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006992 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6993 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006994
Alexey Bataevbef93a92019-10-07 18:54:57 +00006995 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6996 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006997
6998 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006999 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00007000 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007001 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007002
7003 bool HasErrors = false;
7004
7005 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007006 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007007 // OpenMP [2.6, Canonical Loop Form]
7008 // Var is one of the following:
7009 // A variable of signed or unsigned integer type.
7010 // For C++, a variable of a random access iterator type.
7011 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007012 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007013 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7014 !VarType->isPointerType() &&
7015 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007016 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007017 << SemaRef.getLangOpts().CPlusPlus;
7018 HasErrors = true;
7019 }
7020
7021 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7022 // a Construct
7023 // The loop iteration variable(s) in the associated for-loop(s) of a for or
7024 // parallel for construct is (are) private.
7025 // The loop iteration variable in the associated for-loop of a simd
7026 // construct with just one associated for-loop is linear with a
7027 // constant-linear-step that is the increment of the associated for-loop.
7028 // Exclude loop var from the list of variables with implicitly defined data
7029 // sharing attributes.
7030 VarsWithImplicitDSA.erase(LCDecl);
7031
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007032 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7033
7034 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007035 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007036
7037 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007038 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007039 }
7040
Alexey Bataeve3727102018-04-18 15:57:46 +00007041 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007042 return HasErrors;
7043
Alexander Musmana5f070a2014-10-01 06:03:56 +00007044 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007045 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7046 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007047 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7048 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7049 (isOpenMPWorksharingDirective(DKind) ||
7050 isOpenMPTaskLoopDirective(DKind) ||
7051 isOpenMPDistributeDirective(DKind)),
7052 Captures);
7053 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7054 ISC.buildCounterVar(Captures, DSA);
7055 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7056 ISC.buildPrivateCounterVar();
7057 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7058 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7059 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7060 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7061 ISC.getConditionSrcRange();
7062 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7063 ISC.getIncrementSrcRange();
7064 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7065 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7066 ISC.isStrictTestOp();
7067 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7068 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7069 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7070 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7071 ISC.buildFinalCondition(DSA.getCurScope());
7072 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7073 ISC.doesInitDependOnLC();
7074 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7075 ISC.doesCondDependOnLC();
7076 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7077 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007078
Alexey Bataevf8be4762019-08-14 19:30:06 +00007079 HasErrors |=
7080 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7081 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7082 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7083 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7084 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7085 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007086 if (!HasErrors && DSA.isOrderedRegion()) {
7087 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7088 if (CurrentNestedLoopCount <
7089 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7090 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007091 CurrentNestedLoopCount,
7092 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007093 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007094 CurrentNestedLoopCount,
7095 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007096 }
7097 }
7098 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7099 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7100 // Erroneous case - clause has some problems.
7101 continue;
7102 }
7103 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7104 Pair.second.size() <= CurrentNestedLoopCount) {
7105 // Erroneous case - clause has some problems.
7106 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7107 continue;
7108 }
7109 Expr *CntValue;
7110 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7111 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007112 DSA.getCurScope(),
7113 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007114 Pair.first->getDependencyLoc());
7115 else
7116 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007117 DSA.getCurScope(),
7118 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007119 Pair.first->getDependencyLoc(),
7120 Pair.second[CurrentNestedLoopCount].first,
7121 Pair.second[CurrentNestedLoopCount].second);
7122 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7123 }
7124 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007125
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007126 return HasErrors;
7127}
7128
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007129/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007130static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007131buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007132 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007133 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007134 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007135 ExprResult NewStart = IsNonRectangularLB
7136 ? Start.get()
7137 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007138 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007139 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007140 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007141 VarRef.get()->getType())) {
7142 NewStart = SemaRef.PerformImplicitConversion(
7143 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7144 /*AllowExplicit=*/true);
7145 if (!NewStart.isUsable())
7146 return ExprError();
7147 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007148
Alexey Bataeve3727102018-04-18 15:57:46 +00007149 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007150 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7151 return Init;
7152}
7153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007154/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007155static ExprResult buildCounterUpdate(
7156 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7157 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007158 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007159 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007160 // Add parentheses (for debugging purposes only).
7161 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7162 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7163 !Step.isUsable())
7164 return ExprError();
7165
Alexey Bataev5a3af132016-03-29 08:58:54 +00007166 ExprResult NewStep = Step;
7167 if (Captures)
7168 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007169 if (NewStep.isInvalid())
7170 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007171 ExprResult Update =
7172 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007173 if (!Update.isUsable())
7174 return ExprError();
7175
Alexey Bataevc0214e02016-02-16 12:13:49 +00007176 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7177 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007178 if (!Start.isUsable())
7179 return ExprError();
7180 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7181 if (!NewStart.isUsable())
7182 return ExprError();
7183 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007184 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007185 if (NewStart.isInvalid())
7186 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007187
Alexey Bataevc0214e02016-02-16 12:13:49 +00007188 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7189 ExprResult SavedUpdate = Update;
7190 ExprResult UpdateVal;
7191 if (VarRef.get()->getType()->isOverloadableType() ||
7192 NewStart.get()->getType()->isOverloadableType() ||
7193 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007194 Sema::TentativeAnalysisScope Trap(SemaRef);
7195
Alexey Bataevc0214e02016-02-16 12:13:49 +00007196 Update =
7197 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7198 if (Update.isUsable()) {
7199 UpdateVal =
7200 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7201 VarRef.get(), SavedUpdate.get());
7202 if (UpdateVal.isUsable()) {
7203 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7204 UpdateVal.get());
7205 }
7206 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007207 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007208
Alexey Bataevc0214e02016-02-16 12:13:49 +00007209 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7210 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7211 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7212 NewStart.get(), SavedUpdate.get());
7213 if (!Update.isUsable())
7214 return ExprError();
7215
Alexey Bataev11481f52016-02-17 10:29:05 +00007216 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7217 VarRef.get()->getType())) {
7218 Update = SemaRef.PerformImplicitConversion(
7219 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7220 if (!Update.isUsable())
7221 return ExprError();
7222 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007223
7224 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7225 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007226 return Update;
7227}
7228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007229/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007230/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007231static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007232 if (E == nullptr)
7233 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007234 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007235 QualType OldType = E->getType();
7236 unsigned HasBits = C.getTypeSize(OldType);
7237 if (HasBits >= Bits)
7238 return ExprResult(E);
7239 // OK to convert to signed, because new type has more bits than old.
7240 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7241 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7242 true);
7243}
7244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007245/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007246/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007247static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007248 if (E == nullptr)
7249 return false;
7250 llvm::APSInt Result;
7251 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7252 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7253 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007254}
7255
Alexey Bataev5a3af132016-03-29 08:58:54 +00007256/// Build preinits statement for the given declarations.
7257static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007258 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007259 if (!PreInits.empty()) {
7260 return new (Context) DeclStmt(
7261 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7262 SourceLocation(), SourceLocation());
7263 }
7264 return nullptr;
7265}
7266
7267/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007268static Stmt *
7269buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007270 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007271 if (!Captures.empty()) {
7272 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007273 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007274 PreInits.push_back(Pair.second->getDecl());
7275 return buildPreInits(Context, PreInits);
7276 }
7277 return nullptr;
7278}
7279
7280/// Build postupdate expression for the given list of postupdates expressions.
7281static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7282 Expr *PostUpdate = nullptr;
7283 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007284 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007285 Expr *ConvE = S.BuildCStyleCastExpr(
7286 E->getExprLoc(),
7287 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7288 E->getExprLoc(), E)
7289 .get();
7290 PostUpdate = PostUpdate
7291 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7292 PostUpdate, ConvE)
7293 .get()
7294 : ConvE;
7295 }
7296 }
7297 return PostUpdate;
7298}
7299
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007300/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007301/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7302/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007303static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007304checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007305 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7306 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007307 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007308 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007309 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007310 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007311 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007312 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007313 if (!CollapseLoopCountExpr->isValueDependent() &&
7314 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007315 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007316 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007317 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007318 return 1;
7319 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007320 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007321 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007322 if (OrderedLoopCountExpr) {
7323 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007324 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007325 if (!OrderedLoopCountExpr->isValueDependent() &&
7326 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7327 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007328 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007329 if (Result.getLimitedValue() < NestedLoopCount) {
7330 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7331 diag::err_omp_wrong_ordered_loop_count)
7332 << OrderedLoopCountExpr->getSourceRange();
7333 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7334 diag::note_collapse_loop_count)
7335 << CollapseLoopCountExpr->getSourceRange();
7336 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007337 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007338 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007339 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007340 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007341 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007342 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007343 // This is helper routine for loop directives (e.g., 'for', 'simd',
7344 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007345 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007346 SmallVector<LoopIterationSpace, 4> IterSpaces(
7347 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007348 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007349 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007350 if (checkOpenMPIterationSpace(
7351 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7352 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007353 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007354 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007355 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007356 // OpenMP [2.8.1, simd construct, Restrictions]
7357 // All loops associated with the construct must be perfectly nested; that
7358 // is, there must be no intervening code nor any OpenMP directive between
7359 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007360 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7361 CurStmt = For->getBody();
7362 } else {
7363 assert(isa<CXXForRangeStmt>(CurStmt) &&
7364 "Expected canonical for or range-based for loops.");
7365 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7366 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007367 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7368 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007369 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007370 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7371 if (checkOpenMPIterationSpace(
7372 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7373 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007374 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007375 return 0;
7376 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7377 // Handle initialization of captured loop iterator variables.
7378 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7379 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7380 Captures[DRE] = DRE;
7381 }
7382 }
7383 // Move on to the next nested for loop, or to the loop body.
7384 // OpenMP [2.8.1, simd construct, Restrictions]
7385 // All loops associated with the construct must be perfectly nested; that
7386 // is, there must be no intervening code nor any OpenMP directive between
7387 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007388 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7389 CurStmt = For->getBody();
7390 } else {
7391 assert(isa<CXXForRangeStmt>(CurStmt) &&
7392 "Expected canonical for or range-based for loops.");
7393 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7394 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007395 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7396 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007397 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007398
Alexander Musmana5f070a2014-10-01 06:03:56 +00007399 Built.clear(/* size */ NestedLoopCount);
7400
7401 if (SemaRef.CurContext->isDependentContext())
7402 return NestedLoopCount;
7403
7404 // An example of what is generated for the following code:
7405 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007406 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007407 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007408 // for (k = 0; k < NK; ++k)
7409 // for (j = J0; j < NJ; j+=2) {
7410 // <loop body>
7411 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007412 //
7413 // We generate the code below.
7414 // Note: the loop body may be outlined in CodeGen.
7415 // Note: some counters may be C++ classes, operator- is used to find number of
7416 // iterations and operator+= to calculate counter value.
7417 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7418 // or i64 is currently supported).
7419 //
7420 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7421 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7422 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7423 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7424 // // similar updates for vars in clauses (e.g. 'linear')
7425 // <loop body (using local i and j)>
7426 // }
7427 // i = NI; // assign final values of counters
7428 // j = NJ;
7429 //
7430
7431 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7432 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007433 // Precondition tests if there is at least one iteration (all conditions are
7434 // true).
7435 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007436 Expr *N0 = IterSpaces[0].NumIterations;
7437 ExprResult LastIteration32 =
7438 widenIterationCount(/*Bits=*/32,
7439 SemaRef
7440 .PerformImplicitConversion(
7441 N0->IgnoreImpCasts(), N0->getType(),
7442 Sema::AA_Converting, /*AllowExplicit=*/true)
7443 .get(),
7444 SemaRef);
7445 ExprResult LastIteration64 = widenIterationCount(
7446 /*Bits=*/64,
7447 SemaRef
7448 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7449 Sema::AA_Converting,
7450 /*AllowExplicit=*/true)
7451 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007452 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007453
7454 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7455 return NestedLoopCount;
7456
Alexey Bataeve3727102018-04-18 15:57:46 +00007457 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007458 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7459
7460 Scope *CurScope = DSA.getCurScope();
7461 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007462 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007463 PreCond =
7464 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7465 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007466 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007467 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007468 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007469 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7470 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007471 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007472 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007473 SemaRef
7474 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7475 Sema::AA_Converting,
7476 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007477 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007478 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007479 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007480 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007481 SemaRef
7482 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7483 Sema::AA_Converting,
7484 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007485 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007486 }
7487
7488 // Choose either the 32-bit or 64-bit version.
7489 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007490 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7491 (LastIteration32.isUsable() &&
7492 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7493 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7494 fitsInto(
7495 /*Bits=*/32,
7496 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7497 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007498 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007499 QualType VType = LastIteration.get()->getType();
7500 QualType RealVType = VType;
7501 QualType StrideVType = VType;
7502 if (isOpenMPTaskLoopDirective(DKind)) {
7503 VType =
7504 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7505 StrideVType =
7506 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7507 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007508
7509 if (!LastIteration.isUsable())
7510 return 0;
7511
7512 // Save the number of iterations.
7513 ExprResult NumIterations = LastIteration;
7514 {
7515 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007516 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7517 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007518 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7519 if (!LastIteration.isUsable())
7520 return 0;
7521 }
7522
7523 // Calculate the last iteration number beforehand instead of doing this on
7524 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7525 llvm::APSInt Result;
7526 bool IsConstant =
7527 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7528 ExprResult CalcLastIteration;
7529 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007530 ExprResult SaveRef =
7531 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007532 LastIteration = SaveRef;
7533
7534 // Prepare SaveRef + 1.
7535 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007536 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007537 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7538 if (!NumIterations.isUsable())
7539 return 0;
7540 }
7541
7542 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7543
David Majnemer9d168222016-08-05 17:44:54 +00007544 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007545 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007546 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7547 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007548 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007549 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7550 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007551 SemaRef.AddInitializerToDecl(LBDecl,
7552 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7553 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007554
7555 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007556 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7557 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007558 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007559 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007560
7561 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7562 // This will be used to implement clause 'lastprivate'.
7563 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007564 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7565 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007566 SemaRef.AddInitializerToDecl(ILDecl,
7567 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7568 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007569
7570 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007571 VarDecl *STDecl =
7572 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7573 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007574 SemaRef.AddInitializerToDecl(STDecl,
7575 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7576 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007577
7578 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007579 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007580 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7581 UB.get(), LastIteration.get());
7582 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007583 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7584 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007585 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7586 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007587 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007588
7589 // If we have a combined directive that combines 'distribute', 'for' or
7590 // 'simd' we need to be able to access the bounds of the schedule of the
7591 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7592 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7593 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007594 // Lower bound variable, initialized with zero.
7595 VarDecl *CombLBDecl =
7596 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7597 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7598 SemaRef.AddInitializerToDecl(
7599 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7600 /*DirectInit*/ false);
7601
7602 // Upper bound variable, initialized with last iteration number.
7603 VarDecl *CombUBDecl =
7604 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7605 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7606 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7607 /*DirectInit*/ false);
7608
7609 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7610 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7611 ExprResult CombCondOp =
7612 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7613 LastIteration.get(), CombUB.get());
7614 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7615 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007616 CombEUB =
7617 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007618
Alexey Bataeve3727102018-04-18 15:57:46 +00007619 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007620 // We expect to have at least 2 more parameters than the 'parallel'
7621 // directive does - the lower and upper bounds of the previous schedule.
7622 assert(CD->getNumParams() >= 4 &&
7623 "Unexpected number of parameters in loop combined directive");
7624
7625 // Set the proper type for the bounds given what we learned from the
7626 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007627 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7628 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007629
7630 // Previous lower and upper bounds are obtained from the region
7631 // parameters.
7632 PrevLB =
7633 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7634 PrevUB =
7635 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7636 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007637 }
7638
7639 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007640 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007641 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007642 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007643 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7644 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007645 Expr *RHS =
7646 (isOpenMPWorksharingDirective(DKind) ||
7647 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7648 ? LB.get()
7649 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007650 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007651 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007652
7653 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7654 Expr *CombRHS =
7655 (isOpenMPWorksharingDirective(DKind) ||
7656 isOpenMPTaskLoopDirective(DKind) ||
7657 isOpenMPDistributeDirective(DKind))
7658 ? CombLB.get()
7659 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7660 CombInit =
7661 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007662 CombInit =
7663 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007664 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007665 }
7666
Alexey Bataev316ccf62019-01-29 18:51:58 +00007667 bool UseStrictCompare =
7668 RealVType->hasUnsignedIntegerRepresentation() &&
7669 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7670 return LIS.IsStrictCompare;
7671 });
7672 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7673 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007674 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007675 Expr *BoundUB = UB.get();
7676 if (UseStrictCompare) {
7677 BoundUB =
7678 SemaRef
7679 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7680 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7681 .get();
7682 BoundUB =
7683 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7684 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007685 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007686 (isOpenMPWorksharingDirective(DKind) ||
7687 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007688 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7689 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7690 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007691 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7692 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007693 ExprResult CombDistCond;
7694 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007695 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7696 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007697 }
7698
Carlo Bertolliffafe102017-04-20 00:39:39 +00007699 ExprResult CombCond;
7700 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007701 Expr *BoundCombUB = CombUB.get();
7702 if (UseStrictCompare) {
7703 BoundCombUB =
7704 SemaRef
7705 .BuildBinOp(
7706 CurScope, CondLoc, BO_Add, BoundCombUB,
7707 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7708 .get();
7709 BoundCombUB =
7710 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7711 .get();
7712 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007713 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007714 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7715 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007716 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007717 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007718 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007719 ExprResult Inc =
7720 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7721 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7722 if (!Inc.isUsable())
7723 return 0;
7724 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007725 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007726 if (!Inc.isUsable())
7727 return 0;
7728
7729 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7730 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007731 // In combined construct, add combined version that use CombLB and CombUB
7732 // base variables for the update
7733 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007734 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7735 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007736 // LB + ST
7737 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7738 if (!NextLB.isUsable())
7739 return 0;
7740 // LB = LB + ST
7741 NextLB =
7742 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007743 NextLB =
7744 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007745 if (!NextLB.isUsable())
7746 return 0;
7747 // UB + ST
7748 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7749 if (!NextUB.isUsable())
7750 return 0;
7751 // UB = UB + ST
7752 NextUB =
7753 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007754 NextUB =
7755 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007756 if (!NextUB.isUsable())
7757 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007758 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7759 CombNextLB =
7760 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7761 if (!NextLB.isUsable())
7762 return 0;
7763 // LB = LB + ST
7764 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7765 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007766 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7767 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007768 if (!CombNextLB.isUsable())
7769 return 0;
7770 // UB + ST
7771 CombNextUB =
7772 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7773 if (!CombNextUB.isUsable())
7774 return 0;
7775 // UB = UB + ST
7776 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7777 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007778 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7779 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007780 if (!CombNextUB.isUsable())
7781 return 0;
7782 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007783 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007784
Carlo Bertolliffafe102017-04-20 00:39:39 +00007785 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007786 // directive with for as IV = IV + ST; ensure upper bound expression based
7787 // on PrevUB instead of NumIterations - used to implement 'for' when found
7788 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007789 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007790 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007791 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007792 DistCond = SemaRef.BuildBinOp(
7793 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007794 assert(DistCond.isUsable() && "distribute cond expr was not built");
7795
7796 DistInc =
7797 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7798 assert(DistInc.isUsable() && "distribute inc expr was not built");
7799 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7800 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007801 DistInc =
7802 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007803 assert(DistInc.isUsable() && "distribute inc expr was not built");
7804
7805 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7806 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007807 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007808 ExprResult IsUBGreater =
7809 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7810 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7811 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7812 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7813 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007814 PrevEUB =
7815 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007816
Alexey Bataev316ccf62019-01-29 18:51:58 +00007817 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7818 // parallel for is in combination with a distribute directive with
7819 // schedule(static, 1)
7820 Expr *BoundPrevUB = PrevUB.get();
7821 if (UseStrictCompare) {
7822 BoundPrevUB =
7823 SemaRef
7824 .BuildBinOp(
7825 CurScope, CondLoc, BO_Add, BoundPrevUB,
7826 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7827 .get();
7828 BoundPrevUB =
7829 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7830 .get();
7831 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007832 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007833 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7834 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007835 }
7836
Alexander Musmana5f070a2014-10-01 06:03:56 +00007837 // Build updates and final values of the loop counters.
7838 bool HasErrors = false;
7839 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007840 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007841 Built.Updates.resize(NestedLoopCount);
7842 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007843 Built.DependentCounters.resize(NestedLoopCount);
7844 Built.DependentInits.resize(NestedLoopCount);
7845 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007846 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007847 // We implement the following algorithm for obtaining the
7848 // original loop iteration variable values based on the
7849 // value of the collapsed loop iteration variable IV.
7850 //
7851 // Let n+1 be the number of collapsed loops in the nest.
7852 // Iteration variables (I0, I1, .... In)
7853 // Iteration counts (N0, N1, ... Nn)
7854 //
7855 // Acc = IV;
7856 //
7857 // To compute Ik for loop k, 0 <= k <= n, generate:
7858 // Prod = N(k+1) * N(k+2) * ... * Nn;
7859 // Ik = Acc / Prod;
7860 // Acc -= Ik * Prod;
7861 //
7862 ExprResult Acc = IV;
7863 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007864 LoopIterationSpace &IS = IterSpaces[Cnt];
7865 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007866 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007867
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007868 // Compute prod
7869 ExprResult Prod =
7870 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7871 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7872 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7873 IterSpaces[K].NumIterations);
7874
7875 // Iter = Acc / Prod
7876 // If there is at least one more inner loop to avoid
7877 // multiplication by 1.
7878 if (Cnt + 1 < NestedLoopCount)
7879 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7880 Acc.get(), Prod.get());
7881 else
7882 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007883 if (!Iter.isUsable()) {
7884 HasErrors = true;
7885 break;
7886 }
7887
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007888 // Update Acc:
7889 // Acc -= Iter * Prod
7890 // Check if there is at least one more inner loop to avoid
7891 // multiplication by 1.
7892 if (Cnt + 1 < NestedLoopCount)
7893 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7894 Iter.get(), Prod.get());
7895 else
7896 Prod = Iter;
7897 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7898 Acc.get(), Prod.get());
7899
Alexey Bataev39f915b82015-05-08 10:41:21 +00007900 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007901 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007902 DeclRefExpr *CounterVar = buildDeclRefExpr(
7903 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7904 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007905 ExprResult Init =
7906 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7907 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007908 if (!Init.isUsable()) {
7909 HasErrors = true;
7910 break;
7911 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007912 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007913 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007914 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007915 if (!Update.isUsable()) {
7916 HasErrors = true;
7917 break;
7918 }
7919
7920 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007921 ExprResult Final =
7922 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7923 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7924 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007925 if (!Final.isUsable()) {
7926 HasErrors = true;
7927 break;
7928 }
7929
Alexander Musmana5f070a2014-10-01 06:03:56 +00007930 if (!Update.isUsable() || !Final.isUsable()) {
7931 HasErrors = true;
7932 break;
7933 }
7934 // Save results
7935 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007936 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007937 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007938 Built.Updates[Cnt] = Update.get();
7939 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007940 Built.DependentCounters[Cnt] = nullptr;
7941 Built.DependentInits[Cnt] = nullptr;
7942 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007943 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007944 Built.DependentCounters[Cnt] =
7945 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7946 Built.DependentInits[Cnt] =
7947 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7948 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7949 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007950 }
7951 }
7952
7953 if (HasErrors)
7954 return 0;
7955
7956 // Save results
7957 Built.IterationVarRef = IV.get();
7958 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007959 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007960 Built.CalcLastIteration = SemaRef
7961 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007962 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007963 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007964 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007965 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007966 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007967 Built.Init = Init.get();
7968 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007969 Built.LB = LB.get();
7970 Built.UB = UB.get();
7971 Built.IL = IL.get();
7972 Built.ST = ST.get();
7973 Built.EUB = EUB.get();
7974 Built.NLB = NextLB.get();
7975 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007976 Built.PrevLB = PrevLB.get();
7977 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007978 Built.DistInc = DistInc.get();
7979 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007980 Built.DistCombinedFields.LB = CombLB.get();
7981 Built.DistCombinedFields.UB = CombUB.get();
7982 Built.DistCombinedFields.EUB = CombEUB.get();
7983 Built.DistCombinedFields.Init = CombInit.get();
7984 Built.DistCombinedFields.Cond = CombCond.get();
7985 Built.DistCombinedFields.NLB = CombNextLB.get();
7986 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007987 Built.DistCombinedFields.DistCond = CombDistCond.get();
7988 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007989
Alexey Bataevabfc0692014-06-25 06:52:00 +00007990 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007991}
7992
Alexey Bataev10e775f2015-07-30 11:36:16 +00007993static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007994 auto CollapseClauses =
7995 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7996 if (CollapseClauses.begin() != CollapseClauses.end())
7997 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007998 return nullptr;
7999}
8000
Alexey Bataev10e775f2015-07-30 11:36:16 +00008001static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008002 auto OrderedClauses =
8003 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8004 if (OrderedClauses.begin() != OrderedClauses.end())
8005 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00008006 return nullptr;
8007}
8008
Kelvin Lic5609492016-07-15 04:39:07 +00008009static bool checkSimdlenSafelenSpecified(Sema &S,
8010 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008011 const OMPSafelenClause *Safelen = nullptr;
8012 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00008013
Alexey Bataeve3727102018-04-18 15:57:46 +00008014 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00008015 if (Clause->getClauseKind() == OMPC_safelen)
8016 Safelen = cast<OMPSafelenClause>(Clause);
8017 else if (Clause->getClauseKind() == OMPC_simdlen)
8018 Simdlen = cast<OMPSimdlenClause>(Clause);
8019 if (Safelen && Simdlen)
8020 break;
8021 }
8022
8023 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008024 const Expr *SimdlenLength = Simdlen->getSimdlen();
8025 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00008026 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8027 SimdlenLength->isInstantiationDependent() ||
8028 SimdlenLength->containsUnexpandedParameterPack())
8029 return false;
8030 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8031 SafelenLength->isInstantiationDependent() ||
8032 SafelenLength->containsUnexpandedParameterPack())
8033 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008034 Expr::EvalResult SimdlenResult, SafelenResult;
8035 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8036 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8037 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8038 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00008039 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8040 // If both simdlen and safelen clauses are specified, the value of the
8041 // simdlen parameter must be less than or equal to the value of the safelen
8042 // parameter.
8043 if (SimdlenRes > SafelenRes) {
8044 S.Diag(SimdlenLength->getExprLoc(),
8045 diag::err_omp_wrong_simdlen_safelen_values)
8046 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8047 return true;
8048 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00008049 }
8050 return false;
8051}
8052
Alexey Bataeve3727102018-04-18 15:57:46 +00008053StmtResult
8054Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8055 SourceLocation StartLoc, SourceLocation EndLoc,
8056 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008057 if (!AStmt)
8058 return StmtError();
8059
8060 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008061 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008062 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8063 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008064 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008065 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8066 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008067 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008068 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008069
Alexander Musmana5f070a2014-10-01 06:03:56 +00008070 assert((CurContext->isDependentContext() || B.builtAll()) &&
8071 "omp simd loop exprs were not built");
8072
Alexander Musman3276a272015-03-21 10:12:56 +00008073 if (!CurContext->isDependentContext()) {
8074 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008075 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008076 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00008077 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008078 B.NumIterations, *this, CurScope,
8079 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00008080 return StmtError();
8081 }
8082 }
8083
Kelvin Lic5609492016-07-15 04:39:07 +00008084 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008085 return StmtError();
8086
Reid Kleckner87a31802018-03-12 21:43:02 +00008087 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008088 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8089 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008090}
8091
Alexey Bataeve3727102018-04-18 15:57:46 +00008092StmtResult
8093Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8094 SourceLocation StartLoc, SourceLocation EndLoc,
8095 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008096 if (!AStmt)
8097 return StmtError();
8098
8099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008100 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008101 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8102 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008103 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008104 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8105 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008106 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008107 return StmtError();
8108
Alexander Musmana5f070a2014-10-01 06:03:56 +00008109 assert((CurContext->isDependentContext() || B.builtAll()) &&
8110 "omp for loop exprs were not built");
8111
Alexey Bataev54acd402015-08-04 11:18:19 +00008112 if (!CurContext->isDependentContext()) {
8113 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008114 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008115 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008116 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008117 B.NumIterations, *this, CurScope,
8118 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008119 return StmtError();
8120 }
8121 }
8122
Reid Kleckner87a31802018-03-12 21:43:02 +00008123 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008124 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008125 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008126}
8127
Alexander Musmanf82886e2014-09-18 05:12:34 +00008128StmtResult Sema::ActOnOpenMPForSimdDirective(
8129 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008130 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008131 if (!AStmt)
8132 return StmtError();
8133
8134 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008135 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008136 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8137 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008138 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008139 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008140 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8141 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008142 if (NestedLoopCount == 0)
8143 return StmtError();
8144
Alexander Musmanc6388682014-12-15 07:07:06 +00008145 assert((CurContext->isDependentContext() || B.builtAll()) &&
8146 "omp for simd loop exprs were not built");
8147
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008148 if (!CurContext->isDependentContext()) {
8149 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008150 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008151 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008152 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008153 B.NumIterations, *this, CurScope,
8154 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008155 return StmtError();
8156 }
8157 }
8158
Kelvin Lic5609492016-07-15 04:39:07 +00008159 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008160 return StmtError();
8161
Reid Kleckner87a31802018-03-12 21:43:02 +00008162 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008163 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8164 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008165}
8166
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008167StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8168 Stmt *AStmt,
8169 SourceLocation StartLoc,
8170 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008171 if (!AStmt)
8172 return StmtError();
8173
8174 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008175 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008176 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008177 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008178 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008179 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008180 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008181 return StmtError();
8182 // All associated statements must be '#pragma omp section' except for
8183 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008184 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008185 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8186 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008187 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008188 diag::err_omp_sections_substmt_not_section);
8189 return StmtError();
8190 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008191 cast<OMPSectionDirective>(SectionStmt)
8192 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008193 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008194 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008195 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008196 return StmtError();
8197 }
8198
Reid Kleckner87a31802018-03-12 21:43:02 +00008199 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008200
Alexey Bataev25e5b442015-09-15 12:52:43 +00008201 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8202 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008203}
8204
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008205StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8206 SourceLocation StartLoc,
8207 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008208 if (!AStmt)
8209 return StmtError();
8210
8211 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008212
Reid Kleckner87a31802018-03-12 21:43:02 +00008213 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008214 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008215
Alexey Bataev25e5b442015-09-15 12:52:43 +00008216 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8217 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008218}
8219
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008220StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8221 Stmt *AStmt,
8222 SourceLocation StartLoc,
8223 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008224 if (!AStmt)
8225 return StmtError();
8226
8227 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008228
Reid Kleckner87a31802018-03-12 21:43:02 +00008229 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008230
Alexey Bataev3255bf32015-01-19 05:20:46 +00008231 // OpenMP [2.7.3, single Construct, Restrictions]
8232 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008233 const OMPClause *Nowait = nullptr;
8234 const OMPClause *Copyprivate = nullptr;
8235 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008236 if (Clause->getClauseKind() == OMPC_nowait)
8237 Nowait = Clause;
8238 else if (Clause->getClauseKind() == OMPC_copyprivate)
8239 Copyprivate = Clause;
8240 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008241 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008242 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008243 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008244 return StmtError();
8245 }
8246 }
8247
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008248 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8249}
8250
Alexander Musman80c22892014-07-17 08:54:58 +00008251StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8252 SourceLocation StartLoc,
8253 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008254 if (!AStmt)
8255 return StmtError();
8256
8257 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008258
Reid Kleckner87a31802018-03-12 21:43:02 +00008259 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008260
8261 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8262}
8263
Alexey Bataev28c75412015-12-15 08:19:24 +00008264StmtResult Sema::ActOnOpenMPCriticalDirective(
8265 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8266 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008267 if (!AStmt)
8268 return StmtError();
8269
8270 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008271
Alexey Bataev28c75412015-12-15 08:19:24 +00008272 bool ErrorFound = false;
8273 llvm::APSInt Hint;
8274 SourceLocation HintLoc;
8275 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008276 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008277 if (C->getClauseKind() == OMPC_hint) {
8278 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008279 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008280 ErrorFound = true;
8281 }
8282 Expr *E = cast<OMPHintClause>(C)->getHint();
8283 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008284 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008285 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008286 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008287 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008288 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008289 }
8290 }
8291 }
8292 if (ErrorFound)
8293 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008294 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008295 if (Pair.first && DirName.getName() && !DependentHint) {
8296 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8297 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008298 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008299 Diag(HintLoc, diag::note_omp_critical_hint_here)
8300 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008301 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008302 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008303 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008304 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008305 << 1
8306 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8307 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008308 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008309 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008310 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008311 }
8312 }
8313
Reid Kleckner87a31802018-03-12 21:43:02 +00008314 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008315
Alexey Bataev28c75412015-12-15 08:19:24 +00008316 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8317 Clauses, AStmt);
8318 if (!Pair.first && DirName.getName() && !DependentHint)
8319 DSAStack->addCriticalWithHint(Dir, Hint);
8320 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008321}
8322
Alexey Bataev4acb8592014-07-07 13:01:15 +00008323StmtResult Sema::ActOnOpenMPParallelForDirective(
8324 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008325 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008326 if (!AStmt)
8327 return StmtError();
8328
Alexey Bataeve3727102018-04-18 15:57:46 +00008329 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008330 // 1.2.2 OpenMP Language Terminology
8331 // Structured block - An executable statement with a single entry at the
8332 // top and a single exit at the bottom.
8333 // The point of exit cannot be a branch out of the structured block.
8334 // longjmp() and throw() must not violate the entry/exit criteria.
8335 CS->getCapturedDecl()->setNothrow();
8336
Alexander Musmanc6388682014-12-15 07:07:06 +00008337 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8339 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008340 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008342 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8343 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008344 if (NestedLoopCount == 0)
8345 return StmtError();
8346
Alexander Musmana5f070a2014-10-01 06:03:56 +00008347 assert((CurContext->isDependentContext() || B.builtAll()) &&
8348 "omp parallel for loop exprs were not built");
8349
Alexey Bataev54acd402015-08-04 11:18:19 +00008350 if (!CurContext->isDependentContext()) {
8351 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008352 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008353 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008354 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008355 B.NumIterations, *this, CurScope,
8356 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008357 return StmtError();
8358 }
8359 }
8360
Reid Kleckner87a31802018-03-12 21:43:02 +00008361 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008362 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008363 NestedLoopCount, Clauses, AStmt, B,
8364 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008365}
8366
Alexander Musmane4e893b2014-09-23 09:33:00 +00008367StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8368 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008369 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008370 if (!AStmt)
8371 return StmtError();
8372
Alexey Bataeve3727102018-04-18 15:57:46 +00008373 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008374 // 1.2.2 OpenMP Language Terminology
8375 // Structured block - An executable statement with a single entry at the
8376 // top and a single exit at the bottom.
8377 // The point of exit cannot be a branch out of the structured block.
8378 // longjmp() and throw() must not violate the entry/exit criteria.
8379 CS->getCapturedDecl()->setNothrow();
8380
Alexander Musmanc6388682014-12-15 07:07:06 +00008381 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008382 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8383 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008384 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008385 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008386 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8387 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008388 if (NestedLoopCount == 0)
8389 return StmtError();
8390
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008391 if (!CurContext->isDependentContext()) {
8392 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008393 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008394 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008395 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008396 B.NumIterations, *this, CurScope,
8397 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008398 return StmtError();
8399 }
8400 }
8401
Kelvin Lic5609492016-07-15 04:39:07 +00008402 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008403 return StmtError();
8404
Reid Kleckner87a31802018-03-12 21:43:02 +00008405 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008406 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008407 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008408}
8409
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008410StmtResult
cchen47d60942019-12-05 13:43:48 -05008411Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8412 Stmt *AStmt, SourceLocation StartLoc,
8413 SourceLocation EndLoc) {
8414 if (!AStmt)
8415 return StmtError();
8416
8417 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8418 auto *CS = cast<CapturedStmt>(AStmt);
8419 // 1.2.2 OpenMP Language Terminology
8420 // Structured block - An executable statement with a single entry at the
8421 // top and a single exit at the bottom.
8422 // The point of exit cannot be a branch out of the structured block.
8423 // longjmp() and throw() must not violate the entry/exit criteria.
8424 CS->getCapturedDecl()->setNothrow();
8425
8426 setFunctionHasBranchProtectedScope();
8427
8428 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8429 AStmt);
8430}
8431
8432StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008433Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8434 Stmt *AStmt, SourceLocation StartLoc,
8435 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008436 if (!AStmt)
8437 return StmtError();
8438
8439 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008440 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008441 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008442 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008443 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008444 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008445 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008446 return StmtError();
8447 // All associated statements must be '#pragma omp section' except for
8448 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008449 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008450 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8451 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008452 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008453 diag::err_omp_parallel_sections_substmt_not_section);
8454 return StmtError();
8455 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008456 cast<OMPSectionDirective>(SectionStmt)
8457 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008458 }
8459 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008460 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008461 diag::err_omp_parallel_sections_not_compound_stmt);
8462 return StmtError();
8463 }
8464
Reid Kleckner87a31802018-03-12 21:43:02 +00008465 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008466
Alexey Bataev25e5b442015-09-15 12:52:43 +00008467 return OMPParallelSectionsDirective::Create(
8468 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008469}
8470
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008471StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8472 Stmt *AStmt, SourceLocation StartLoc,
8473 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008474 if (!AStmt)
8475 return StmtError();
8476
David Majnemer9d168222016-08-05 17:44:54 +00008477 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008478 // 1.2.2 OpenMP Language Terminology
8479 // Structured block - An executable statement with a single entry at the
8480 // top and a single exit at the bottom.
8481 // The point of exit cannot be a branch out of the structured block.
8482 // longjmp() and throw() must not violate the entry/exit criteria.
8483 CS->getCapturedDecl()->setNothrow();
8484
Reid Kleckner87a31802018-03-12 21:43:02 +00008485 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008486
Alexey Bataev25e5b442015-09-15 12:52:43 +00008487 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8488 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008489}
8490
Alexey Bataev68446b72014-07-18 07:47:19 +00008491StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8492 SourceLocation EndLoc) {
8493 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8494}
8495
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008496StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8497 SourceLocation EndLoc) {
8498 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8499}
8500
Alexey Bataev2df347a2014-07-18 10:17:07 +00008501StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8502 SourceLocation EndLoc) {
8503 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8504}
8505
Alexey Bataev169d96a2017-07-18 20:17:46 +00008506StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8507 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008508 SourceLocation StartLoc,
8509 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008510 if (!AStmt)
8511 return StmtError();
8512
8513 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008514
Reid Kleckner87a31802018-03-12 21:43:02 +00008515 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008516
Alexey Bataev169d96a2017-07-18 20:17:46 +00008517 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008518 AStmt,
8519 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008520}
8521
Alexey Bataev6125da92014-07-21 11:26:11 +00008522StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8523 SourceLocation StartLoc,
8524 SourceLocation EndLoc) {
8525 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8526 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8527}
8528
Alexey Bataev346265e2015-09-25 10:37:12 +00008529StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8530 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008531 SourceLocation StartLoc,
8532 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008533 const OMPClause *DependFound = nullptr;
8534 const OMPClause *DependSourceClause = nullptr;
8535 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008536 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008537 const OMPThreadsClause *TC = nullptr;
8538 const OMPSIMDClause *SC = nullptr;
8539 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008540 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8541 DependFound = C;
8542 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8543 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008544 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008545 << getOpenMPDirectiveName(OMPD_ordered)
8546 << getOpenMPClauseName(OMPC_depend) << 2;
8547 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008548 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008549 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008550 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008551 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008552 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008553 << 0;
8554 ErrorFound = true;
8555 }
8556 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8557 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008558 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008559 << 1;
8560 ErrorFound = true;
8561 }
8562 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008563 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008564 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008565 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008566 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008567 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008568 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008569 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008570 if (!ErrorFound && !SC &&
8571 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008572 // OpenMP [2.8.1,simd Construct, Restrictions]
8573 // An ordered construct with the simd clause is the only OpenMP construct
8574 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008575 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8576 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008577 ErrorFound = true;
8578 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008579 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008580 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8581 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008582 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008583 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008584 diag::err_omp_ordered_directive_without_param);
8585 ErrorFound = true;
8586 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008587 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008588 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008589 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8590 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008591 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008592 ErrorFound = true;
8593 }
8594 }
8595 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008596 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008597
8598 if (AStmt) {
8599 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8600
Reid Kleckner87a31802018-03-12 21:43:02 +00008601 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008602 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008603
8604 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008605}
8606
Alexey Bataev1d160b12015-03-13 12:27:31 +00008607namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008608/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008609/// construct.
8610class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008611 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008612 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008613 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008614 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008615 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008616 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008617 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008618 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008619 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008620 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008621 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008622 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008623 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008624 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008625 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008626 /// expression.
8627 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008628 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008629 /// part.
8630 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008631 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008632 NoError
8633 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008634 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008635 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008636 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008637 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008638 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008639 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008640 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008641 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008642 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008643 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8644 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8645 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008646 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008647 /// important for non-associative operations.
8648 bool IsXLHSInRHSPart;
8649 BinaryOperatorKind Op;
8650 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008651 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008652 /// if it is a prefix unary operation.
8653 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008654
8655public:
8656 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008657 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008658 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008659 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008660 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008661 /// expression. If DiagId and NoteId == 0, then only check is performed
8662 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008663 /// \param DiagId Diagnostic which should be emitted if error is found.
8664 /// \param NoteId Diagnostic note for the main error message.
8665 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008666 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008667 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008668 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008669 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008670 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008671 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008672 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8673 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8674 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008675 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008676 /// false otherwise.
8677 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008679 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008680 /// if it is a prefix unary operation.
8681 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8682
Alexey Bataev1d160b12015-03-13 12:27:31 +00008683private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008684 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8685 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008686};
8687} // namespace
8688
8689bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8690 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8691 ExprAnalysisErrorCode ErrorFound = NoError;
8692 SourceLocation ErrorLoc, NoteLoc;
8693 SourceRange ErrorRange, NoteRange;
8694 // Allowed constructs are:
8695 // x = x binop expr;
8696 // x = expr binop x;
8697 if (AtomicBinOp->getOpcode() == BO_Assign) {
8698 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008699 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008700 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8701 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8702 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8703 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008704 Op = AtomicInnerBinOp->getOpcode();
8705 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008706 Expr *LHS = AtomicInnerBinOp->getLHS();
8707 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008708 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8709 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8710 /*Canonical=*/true);
8711 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8712 /*Canonical=*/true);
8713 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8714 /*Canonical=*/true);
8715 if (XId == LHSId) {
8716 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008717 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008718 } else if (XId == RHSId) {
8719 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008720 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008721 } else {
8722 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8723 ErrorRange = AtomicInnerBinOp->getSourceRange();
8724 NoteLoc = X->getExprLoc();
8725 NoteRange = X->getSourceRange();
8726 ErrorFound = NotAnUpdateExpression;
8727 }
8728 } else {
8729 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8730 ErrorRange = AtomicInnerBinOp->getSourceRange();
8731 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8732 NoteRange = SourceRange(NoteLoc, NoteLoc);
8733 ErrorFound = NotABinaryOperator;
8734 }
8735 } else {
8736 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8737 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8738 ErrorFound = NotABinaryExpression;
8739 }
8740 } else {
8741 ErrorLoc = AtomicBinOp->getExprLoc();
8742 ErrorRange = AtomicBinOp->getSourceRange();
8743 NoteLoc = AtomicBinOp->getOperatorLoc();
8744 NoteRange = SourceRange(NoteLoc, NoteLoc);
8745 ErrorFound = NotAnAssignmentOp;
8746 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008747 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008748 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8749 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8750 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008751 }
8752 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008753 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008754 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008755}
8756
8757bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8758 unsigned NoteId) {
8759 ExprAnalysisErrorCode ErrorFound = NoError;
8760 SourceLocation ErrorLoc, NoteLoc;
8761 SourceRange ErrorRange, NoteRange;
8762 // Allowed constructs are:
8763 // x++;
8764 // x--;
8765 // ++x;
8766 // --x;
8767 // x binop= expr;
8768 // x = x binop expr;
8769 // x = expr binop x;
8770 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8771 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8772 if (AtomicBody->getType()->isScalarType() ||
8773 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008774 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008775 AtomicBody->IgnoreParenImpCasts())) {
8776 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008777 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008778 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008779 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008780 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008781 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008782 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008783 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8784 AtomicBody->IgnoreParenImpCasts())) {
8785 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008786 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008787 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008788 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008789 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008790 // Check for Unary Operation
8791 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008792 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008793 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8794 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008795 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008796 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8797 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008798 } else {
8799 ErrorFound = NotAnUnaryIncDecExpression;
8800 ErrorLoc = AtomicUnaryOp->getExprLoc();
8801 ErrorRange = AtomicUnaryOp->getSourceRange();
8802 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8803 NoteRange = SourceRange(NoteLoc, NoteLoc);
8804 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008805 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008806 ErrorFound = NotABinaryOrUnaryExpression;
8807 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8808 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8809 }
8810 } else {
8811 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008812 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008813 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8814 }
8815 } else {
8816 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008817 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008818 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8819 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008820 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008821 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8822 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8823 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008824 }
8825 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008826 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008827 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008828 // Build an update expression of form 'OpaqueValueExpr(x) binop
8829 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8830 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8831 auto *OVEX = new (SemaRef.getASTContext())
8832 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8833 auto *OVEExpr = new (SemaRef.getASTContext())
8834 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008835 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008836 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8837 IsXLHSInRHSPart ? OVEExpr : OVEX);
8838 if (Update.isInvalid())
8839 return true;
8840 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8841 Sema::AA_Casting);
8842 if (Update.isInvalid())
8843 return true;
8844 UpdateExpr = Update.get();
8845 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008846 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008847}
8848
Alexey Bataev0162e452014-07-22 10:10:35 +00008849StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8850 Stmt *AStmt,
8851 SourceLocation StartLoc,
8852 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008853 if (!AStmt)
8854 return StmtError();
8855
David Majnemer9d168222016-08-05 17:44:54 +00008856 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008857 // 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.
Alexey Bataevdea47612014-07-23 07:46:59 +00008862 OpenMPClauseKind AtomicKind = OMPC_unknown;
8863 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008864 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008865 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008866 C->getClauseKind() == OMPC_update ||
8867 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008868 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008869 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008870 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008871 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8872 << getOpenMPClauseName(AtomicKind);
8873 } else {
8874 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008875 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008876 }
8877 }
8878 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008879
Alexey Bataeve3727102018-04-18 15:57:46 +00008880 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008881 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8882 Body = EWC->getSubExpr();
8883
Alexey Bataev62cec442014-11-18 10:14:22 +00008884 Expr *X = nullptr;
8885 Expr *V = nullptr;
8886 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008887 Expr *UE = nullptr;
8888 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008889 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008890 // OpenMP [2.12.6, atomic Construct]
8891 // In the next expressions:
8892 // * x and v (as applicable) are both l-value expressions with scalar type.
8893 // * During the execution of an atomic region, multiple syntactic
8894 // occurrences of x must designate the same storage location.
8895 // * Neither of v and expr (as applicable) may access the storage location
8896 // designated by x.
8897 // * Neither of x and expr (as applicable) may access the storage location
8898 // designated by v.
8899 // * expr is an expression with scalar type.
8900 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8901 // * binop, binop=, ++, and -- are not overloaded operators.
8902 // * The expression x binop expr must be numerically equivalent to x binop
8903 // (expr). This requirement is satisfied if the operators in expr have
8904 // precedence greater than binop, or by using parentheses around expr or
8905 // subexpressions of expr.
8906 // * The expression expr binop x must be numerically equivalent to (expr)
8907 // binop x. This requirement is satisfied if the operators in expr have
8908 // precedence equal to or greater than binop, or by using parentheses around
8909 // expr or subexpressions of expr.
8910 // * For forms that allow multiple occurrences of x, the number of times
8911 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008912 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008913 enum {
8914 NotAnExpression,
8915 NotAnAssignmentOp,
8916 NotAScalarType,
8917 NotAnLValue,
8918 NoError
8919 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008920 SourceLocation ErrorLoc, NoteLoc;
8921 SourceRange ErrorRange, NoteRange;
8922 // If clause is read:
8923 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008924 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8925 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008926 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8927 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8928 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8929 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8930 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8931 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8932 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008933 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008934 ErrorFound = NotAnLValue;
8935 ErrorLoc = AtomicBinOp->getExprLoc();
8936 ErrorRange = AtomicBinOp->getSourceRange();
8937 NoteLoc = NotLValueExpr->getExprLoc();
8938 NoteRange = NotLValueExpr->getSourceRange();
8939 }
8940 } else if (!X->isInstantiationDependent() ||
8941 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008942 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008943 (X->isInstantiationDependent() || X->getType()->isScalarType())
8944 ? V
8945 : X;
8946 ErrorFound = NotAScalarType;
8947 ErrorLoc = AtomicBinOp->getExprLoc();
8948 ErrorRange = AtomicBinOp->getSourceRange();
8949 NoteLoc = NotScalarExpr->getExprLoc();
8950 NoteRange = NotScalarExpr->getSourceRange();
8951 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008952 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008953 ErrorFound = NotAnAssignmentOp;
8954 ErrorLoc = AtomicBody->getExprLoc();
8955 ErrorRange = AtomicBody->getSourceRange();
8956 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8957 : AtomicBody->getExprLoc();
8958 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8959 : AtomicBody->getSourceRange();
8960 }
8961 } else {
8962 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008963 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008964 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008965 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008966 if (ErrorFound != NoError) {
8967 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8968 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008969 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8970 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008971 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008972 }
8973 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008974 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008975 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008976 enum {
8977 NotAnExpression,
8978 NotAnAssignmentOp,
8979 NotAScalarType,
8980 NotAnLValue,
8981 NoError
8982 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008983 SourceLocation ErrorLoc, NoteLoc;
8984 SourceRange ErrorRange, NoteRange;
8985 // If clause is write:
8986 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008987 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8988 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008989 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8990 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008991 X = AtomicBinOp->getLHS();
8992 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008993 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8994 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8995 if (!X->isLValue()) {
8996 ErrorFound = NotAnLValue;
8997 ErrorLoc = AtomicBinOp->getExprLoc();
8998 ErrorRange = AtomicBinOp->getSourceRange();
8999 NoteLoc = X->getExprLoc();
9000 NoteRange = X->getSourceRange();
9001 }
9002 } else if (!X->isInstantiationDependent() ||
9003 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009004 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009005 (X->isInstantiationDependent() || X->getType()->isScalarType())
9006 ? E
9007 : X;
9008 ErrorFound = NotAScalarType;
9009 ErrorLoc = AtomicBinOp->getExprLoc();
9010 ErrorRange = AtomicBinOp->getSourceRange();
9011 NoteLoc = NotScalarExpr->getExprLoc();
9012 NoteRange = NotScalarExpr->getSourceRange();
9013 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009014 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00009015 ErrorFound = NotAnAssignmentOp;
9016 ErrorLoc = AtomicBody->getExprLoc();
9017 ErrorRange = AtomicBody->getSourceRange();
9018 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9019 : AtomicBody->getExprLoc();
9020 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9021 : AtomicBody->getSourceRange();
9022 }
9023 } else {
9024 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009025 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009026 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009027 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00009028 if (ErrorFound != NoError) {
9029 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9030 << ErrorRange;
9031 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9032 << NoteRange;
9033 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009034 }
9035 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00009036 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009037 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00009038 // If clause is update:
9039 // x++;
9040 // x--;
9041 // ++x;
9042 // --x;
9043 // x binop= expr;
9044 // x = x binop expr;
9045 // x = expr binop x;
9046 OpenMPAtomicUpdateChecker Checker(*this);
9047 if (Checker.checkStatement(
9048 Body, (AtomicKind == OMPC_update)
9049 ? diag::err_omp_atomic_update_not_expression_statement
9050 : diag::err_omp_atomic_not_expression_statement,
9051 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00009052 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00009053 if (!CurContext->isDependentContext()) {
9054 E = Checker.getExpr();
9055 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00009056 UE = Checker.getUpdateExpr();
9057 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00009058 }
Alexey Bataev459dec02014-07-24 06:46:57 +00009059 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009060 enum {
9061 NotAnAssignmentOp,
9062 NotACompoundStatement,
9063 NotTwoSubstatements,
9064 NotASpecificExpression,
9065 NoError
9066 } ErrorFound = NoError;
9067 SourceLocation ErrorLoc, NoteLoc;
9068 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009069 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009070 // If clause is a capture:
9071 // v = x++;
9072 // v = x--;
9073 // v = ++x;
9074 // v = --x;
9075 // v = x binop= expr;
9076 // v = x = x binop expr;
9077 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009078 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00009079 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9080 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9081 V = AtomicBinOp->getLHS();
9082 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9083 OpenMPAtomicUpdateChecker Checker(*this);
9084 if (Checker.checkStatement(
9085 Body, diag::err_omp_atomic_capture_not_expression_statement,
9086 diag::note_omp_atomic_update))
9087 return StmtError();
9088 E = Checker.getExpr();
9089 X = Checker.getX();
9090 UE = Checker.getUpdateExpr();
9091 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9092 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009093 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009094 ErrorLoc = AtomicBody->getExprLoc();
9095 ErrorRange = AtomicBody->getSourceRange();
9096 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9097 : AtomicBody->getExprLoc();
9098 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9099 : AtomicBody->getSourceRange();
9100 ErrorFound = NotAnAssignmentOp;
9101 }
9102 if (ErrorFound != NoError) {
9103 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9104 << ErrorRange;
9105 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9106 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009107 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009108 if (CurContext->isDependentContext())
9109 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009110 } else {
9111 // If clause is a capture:
9112 // { v = x; x = expr; }
9113 // { v = x; x++; }
9114 // { v = x; x--; }
9115 // { v = x; ++x; }
9116 // { v = x; --x; }
9117 // { v = x; x binop= expr; }
9118 // { v = x; x = x binop expr; }
9119 // { v = x; x = expr binop x; }
9120 // { x++; v = x; }
9121 // { x--; v = x; }
9122 // { ++x; v = x; }
9123 // { --x; v = x; }
9124 // { x binop= expr; v = x; }
9125 // { x = x binop expr; v = x; }
9126 // { x = expr binop x; v = x; }
9127 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9128 // Check that this is { expr1; expr2; }
9129 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009130 Stmt *First = CS->body_front();
9131 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009132 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9133 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9134 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9135 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9136 // Need to find what subexpression is 'v' and what is 'x'.
9137 OpenMPAtomicUpdateChecker Checker(*this);
9138 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9139 BinaryOperator *BinOp = nullptr;
9140 if (IsUpdateExprFound) {
9141 BinOp = dyn_cast<BinaryOperator>(First);
9142 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9143 }
9144 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9145 // { v = x; x++; }
9146 // { v = x; x--; }
9147 // { v = x; ++x; }
9148 // { v = x; --x; }
9149 // { v = x; x binop= expr; }
9150 // { v = x; x = x binop expr; }
9151 // { v = x; x = expr binop x; }
9152 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009153 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009154 llvm::FoldingSetNodeID XId, PossibleXId;
9155 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9156 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9157 IsUpdateExprFound = XId == PossibleXId;
9158 if (IsUpdateExprFound) {
9159 V = BinOp->getLHS();
9160 X = Checker.getX();
9161 E = Checker.getExpr();
9162 UE = Checker.getUpdateExpr();
9163 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009164 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009165 }
9166 }
9167 if (!IsUpdateExprFound) {
9168 IsUpdateExprFound = !Checker.checkStatement(First);
9169 BinOp = nullptr;
9170 if (IsUpdateExprFound) {
9171 BinOp = dyn_cast<BinaryOperator>(Second);
9172 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9173 }
9174 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9175 // { x++; v = x; }
9176 // { x--; v = x; }
9177 // { ++x; v = x; }
9178 // { --x; v = x; }
9179 // { x binop= expr; v = x; }
9180 // { x = x binop expr; v = x; }
9181 // { x = expr binop x; v = x; }
9182 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009183 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009184 llvm::FoldingSetNodeID XId, PossibleXId;
9185 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9186 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9187 IsUpdateExprFound = XId == PossibleXId;
9188 if (IsUpdateExprFound) {
9189 V = BinOp->getLHS();
9190 X = Checker.getX();
9191 E = Checker.getExpr();
9192 UE = Checker.getUpdateExpr();
9193 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009194 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009195 }
9196 }
9197 }
9198 if (!IsUpdateExprFound) {
9199 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009200 auto *FirstExpr = dyn_cast<Expr>(First);
9201 auto *SecondExpr = dyn_cast<Expr>(Second);
9202 if (!FirstExpr || !SecondExpr ||
9203 !(FirstExpr->isInstantiationDependent() ||
9204 SecondExpr->isInstantiationDependent())) {
9205 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9206 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009207 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009208 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009209 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009210 NoteRange = ErrorRange = FirstBinOp
9211 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009212 : SourceRange(ErrorLoc, ErrorLoc);
9213 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009214 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9215 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9216 ErrorFound = NotAnAssignmentOp;
9217 NoteLoc = ErrorLoc = SecondBinOp
9218 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009219 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009220 NoteRange = ErrorRange =
9221 SecondBinOp ? SecondBinOp->getSourceRange()
9222 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009223 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009224 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009225 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009226 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009227 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9228 llvm::FoldingSetNodeID X1Id, X2Id;
9229 PossibleXRHSInFirst->Profile(X1Id, Context,
9230 /*Canonical=*/true);
9231 PossibleXLHSInSecond->Profile(X2Id, Context,
9232 /*Canonical=*/true);
9233 IsUpdateExprFound = X1Id == X2Id;
9234 if (IsUpdateExprFound) {
9235 V = FirstBinOp->getLHS();
9236 X = SecondBinOp->getLHS();
9237 E = SecondBinOp->getRHS();
9238 UE = nullptr;
9239 IsXLHSInRHSPart = false;
9240 IsPostfixUpdate = true;
9241 } else {
9242 ErrorFound = NotASpecificExpression;
9243 ErrorLoc = FirstBinOp->getExprLoc();
9244 ErrorRange = FirstBinOp->getSourceRange();
9245 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9246 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9247 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009248 }
9249 }
9250 }
9251 }
9252 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009253 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009254 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009255 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009256 ErrorFound = NotTwoSubstatements;
9257 }
9258 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009259 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009260 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009261 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009262 ErrorFound = NotACompoundStatement;
9263 }
9264 if (ErrorFound != NoError) {
9265 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9266 << ErrorRange;
9267 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9268 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009269 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009270 if (CurContext->isDependentContext())
9271 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009272 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009273 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009274
Reid Kleckner87a31802018-03-12 21:43:02 +00009275 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009276
Alexey Bataev62cec442014-11-18 10:14:22 +00009277 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009278 X, V, E, UE, IsXLHSInRHSPart,
9279 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009280}
9281
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009282StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9283 Stmt *AStmt,
9284 SourceLocation StartLoc,
9285 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009286 if (!AStmt)
9287 return StmtError();
9288
Alexey Bataeve3727102018-04-18 15:57:46 +00009289 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009290 // 1.2.2 OpenMP Language Terminology
9291 // Structured block - An executable statement with a single entry at the
9292 // top and a single exit at the bottom.
9293 // The point of exit cannot be a branch out of the structured block.
9294 // longjmp() and throw() must not violate the entry/exit criteria.
9295 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009296 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9297 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9298 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9299 // 1.2.2 OpenMP Language Terminology
9300 // Structured block - An executable statement with a single entry at the
9301 // top and a single exit at the bottom.
9302 // The point of exit cannot be a branch out of the structured block.
9303 // longjmp() and throw() must not violate the entry/exit criteria.
9304 CS->getCapturedDecl()->setNothrow();
9305 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009306
Alexey Bataev13314bf2014-10-09 04:18:56 +00009307 // OpenMP [2.16, Nesting of Regions]
9308 // If specified, a teams construct must be contained within a target
9309 // construct. That target construct must contain no statements or directives
9310 // outside of the teams construct.
9311 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009312 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009313 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009314 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009315 auto I = CS->body_begin();
9316 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009317 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009318 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9319 OMPTeamsFound) {
9320
Alexey Bataev13314bf2014-10-09 04:18:56 +00009321 OMPTeamsFound = false;
9322 break;
9323 }
9324 ++I;
9325 }
9326 assert(I != CS->body_end() && "Not found statement");
9327 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009328 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009329 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009330 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009331 }
9332 if (!OMPTeamsFound) {
9333 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9334 Diag(DSAStack->getInnerTeamsRegionLoc(),
9335 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009336 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009337 << isa<OMPExecutableDirective>(S);
9338 return StmtError();
9339 }
9340 }
9341
Reid Kleckner87a31802018-03-12 21:43:02 +00009342 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009343
9344 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9345}
9346
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009347StmtResult
9348Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9349 Stmt *AStmt, SourceLocation StartLoc,
9350 SourceLocation EndLoc) {
9351 if (!AStmt)
9352 return StmtError();
9353
Alexey Bataeve3727102018-04-18 15:57:46 +00009354 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009355 // 1.2.2 OpenMP Language Terminology
9356 // Structured block - An executable statement with a single entry at the
9357 // top and a single exit at the bottom.
9358 // The point of exit cannot be a branch out of the structured block.
9359 // longjmp() and throw() must not violate the entry/exit criteria.
9360 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009361 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9362 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9363 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9364 // 1.2.2 OpenMP Language Terminology
9365 // Structured block - An executable statement with a single entry at the
9366 // top and a single exit at the bottom.
9367 // The point of exit cannot be a branch out of the structured block.
9368 // longjmp() and throw() must not violate the entry/exit criteria.
9369 CS->getCapturedDecl()->setNothrow();
9370 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009371
Reid Kleckner87a31802018-03-12 21:43:02 +00009372 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009373
9374 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9375 AStmt);
9376}
9377
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009378StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9379 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009380 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009381 if (!AStmt)
9382 return StmtError();
9383
Alexey Bataeve3727102018-04-18 15:57:46 +00009384 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009385 // 1.2.2 OpenMP Language Terminology
9386 // Structured block - An executable statement with a single entry at the
9387 // top and a single exit at the bottom.
9388 // The point of exit cannot be a branch out of the structured block.
9389 // longjmp() and throw() must not violate the entry/exit criteria.
9390 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009391 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9392 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9393 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9394 // 1.2.2 OpenMP Language Terminology
9395 // Structured block - An executable statement with a single entry at the
9396 // top and a single exit at the bottom.
9397 // The point of exit cannot be a branch out of the structured block.
9398 // longjmp() and throw() must not violate the entry/exit criteria.
9399 CS->getCapturedDecl()->setNothrow();
9400 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009401
9402 OMPLoopDirective::HelperExprs B;
9403 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9404 // define the nested loops number.
9405 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009406 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009407 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009408 VarsWithImplicitDSA, B);
9409 if (NestedLoopCount == 0)
9410 return StmtError();
9411
9412 assert((CurContext->isDependentContext() || B.builtAll()) &&
9413 "omp target parallel for loop exprs were not built");
9414
9415 if (!CurContext->isDependentContext()) {
9416 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009417 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009418 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009419 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009420 B.NumIterations, *this, CurScope,
9421 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009422 return StmtError();
9423 }
9424 }
9425
Reid Kleckner87a31802018-03-12 21:43:02 +00009426 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009427 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9428 NestedLoopCount, Clauses, AStmt,
9429 B, DSAStack->isCancelRegion());
9430}
9431
Alexey Bataev95b64a92017-05-30 16:00:04 +00009432/// Check for existence of a map clause in the list of clauses.
9433static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9434 const OpenMPClauseKind K) {
9435 return llvm::any_of(
9436 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9437}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009438
Alexey Bataev95b64a92017-05-30 16:00:04 +00009439template <typename... Params>
9440static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9441 const Params... ClauseTypes) {
9442 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009443}
9444
Michael Wong65f367f2015-07-21 13:44:28 +00009445StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9446 Stmt *AStmt,
9447 SourceLocation StartLoc,
9448 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009449 if (!AStmt)
9450 return StmtError();
9451
9452 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9453
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009454 // OpenMP [2.10.1, Restrictions, p. 97]
9455 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009456 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9457 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9458 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009459 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009460 return StmtError();
9461 }
9462
Reid Kleckner87a31802018-03-12 21:43:02 +00009463 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009464
9465 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9466 AStmt);
9467}
9468
Samuel Antaodf67fc42016-01-19 19:15:56 +00009469StmtResult
9470Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9471 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009472 SourceLocation EndLoc, Stmt *AStmt) {
9473 if (!AStmt)
9474 return StmtError();
9475
Alexey Bataeve3727102018-04-18 15:57:46 +00009476 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009477 // 1.2.2 OpenMP Language Terminology
9478 // Structured block - An executable statement with a single entry at the
9479 // top and a single exit at the bottom.
9480 // The point of exit cannot be a branch out of the structured block.
9481 // longjmp() and throw() must not violate the entry/exit criteria.
9482 CS->getCapturedDecl()->setNothrow();
9483 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9484 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9485 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9486 // 1.2.2 OpenMP Language Terminology
9487 // Structured block - An executable statement with a single entry at the
9488 // top and a single exit at the bottom.
9489 // The point of exit cannot be a branch out of the structured block.
9490 // longjmp() and throw() must not violate the entry/exit criteria.
9491 CS->getCapturedDecl()->setNothrow();
9492 }
9493
Samuel Antaodf67fc42016-01-19 19:15:56 +00009494 // OpenMP [2.10.2, Restrictions, p. 99]
9495 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009496 if (!hasClauses(Clauses, OMPC_map)) {
9497 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9498 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009499 return StmtError();
9500 }
9501
Alexey Bataev7828b252017-11-21 17:08:48 +00009502 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9503 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009504}
9505
Samuel Antao72590762016-01-19 20:04:50 +00009506StmtResult
9507Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9508 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009509 SourceLocation EndLoc, Stmt *AStmt) {
9510 if (!AStmt)
9511 return StmtError();
9512
Alexey Bataeve3727102018-04-18 15:57:46 +00009513 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009514 // 1.2.2 OpenMP Language Terminology
9515 // Structured block - An executable statement with a single entry at the
9516 // top and a single exit at the bottom.
9517 // The point of exit cannot be a branch out of the structured block.
9518 // longjmp() and throw() must not violate the entry/exit criteria.
9519 CS->getCapturedDecl()->setNothrow();
9520 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9521 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9522 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9523 // 1.2.2 OpenMP Language Terminology
9524 // Structured block - An executable statement with a single entry at the
9525 // top and a single exit at the bottom.
9526 // The point of exit cannot be a branch out of the structured block.
9527 // longjmp() and throw() must not violate the entry/exit criteria.
9528 CS->getCapturedDecl()->setNothrow();
9529 }
9530
Samuel Antao72590762016-01-19 20:04:50 +00009531 // OpenMP [2.10.3, Restrictions, p. 102]
9532 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009533 if (!hasClauses(Clauses, OMPC_map)) {
9534 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9535 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009536 return StmtError();
9537 }
9538
Alexey Bataev7828b252017-11-21 17:08:48 +00009539 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9540 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009541}
9542
Samuel Antao686c70c2016-05-26 17:30:50 +00009543StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9544 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009545 SourceLocation EndLoc,
9546 Stmt *AStmt) {
9547 if (!AStmt)
9548 return StmtError();
9549
Alexey Bataeve3727102018-04-18 15:57:46 +00009550 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009551 // 1.2.2 OpenMP Language Terminology
9552 // Structured block - An executable statement with a single entry at the
9553 // top and a single exit at the bottom.
9554 // The point of exit cannot be a branch out of the structured block.
9555 // longjmp() and throw() must not violate the entry/exit criteria.
9556 CS->getCapturedDecl()->setNothrow();
9557 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9558 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9559 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9560 // 1.2.2 OpenMP Language Terminology
9561 // Structured block - An executable statement with a single entry at the
9562 // top and a single exit at the bottom.
9563 // The point of exit cannot be a branch out of the structured block.
9564 // longjmp() and throw() must not violate the entry/exit criteria.
9565 CS->getCapturedDecl()->setNothrow();
9566 }
9567
Alexey Bataev95b64a92017-05-30 16:00:04 +00009568 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009569 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9570 return StmtError();
9571 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009572 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9573 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009574}
9575
Alexey Bataev13314bf2014-10-09 04:18:56 +00009576StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9577 Stmt *AStmt, SourceLocation StartLoc,
9578 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009579 if (!AStmt)
9580 return StmtError();
9581
Alexey Bataeve3727102018-04-18 15:57:46 +00009582 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009583 // 1.2.2 OpenMP Language Terminology
9584 // Structured block - An executable statement with a single entry at the
9585 // top and a single exit at the bottom.
9586 // The point of exit cannot be a branch out of the structured block.
9587 // longjmp() and throw() must not violate the entry/exit criteria.
9588 CS->getCapturedDecl()->setNothrow();
9589
Reid Kleckner87a31802018-03-12 21:43:02 +00009590 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009591
Alexey Bataevceabd412017-11-30 18:01:54 +00009592 DSAStack->setParentTeamsRegionLoc(StartLoc);
9593
Alexey Bataev13314bf2014-10-09 04:18:56 +00009594 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9595}
9596
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009597StmtResult
9598Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9599 SourceLocation EndLoc,
9600 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009601 if (DSAStack->isParentNowaitRegion()) {
9602 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9603 return StmtError();
9604 }
9605 if (DSAStack->isParentOrderedRegion()) {
9606 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9607 return StmtError();
9608 }
9609 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9610 CancelRegion);
9611}
9612
Alexey Bataev87933c72015-09-18 08:07:34 +00009613StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9614 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009615 SourceLocation EndLoc,
9616 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009617 if (DSAStack->isParentNowaitRegion()) {
9618 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9619 return StmtError();
9620 }
9621 if (DSAStack->isParentOrderedRegion()) {
9622 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9623 return StmtError();
9624 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009625 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009626 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9627 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009628}
9629
Alexey Bataev382967a2015-12-08 12:06:20 +00009630static bool checkGrainsizeNumTasksClauses(Sema &S,
9631 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009632 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009633 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009634 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009635 if (C->getClauseKind() == OMPC_grainsize ||
9636 C->getClauseKind() == OMPC_num_tasks) {
9637 if (!PrevClause)
9638 PrevClause = C;
9639 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009640 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009641 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9642 << getOpenMPClauseName(C->getClauseKind())
9643 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009644 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009645 diag::note_omp_previous_grainsize_num_tasks)
9646 << getOpenMPClauseName(PrevClause->getClauseKind());
9647 ErrorFound = true;
9648 }
9649 }
9650 }
9651 return ErrorFound;
9652}
9653
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009654static bool checkReductionClauseWithNogroup(Sema &S,
9655 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009656 const OMPClause *ReductionClause = nullptr;
9657 const OMPClause *NogroupClause = nullptr;
9658 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009659 if (C->getClauseKind() == OMPC_reduction) {
9660 ReductionClause = C;
9661 if (NogroupClause)
9662 break;
9663 continue;
9664 }
9665 if (C->getClauseKind() == OMPC_nogroup) {
9666 NogroupClause = C;
9667 if (ReductionClause)
9668 break;
9669 continue;
9670 }
9671 }
9672 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009673 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9674 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009675 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009676 return true;
9677 }
9678 return false;
9679}
9680
Alexey Bataev49f6e782015-12-01 04:18:41 +00009681StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9682 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009683 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009684 if (!AStmt)
9685 return StmtError();
9686
9687 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9688 OMPLoopDirective::HelperExprs B;
9689 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9690 // define the nested loops number.
9691 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009692 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009693 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009694 VarsWithImplicitDSA, B);
9695 if (NestedLoopCount == 0)
9696 return StmtError();
9697
9698 assert((CurContext->isDependentContext() || B.builtAll()) &&
9699 "omp for loop exprs were not built");
9700
Alexey Bataev382967a2015-12-08 12:06:20 +00009701 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9702 // The grainsize clause and num_tasks clause are mutually exclusive and may
9703 // not appear on the same taskloop directive.
9704 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9705 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009706 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9707 // If a reduction clause is present on the taskloop directive, the nogroup
9708 // clause must not be specified.
9709 if (checkReductionClauseWithNogroup(*this, Clauses))
9710 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009711
Reid Kleckner87a31802018-03-12 21:43:02 +00009712 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009713 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9714 NestedLoopCount, Clauses, AStmt, B);
9715}
9716
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009717StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9718 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009719 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009720 if (!AStmt)
9721 return StmtError();
9722
9723 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9724 OMPLoopDirective::HelperExprs B;
9725 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9726 // define the nested loops number.
9727 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009728 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009729 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9730 VarsWithImplicitDSA, B);
9731 if (NestedLoopCount == 0)
9732 return StmtError();
9733
9734 assert((CurContext->isDependentContext() || B.builtAll()) &&
9735 "omp for loop exprs were not built");
9736
Alexey Bataev5a3af132016-03-29 08:58:54 +00009737 if (!CurContext->isDependentContext()) {
9738 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009739 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009740 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009741 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009742 B.NumIterations, *this, CurScope,
9743 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009744 return StmtError();
9745 }
9746 }
9747
Alexey Bataev382967a2015-12-08 12:06:20 +00009748 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9749 // The grainsize clause and num_tasks clause are mutually exclusive and may
9750 // not appear on the same taskloop directive.
9751 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9752 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009753 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9754 // If a reduction clause is present on the taskloop directive, the nogroup
9755 // clause must not be specified.
9756 if (checkReductionClauseWithNogroup(*this, Clauses))
9757 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009758 if (checkSimdlenSafelenSpecified(*this, Clauses))
9759 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009760
Reid Kleckner87a31802018-03-12 21:43:02 +00009761 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009762 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9763 NestedLoopCount, Clauses, AStmt, B);
9764}
9765
Alexey Bataev60e51c42019-10-10 20:13:02 +00009766StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9767 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9768 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9769 if (!AStmt)
9770 return StmtError();
9771
9772 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9773 OMPLoopDirective::HelperExprs B;
9774 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9775 // define the nested loops number.
9776 unsigned NestedLoopCount =
9777 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9778 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9779 VarsWithImplicitDSA, B);
9780 if (NestedLoopCount == 0)
9781 return StmtError();
9782
9783 assert((CurContext->isDependentContext() || B.builtAll()) &&
9784 "omp for loop exprs were not built");
9785
9786 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9787 // The grainsize clause and num_tasks clause are mutually exclusive and may
9788 // not appear on the same taskloop directive.
9789 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9790 return StmtError();
9791 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9792 // If a reduction clause is present on the taskloop directive, the nogroup
9793 // clause must not be specified.
9794 if (checkReductionClauseWithNogroup(*this, Clauses))
9795 return StmtError();
9796
9797 setFunctionHasBranchProtectedScope();
9798 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9799 NestedLoopCount, Clauses, AStmt, B);
9800}
9801
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009802StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9803 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9804 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9805 if (!AStmt)
9806 return StmtError();
9807
9808 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9809 OMPLoopDirective::HelperExprs B;
9810 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9811 // define the nested loops number.
9812 unsigned NestedLoopCount =
9813 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9814 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9815 VarsWithImplicitDSA, B);
9816 if (NestedLoopCount == 0)
9817 return StmtError();
9818
9819 assert((CurContext->isDependentContext() || B.builtAll()) &&
9820 "omp for loop exprs were not built");
9821
9822 if (!CurContext->isDependentContext()) {
9823 // Finalize the clauses that need pre-built expressions for CodeGen.
9824 for (OMPClause *C : Clauses) {
9825 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9826 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9827 B.NumIterations, *this, CurScope,
9828 DSAStack))
9829 return StmtError();
9830 }
9831 }
9832
9833 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9834 // The grainsize clause and num_tasks clause are mutually exclusive and may
9835 // not appear on the same taskloop directive.
9836 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9837 return StmtError();
9838 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9839 // If a reduction clause is present on the taskloop directive, the nogroup
9840 // clause must not be specified.
9841 if (checkReductionClauseWithNogroup(*this, Clauses))
9842 return StmtError();
9843 if (checkSimdlenSafelenSpecified(*this, Clauses))
9844 return StmtError();
9845
9846 setFunctionHasBranchProtectedScope();
9847 return OMPMasterTaskLoopSimdDirective::Create(
9848 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9849}
9850
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009851StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9852 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9853 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9854 if (!AStmt)
9855 return StmtError();
9856
9857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9858 auto *CS = cast<CapturedStmt>(AStmt);
9859 // 1.2.2 OpenMP Language Terminology
9860 // Structured block - An executable statement with a single entry at the
9861 // top and a single exit at the bottom.
9862 // The point of exit cannot be a branch out of the structured block.
9863 // longjmp() and throw() must not violate the entry/exit criteria.
9864 CS->getCapturedDecl()->setNothrow();
9865 for (int ThisCaptureLevel =
9866 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9867 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9868 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9869 // 1.2.2 OpenMP Language Terminology
9870 // Structured block - An executable statement with a single entry at the
9871 // top and a single exit at the bottom.
9872 // The point of exit cannot be a branch out of the structured block.
9873 // longjmp() and throw() must not violate the entry/exit criteria.
9874 CS->getCapturedDecl()->setNothrow();
9875 }
9876
9877 OMPLoopDirective::HelperExprs B;
9878 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9879 // define the nested loops number.
9880 unsigned NestedLoopCount = checkOpenMPLoop(
9881 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9882 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9883 VarsWithImplicitDSA, B);
9884 if (NestedLoopCount == 0)
9885 return StmtError();
9886
9887 assert((CurContext->isDependentContext() || B.builtAll()) &&
9888 "omp for loop exprs were not built");
9889
9890 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9891 // The grainsize clause and num_tasks clause are mutually exclusive and may
9892 // not appear on the same taskloop directive.
9893 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9894 return StmtError();
9895 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9896 // If a reduction clause is present on the taskloop directive, the nogroup
9897 // clause must not be specified.
9898 if (checkReductionClauseWithNogroup(*this, Clauses))
9899 return StmtError();
9900
9901 setFunctionHasBranchProtectedScope();
9902 return OMPParallelMasterTaskLoopDirective::Create(
9903 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9904}
9905
Alexey Bataev14a388f2019-10-25 10:27:13 -04009906StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9907 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9908 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9909 if (!AStmt)
9910 return StmtError();
9911
9912 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9913 auto *CS = cast<CapturedStmt>(AStmt);
9914 // 1.2.2 OpenMP Language Terminology
9915 // Structured block - An executable statement with a single entry at the
9916 // top and a single exit at the bottom.
9917 // The point of exit cannot be a branch out of the structured block.
9918 // longjmp() and throw() must not violate the entry/exit criteria.
9919 CS->getCapturedDecl()->setNothrow();
9920 for (int ThisCaptureLevel =
9921 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9922 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9923 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9924 // 1.2.2 OpenMP Language Terminology
9925 // Structured block - An executable statement with a single entry at the
9926 // top and a single exit at the bottom.
9927 // The point of exit cannot be a branch out of the structured block.
9928 // longjmp() and throw() must not violate the entry/exit criteria.
9929 CS->getCapturedDecl()->setNothrow();
9930 }
9931
9932 OMPLoopDirective::HelperExprs B;
9933 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9934 // define the nested loops number.
9935 unsigned NestedLoopCount = checkOpenMPLoop(
9936 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9937 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9938 VarsWithImplicitDSA, B);
9939 if (NestedLoopCount == 0)
9940 return StmtError();
9941
9942 assert((CurContext->isDependentContext() || B.builtAll()) &&
9943 "omp for loop exprs were not built");
9944
9945 if (!CurContext->isDependentContext()) {
9946 // Finalize the clauses that need pre-built expressions for CodeGen.
9947 for (OMPClause *C : Clauses) {
9948 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9949 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9950 B.NumIterations, *this, CurScope,
9951 DSAStack))
9952 return StmtError();
9953 }
9954 }
9955
9956 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9957 // The grainsize clause and num_tasks clause are mutually exclusive and may
9958 // not appear on the same taskloop directive.
9959 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9960 return StmtError();
9961 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9962 // If a reduction clause is present on the taskloop directive, the nogroup
9963 // clause must not be specified.
9964 if (checkReductionClauseWithNogroup(*this, Clauses))
9965 return StmtError();
9966 if (checkSimdlenSafelenSpecified(*this, Clauses))
9967 return StmtError();
9968
9969 setFunctionHasBranchProtectedScope();
9970 return OMPParallelMasterTaskLoopSimdDirective::Create(
9971 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9972}
9973
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009974StmtResult Sema::ActOnOpenMPDistributeDirective(
9975 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009976 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009977 if (!AStmt)
9978 return StmtError();
9979
9980 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9981 OMPLoopDirective::HelperExprs B;
9982 // In presence of clause 'collapse' with number of loops, it will
9983 // define the nested loops number.
9984 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009985 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009986 nullptr /*ordered not a clause on distribute*/, AStmt,
9987 *this, *DSAStack, VarsWithImplicitDSA, B);
9988 if (NestedLoopCount == 0)
9989 return StmtError();
9990
9991 assert((CurContext->isDependentContext() || B.builtAll()) &&
9992 "omp for loop exprs were not built");
9993
Reid Kleckner87a31802018-03-12 21:43:02 +00009994 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009995 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9996 NestedLoopCount, Clauses, AStmt, B);
9997}
9998
Carlo Bertolli9925f152016-06-27 14:55:37 +00009999StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10000 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010001 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +000010002 if (!AStmt)
10003 return StmtError();
10004
Alexey Bataeve3727102018-04-18 15:57:46 +000010005 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +000010006 // 1.2.2 OpenMP Language Terminology
10007 // Structured block - An executable statement with a single entry at the
10008 // top and a single exit at the bottom.
10009 // The point of exit cannot be a branch out of the structured block.
10010 // longjmp() and throw() must not violate the entry/exit criteria.
10011 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +000010012 for (int ThisCaptureLevel =
10013 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10014 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10015 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10016 // 1.2.2 OpenMP Language Terminology
10017 // Structured block - An executable statement with a single entry at the
10018 // top and a single exit at the bottom.
10019 // The point of exit cannot be a branch out of the structured block.
10020 // longjmp() and throw() must not violate the entry/exit criteria.
10021 CS->getCapturedDecl()->setNothrow();
10022 }
Carlo Bertolli9925f152016-06-27 14:55:37 +000010023
10024 OMPLoopDirective::HelperExprs B;
10025 // In presence of clause 'collapse' with number of loops, it will
10026 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010027 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +000010028 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +000010029 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +000010030 VarsWithImplicitDSA, B);
10031 if (NestedLoopCount == 0)
10032 return StmtError();
10033
10034 assert((CurContext->isDependentContext() || B.builtAll()) &&
10035 "omp for loop exprs were not built");
10036
Reid Kleckner87a31802018-03-12 21:43:02 +000010037 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +000010038 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010039 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10040 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +000010041}
10042
Kelvin Li4a39add2016-07-05 05:00:15 +000010043StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10044 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010045 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +000010046 if (!AStmt)
10047 return StmtError();
10048
Alexey Bataeve3727102018-04-18 15:57:46 +000010049 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +000010050 // 1.2.2 OpenMP Language Terminology
10051 // Structured block - An executable statement with a single entry at the
10052 // top and a single exit at the bottom.
10053 // The point of exit cannot be a branch out of the structured block.
10054 // longjmp() and throw() must not violate the entry/exit criteria.
10055 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +000010056 for (int ThisCaptureLevel =
10057 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10058 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10059 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10060 // 1.2.2 OpenMP Language Terminology
10061 // Structured block - An executable statement with a single entry at the
10062 // top and a single exit at the bottom.
10063 // The point of exit cannot be a branch out of the structured block.
10064 // longjmp() and throw() must not violate the entry/exit criteria.
10065 CS->getCapturedDecl()->setNothrow();
10066 }
Kelvin Li4a39add2016-07-05 05:00:15 +000010067
10068 OMPLoopDirective::HelperExprs B;
10069 // In presence of clause 'collapse' with number of loops, it will
10070 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010071 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +000010072 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +000010073 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +000010074 VarsWithImplicitDSA, B);
10075 if (NestedLoopCount == 0)
10076 return StmtError();
10077
10078 assert((CurContext->isDependentContext() || B.builtAll()) &&
10079 "omp for loop exprs were not built");
10080
Alexey Bataev438388c2017-11-22 18:34:02 +000010081 if (!CurContext->isDependentContext()) {
10082 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010083 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010084 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10085 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10086 B.NumIterations, *this, CurScope,
10087 DSAStack))
10088 return StmtError();
10089 }
10090 }
10091
Kelvin Lic5609492016-07-15 04:39:07 +000010092 if (checkSimdlenSafelenSpecified(*this, Clauses))
10093 return StmtError();
10094
Reid Kleckner87a31802018-03-12 21:43:02 +000010095 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010096 return OMPDistributeParallelForSimdDirective::Create(
10097 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10098}
10099
Kelvin Li787f3fc2016-07-06 04:45:38 +000010100StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10101 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010102 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010103 if (!AStmt)
10104 return StmtError();
10105
Alexey Bataeve3727102018-04-18 15:57:46 +000010106 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010107 // 1.2.2 OpenMP Language Terminology
10108 // Structured block - An executable statement with a single entry at the
10109 // top and a single exit at the bottom.
10110 // The point of exit cannot be a branch out of the structured block.
10111 // longjmp() and throw() must not violate the entry/exit criteria.
10112 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010113 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10114 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10115 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10116 // 1.2.2 OpenMP Language Terminology
10117 // Structured block - An executable statement with a single entry at the
10118 // top and a single exit at the bottom.
10119 // The point of exit cannot be a branch out of the structured block.
10120 // longjmp() and throw() must not violate the entry/exit criteria.
10121 CS->getCapturedDecl()->setNothrow();
10122 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010123
10124 OMPLoopDirective::HelperExprs B;
10125 // In presence of clause 'collapse' with number of loops, it will
10126 // define the nested loops number.
10127 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010128 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010129 nullptr /*ordered not a clause on distribute*/, CS, *this,
10130 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010131 if (NestedLoopCount == 0)
10132 return StmtError();
10133
10134 assert((CurContext->isDependentContext() || B.builtAll()) &&
10135 "omp for loop exprs were not built");
10136
Alexey Bataev438388c2017-11-22 18:34:02 +000010137 if (!CurContext->isDependentContext()) {
10138 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010139 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010140 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10141 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10142 B.NumIterations, *this, CurScope,
10143 DSAStack))
10144 return StmtError();
10145 }
10146 }
10147
Kelvin Lic5609492016-07-15 04:39:07 +000010148 if (checkSimdlenSafelenSpecified(*this, Clauses))
10149 return StmtError();
10150
Reid Kleckner87a31802018-03-12 21:43:02 +000010151 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010152 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10153 NestedLoopCount, Clauses, AStmt, B);
10154}
10155
Kelvin Lia579b912016-07-14 02:54:56 +000010156StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10157 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010158 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010159 if (!AStmt)
10160 return StmtError();
10161
Alexey Bataeve3727102018-04-18 15:57:46 +000010162 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010163 // 1.2.2 OpenMP Language Terminology
10164 // Structured block - An executable statement with a single entry at the
10165 // top and a single exit at the bottom.
10166 // The point of exit cannot be a branch out of the structured block.
10167 // longjmp() and throw() must not violate the entry/exit criteria.
10168 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010169 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10170 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10171 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10172 // 1.2.2 OpenMP Language Terminology
10173 // Structured block - An executable statement with a single entry at the
10174 // top and a single exit at the bottom.
10175 // The point of exit cannot be a branch out of the structured block.
10176 // longjmp() and throw() must not violate the entry/exit criteria.
10177 CS->getCapturedDecl()->setNothrow();
10178 }
Kelvin Lia579b912016-07-14 02:54:56 +000010179
10180 OMPLoopDirective::HelperExprs B;
10181 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10182 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010183 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010184 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010185 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010186 VarsWithImplicitDSA, B);
10187 if (NestedLoopCount == 0)
10188 return StmtError();
10189
10190 assert((CurContext->isDependentContext() || B.builtAll()) &&
10191 "omp target parallel for simd loop exprs were not built");
10192
10193 if (!CurContext->isDependentContext()) {
10194 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010195 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010196 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010197 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10198 B.NumIterations, *this, CurScope,
10199 DSAStack))
10200 return StmtError();
10201 }
10202 }
Kelvin Lic5609492016-07-15 04:39:07 +000010203 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010204 return StmtError();
10205
Reid Kleckner87a31802018-03-12 21:43:02 +000010206 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010207 return OMPTargetParallelForSimdDirective::Create(
10208 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10209}
10210
Kelvin Li986330c2016-07-20 22:57:10 +000010211StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10212 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010213 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010214 if (!AStmt)
10215 return StmtError();
10216
Alexey Bataeve3727102018-04-18 15:57:46 +000010217 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010218 // 1.2.2 OpenMP Language Terminology
10219 // Structured block - An executable statement with a single entry at the
10220 // top and a single exit at the bottom.
10221 // The point of exit cannot be a branch out of the structured block.
10222 // longjmp() and throw() must not violate the entry/exit criteria.
10223 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010224 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10225 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10226 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10227 // 1.2.2 OpenMP Language Terminology
10228 // Structured block - An executable statement with a single entry at the
10229 // top and a single exit at the bottom.
10230 // The point of exit cannot be a branch out of the structured block.
10231 // longjmp() and throw() must not violate the entry/exit criteria.
10232 CS->getCapturedDecl()->setNothrow();
10233 }
10234
Kelvin Li986330c2016-07-20 22:57:10 +000010235 OMPLoopDirective::HelperExprs B;
10236 // In presence of clause 'collapse' with number of loops, it will define the
10237 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010238 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010239 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010240 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010241 VarsWithImplicitDSA, B);
10242 if (NestedLoopCount == 0)
10243 return StmtError();
10244
10245 assert((CurContext->isDependentContext() || B.builtAll()) &&
10246 "omp target simd loop exprs were not built");
10247
10248 if (!CurContext->isDependentContext()) {
10249 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010250 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010251 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010252 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10253 B.NumIterations, *this, CurScope,
10254 DSAStack))
10255 return StmtError();
10256 }
10257 }
10258
10259 if (checkSimdlenSafelenSpecified(*this, Clauses))
10260 return StmtError();
10261
Reid Kleckner87a31802018-03-12 21:43:02 +000010262 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010263 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10264 NestedLoopCount, Clauses, AStmt, B);
10265}
10266
Kelvin Li02532872016-08-05 14:37:37 +000010267StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10268 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010269 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010270 if (!AStmt)
10271 return StmtError();
10272
Alexey Bataeve3727102018-04-18 15:57:46 +000010273 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010274 // 1.2.2 OpenMP Language Terminology
10275 // Structured block - An executable statement with a single entry at the
10276 // top and a single exit at the bottom.
10277 // The point of exit cannot be a branch out of the structured block.
10278 // longjmp() and throw() must not violate the entry/exit criteria.
10279 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010280 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10281 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10282 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10283 // 1.2.2 OpenMP Language Terminology
10284 // Structured block - An executable statement with a single entry at the
10285 // top and a single exit at the bottom.
10286 // The point of exit cannot be a branch out of the structured block.
10287 // longjmp() and throw() must not violate the entry/exit criteria.
10288 CS->getCapturedDecl()->setNothrow();
10289 }
Kelvin Li02532872016-08-05 14:37:37 +000010290
10291 OMPLoopDirective::HelperExprs B;
10292 // In presence of clause 'collapse' with number of loops, it will
10293 // define the nested loops number.
10294 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010295 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010296 nullptr /*ordered not a clause on distribute*/, CS, *this,
10297 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010298 if (NestedLoopCount == 0)
10299 return StmtError();
10300
10301 assert((CurContext->isDependentContext() || B.builtAll()) &&
10302 "omp teams distribute loop exprs were not built");
10303
Reid Kleckner87a31802018-03-12 21:43:02 +000010304 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010305
10306 DSAStack->setParentTeamsRegionLoc(StartLoc);
10307
David Majnemer9d168222016-08-05 17:44:54 +000010308 return OMPTeamsDistributeDirective::Create(
10309 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010310}
10311
Kelvin Li4e325f72016-10-25 12:50:55 +000010312StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10313 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010314 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010315 if (!AStmt)
10316 return StmtError();
10317
Alexey Bataeve3727102018-04-18 15:57:46 +000010318 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010319 // 1.2.2 OpenMP Language Terminology
10320 // Structured block - An executable statement with a single entry at the
10321 // top and a single exit at the bottom.
10322 // The point of exit cannot be a branch out of the structured block.
10323 // longjmp() and throw() must not violate the entry/exit criteria.
10324 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010325 for (int ThisCaptureLevel =
10326 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10327 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10328 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10329 // 1.2.2 OpenMP Language Terminology
10330 // Structured block - An executable statement with a single entry at the
10331 // top and a single exit at the bottom.
10332 // The point of exit cannot be a branch out of the structured block.
10333 // longjmp() and throw() must not violate the entry/exit criteria.
10334 CS->getCapturedDecl()->setNothrow();
10335 }
10336
Kelvin Li4e325f72016-10-25 12:50:55 +000010337
10338 OMPLoopDirective::HelperExprs B;
10339 // In presence of clause 'collapse' with number of loops, it will
10340 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010341 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010342 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010343 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010344 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010345
10346 if (NestedLoopCount == 0)
10347 return StmtError();
10348
10349 assert((CurContext->isDependentContext() || B.builtAll()) &&
10350 "omp teams distribute simd loop exprs were not built");
10351
10352 if (!CurContext->isDependentContext()) {
10353 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010354 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010355 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10356 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10357 B.NumIterations, *this, CurScope,
10358 DSAStack))
10359 return StmtError();
10360 }
10361 }
10362
10363 if (checkSimdlenSafelenSpecified(*this, Clauses))
10364 return StmtError();
10365
Reid Kleckner87a31802018-03-12 21:43:02 +000010366 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010367
10368 DSAStack->setParentTeamsRegionLoc(StartLoc);
10369
Kelvin Li4e325f72016-10-25 12:50:55 +000010370 return OMPTeamsDistributeSimdDirective::Create(
10371 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10372}
10373
Kelvin Li579e41c2016-11-30 23:51:03 +000010374StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10375 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010376 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010377 if (!AStmt)
10378 return StmtError();
10379
Alexey Bataeve3727102018-04-18 15:57:46 +000010380 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010381 // 1.2.2 OpenMP Language Terminology
10382 // Structured block - An executable statement with a single entry at the
10383 // top and a single exit at the bottom.
10384 // The point of exit cannot be a branch out of the structured block.
10385 // longjmp() and throw() must not violate the entry/exit criteria.
10386 CS->getCapturedDecl()->setNothrow();
10387
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010388 for (int ThisCaptureLevel =
10389 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10390 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10391 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10392 // 1.2.2 OpenMP Language Terminology
10393 // Structured block - An executable statement with a single entry at the
10394 // top and a single exit at the bottom.
10395 // The point of exit cannot be a branch out of the structured block.
10396 // longjmp() and throw() must not violate the entry/exit criteria.
10397 CS->getCapturedDecl()->setNothrow();
10398 }
10399
Kelvin Li579e41c2016-11-30 23:51:03 +000010400 OMPLoopDirective::HelperExprs B;
10401 // In presence of clause 'collapse' with number of loops, it will
10402 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010403 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010404 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010405 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010406 VarsWithImplicitDSA, B);
10407
10408 if (NestedLoopCount == 0)
10409 return StmtError();
10410
10411 assert((CurContext->isDependentContext() || B.builtAll()) &&
10412 "omp for loop exprs were not built");
10413
10414 if (!CurContext->isDependentContext()) {
10415 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010416 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010417 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10418 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10419 B.NumIterations, *this, CurScope,
10420 DSAStack))
10421 return StmtError();
10422 }
10423 }
10424
10425 if (checkSimdlenSafelenSpecified(*this, Clauses))
10426 return StmtError();
10427
Reid Kleckner87a31802018-03-12 21:43:02 +000010428 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010429
10430 DSAStack->setParentTeamsRegionLoc(StartLoc);
10431
Kelvin Li579e41c2016-11-30 23:51:03 +000010432 return OMPTeamsDistributeParallelForSimdDirective::Create(
10433 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10434}
10435
Kelvin Li7ade93f2016-12-09 03:24:30 +000010436StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10437 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010438 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010439 if (!AStmt)
10440 return StmtError();
10441
Alexey Bataeve3727102018-04-18 15:57:46 +000010442 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010443 // 1.2.2 OpenMP Language Terminology
10444 // Structured block - An executable statement with a single entry at the
10445 // top and a single exit at the bottom.
10446 // The point of exit cannot be a branch out of the structured block.
10447 // longjmp() and throw() must not violate the entry/exit criteria.
10448 CS->getCapturedDecl()->setNothrow();
10449
Carlo Bertolli62fae152017-11-20 20:46:39 +000010450 for (int ThisCaptureLevel =
10451 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10452 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10453 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10454 // 1.2.2 OpenMP Language Terminology
10455 // Structured block - An executable statement with a single entry at the
10456 // top and a single exit at the bottom.
10457 // The point of exit cannot be a branch out of the structured block.
10458 // longjmp() and throw() must not violate the entry/exit criteria.
10459 CS->getCapturedDecl()->setNothrow();
10460 }
10461
Kelvin Li7ade93f2016-12-09 03:24:30 +000010462 OMPLoopDirective::HelperExprs B;
10463 // In presence of clause 'collapse' with number of loops, it will
10464 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010465 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010466 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010467 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010468 VarsWithImplicitDSA, B);
10469
10470 if (NestedLoopCount == 0)
10471 return StmtError();
10472
10473 assert((CurContext->isDependentContext() || B.builtAll()) &&
10474 "omp for loop exprs were not built");
10475
Reid Kleckner87a31802018-03-12 21:43:02 +000010476 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010477
10478 DSAStack->setParentTeamsRegionLoc(StartLoc);
10479
Kelvin Li7ade93f2016-12-09 03:24:30 +000010480 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010481 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10482 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010483}
10484
Kelvin Libf594a52016-12-17 05:48:59 +000010485StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10486 Stmt *AStmt,
10487 SourceLocation StartLoc,
10488 SourceLocation EndLoc) {
10489 if (!AStmt)
10490 return StmtError();
10491
Alexey Bataeve3727102018-04-18 15:57:46 +000010492 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010493 // 1.2.2 OpenMP Language Terminology
10494 // Structured block - An executable statement with a single entry at the
10495 // top and a single exit at the bottom.
10496 // The point of exit cannot be a branch out of the structured block.
10497 // longjmp() and throw() must not violate the entry/exit criteria.
10498 CS->getCapturedDecl()->setNothrow();
10499
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010500 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10501 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10502 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10503 // 1.2.2 OpenMP Language Terminology
10504 // Structured block - An executable statement with a single entry at the
10505 // top and a single exit at the bottom.
10506 // The point of exit cannot be a branch out of the structured block.
10507 // longjmp() and throw() must not violate the entry/exit criteria.
10508 CS->getCapturedDecl()->setNothrow();
10509 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010510 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010511
10512 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10513 AStmt);
10514}
10515
Kelvin Li83c451e2016-12-25 04:52:54 +000010516StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10517 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010518 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010519 if (!AStmt)
10520 return StmtError();
10521
Alexey Bataeve3727102018-04-18 15:57:46 +000010522 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010523 // 1.2.2 OpenMP Language Terminology
10524 // Structured block - An executable statement with a single entry at the
10525 // top and a single exit at the bottom.
10526 // The point of exit cannot be a branch out of the structured block.
10527 // longjmp() and throw() must not violate the entry/exit criteria.
10528 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010529 for (int ThisCaptureLevel =
10530 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10531 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10532 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10533 // 1.2.2 OpenMP Language Terminology
10534 // Structured block - An executable statement with a single entry at the
10535 // top and a single exit at the bottom.
10536 // The point of exit cannot be a branch out of the structured block.
10537 // longjmp() and throw() must not violate the entry/exit criteria.
10538 CS->getCapturedDecl()->setNothrow();
10539 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010540
10541 OMPLoopDirective::HelperExprs B;
10542 // In presence of clause 'collapse' with number of loops, it will
10543 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010544 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010545 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10546 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010547 VarsWithImplicitDSA, B);
10548 if (NestedLoopCount == 0)
10549 return StmtError();
10550
10551 assert((CurContext->isDependentContext() || B.builtAll()) &&
10552 "omp target teams distribute loop exprs were not built");
10553
Reid Kleckner87a31802018-03-12 21:43:02 +000010554 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010555 return OMPTargetTeamsDistributeDirective::Create(
10556 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10557}
10558
Kelvin Li80e8f562016-12-29 22:16:30 +000010559StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10560 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010561 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010562 if (!AStmt)
10563 return StmtError();
10564
Alexey Bataeve3727102018-04-18 15:57:46 +000010565 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010566 // 1.2.2 OpenMP Language Terminology
10567 // Structured block - An executable statement with a single entry at the
10568 // top and a single exit at the bottom.
10569 // The point of exit cannot be a branch out of the structured block.
10570 // longjmp() and throw() must not violate the entry/exit criteria.
10571 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010572 for (int ThisCaptureLevel =
10573 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10574 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10575 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10576 // 1.2.2 OpenMP Language Terminology
10577 // Structured block - An executable statement with a single entry at the
10578 // top and a single exit at the bottom.
10579 // The point of exit cannot be a branch out of the structured block.
10580 // longjmp() and throw() must not violate the entry/exit criteria.
10581 CS->getCapturedDecl()->setNothrow();
10582 }
10583
Kelvin Li80e8f562016-12-29 22:16:30 +000010584 OMPLoopDirective::HelperExprs B;
10585 // In presence of clause 'collapse' with number of loops, it will
10586 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010587 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010588 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10589 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010590 VarsWithImplicitDSA, B);
10591 if (NestedLoopCount == 0)
10592 return StmtError();
10593
10594 assert((CurContext->isDependentContext() || B.builtAll()) &&
10595 "omp target teams distribute parallel for loop exprs were not built");
10596
Alexey Bataev647dd842018-01-15 20:59:40 +000010597 if (!CurContext->isDependentContext()) {
10598 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010599 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010600 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10601 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10602 B.NumIterations, *this, CurScope,
10603 DSAStack))
10604 return StmtError();
10605 }
10606 }
10607
Reid Kleckner87a31802018-03-12 21:43:02 +000010608 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010609 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010610 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10611 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010612}
10613
Kelvin Li1851df52017-01-03 05:23:48 +000010614StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10615 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010616 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010617 if (!AStmt)
10618 return StmtError();
10619
Alexey Bataeve3727102018-04-18 15:57:46 +000010620 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010621 // 1.2.2 OpenMP Language Terminology
10622 // Structured block - An executable statement with a single entry at the
10623 // top and a single exit at the bottom.
10624 // The point of exit cannot be a branch out of the structured block.
10625 // longjmp() and throw() must not violate the entry/exit criteria.
10626 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010627 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10628 OMPD_target_teams_distribute_parallel_for_simd);
10629 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10630 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10631 // 1.2.2 OpenMP Language Terminology
10632 // Structured block - An executable statement with a single entry at the
10633 // top and a single exit at the bottom.
10634 // The point of exit cannot be a branch out of the structured block.
10635 // longjmp() and throw() must not violate the entry/exit criteria.
10636 CS->getCapturedDecl()->setNothrow();
10637 }
Kelvin Li1851df52017-01-03 05:23:48 +000010638
10639 OMPLoopDirective::HelperExprs B;
10640 // In presence of clause 'collapse' with number of loops, it will
10641 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010642 unsigned NestedLoopCount =
10643 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010644 getCollapseNumberExpr(Clauses),
10645 nullptr /*ordered not a clause on distribute*/, CS, *this,
10646 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010647 if (NestedLoopCount == 0)
10648 return StmtError();
10649
10650 assert((CurContext->isDependentContext() || B.builtAll()) &&
10651 "omp target teams distribute parallel for simd loop exprs were not "
10652 "built");
10653
10654 if (!CurContext->isDependentContext()) {
10655 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010656 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010657 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10658 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10659 B.NumIterations, *this, CurScope,
10660 DSAStack))
10661 return StmtError();
10662 }
10663 }
10664
Alexey Bataev438388c2017-11-22 18:34:02 +000010665 if (checkSimdlenSafelenSpecified(*this, Clauses))
10666 return StmtError();
10667
Reid Kleckner87a31802018-03-12 21:43:02 +000010668 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010669 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10670 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10671}
10672
Kelvin Lida681182017-01-10 18:08:18 +000010673StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10674 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010675 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010676 if (!AStmt)
10677 return StmtError();
10678
10679 auto *CS = cast<CapturedStmt>(AStmt);
10680 // 1.2.2 OpenMP Language Terminology
10681 // Structured block - An executable statement with a single entry at the
10682 // top and a single exit at the bottom.
10683 // The point of exit cannot be a branch out of the structured block.
10684 // longjmp() and throw() must not violate the entry/exit criteria.
10685 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010686 for (int ThisCaptureLevel =
10687 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10688 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10689 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10690 // 1.2.2 OpenMP Language Terminology
10691 // Structured block - An executable statement with a single entry at the
10692 // top and a single exit at the bottom.
10693 // The point of exit cannot be a branch out of the structured block.
10694 // longjmp() and throw() must not violate the entry/exit criteria.
10695 CS->getCapturedDecl()->setNothrow();
10696 }
Kelvin Lida681182017-01-10 18:08:18 +000010697
10698 OMPLoopDirective::HelperExprs B;
10699 // In presence of clause 'collapse' with number of loops, it will
10700 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010701 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010702 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010703 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010704 VarsWithImplicitDSA, B);
10705 if (NestedLoopCount == 0)
10706 return StmtError();
10707
10708 assert((CurContext->isDependentContext() || B.builtAll()) &&
10709 "omp target teams distribute simd loop exprs were not built");
10710
Alexey Bataev438388c2017-11-22 18:34:02 +000010711 if (!CurContext->isDependentContext()) {
10712 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010713 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010714 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10715 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10716 B.NumIterations, *this, CurScope,
10717 DSAStack))
10718 return StmtError();
10719 }
10720 }
10721
10722 if (checkSimdlenSafelenSpecified(*this, Clauses))
10723 return StmtError();
10724
Reid Kleckner87a31802018-03-12 21:43:02 +000010725 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010726 return OMPTargetTeamsDistributeSimdDirective::Create(
10727 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10728}
10729
Alexey Bataeved09d242014-05-28 05:53:51 +000010730OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010731 SourceLocation StartLoc,
10732 SourceLocation LParenLoc,
10733 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010734 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010735 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010736 case OMPC_final:
10737 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10738 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010739 case OMPC_num_threads:
10740 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10741 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010742 case OMPC_safelen:
10743 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10744 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010745 case OMPC_simdlen:
10746 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10747 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010748 case OMPC_allocator:
10749 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10750 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010751 case OMPC_collapse:
10752 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10753 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010754 case OMPC_ordered:
10755 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10756 break;
Michael Wonge710d542015-08-07 16:16:36 +000010757 case OMPC_device:
10758 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10759 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010760 case OMPC_num_teams:
10761 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10762 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010763 case OMPC_thread_limit:
10764 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10765 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010766 case OMPC_priority:
10767 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10768 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010769 case OMPC_grainsize:
10770 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10771 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010772 case OMPC_num_tasks:
10773 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10774 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010775 case OMPC_hint:
10776 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10777 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010778 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010779 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010780 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010781 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010782 case OMPC_private:
10783 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010784 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010785 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010786 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010787 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010788 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010789 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010790 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010791 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010792 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010793 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010794 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010795 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010796 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010797 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010798 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010799 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010800 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010801 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010802 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010803 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010804 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010805 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010806 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010807 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010808 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010809 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010810 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010811 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010812 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010813 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010814 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010815 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010816 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010817 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010818 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010819 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010820 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010821 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010822 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010823 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050010824 case OMPC_nontemporal:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010825 llvm_unreachable("Clause is not allowed.");
10826 }
10827 return Res;
10828}
10829
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010830// An OpenMP directive such as 'target parallel' has two captured regions:
10831// for the 'target' and 'parallel' respectively. This function returns
10832// the region in which to capture expressions associated with a clause.
10833// A return value of OMPD_unknown signifies that the expression should not
10834// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010835static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010836 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010837 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010838 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010839 switch (CKind) {
10840 case OMPC_if:
10841 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010842 case OMPD_target_parallel_for_simd:
10843 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010844 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010845 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010846 break;
10847 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010848 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010849 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010850 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010851 // If this clause applies to the nested 'parallel' region, capture within
10852 // the 'target' region, otherwise do not capture.
10853 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10854 CaptureRegion = OMPD_target;
10855 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010856 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050010857 if (OpenMPVersion >= 50 &&
10858 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10859 CaptureRegion = OMPD_parallel;
10860 break;
10861 }
10862 LLVM_FALLTHROUGH;
10863 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000010864 // If this clause applies to the nested 'parallel' region, capture within
10865 // the 'teams' region, otherwise do not capture.
10866 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10867 CaptureRegion = OMPD_teams;
10868 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010869 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050010870 if (OpenMPVersion >= 50 &&
10871 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10872 CaptureRegion = OMPD_parallel;
10873 break;
10874 }
10875 LLVM_FALLTHROUGH;
10876 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010877 CaptureRegion = OMPD_teams;
10878 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010879 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010880 case OMPD_target_enter_data:
10881 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010882 CaptureRegion = OMPD_task;
10883 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010884 case OMPD_parallel_master_taskloop:
10885 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10886 CaptureRegion = OMPD_parallel;
10887 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010888 case OMPD_parallel_master_taskloop_simd:
10889 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10890 NameModifier == OMPD_taskloop) {
10891 CaptureRegion = OMPD_parallel;
10892 break;
10893 }
10894 if (OpenMPVersion <= 45)
10895 break;
10896 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10897 CaptureRegion = OMPD_taskloop;
10898 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010899 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010900 if (OpenMPVersion <= 45)
10901 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010902 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10903 CaptureRegion = OMPD_parallel;
10904 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010905 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010906 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010907 if (OpenMPVersion <= 45)
10908 break;
10909 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10910 CaptureRegion = OMPD_taskloop;
10911 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050010912 case OMPD_distribute_parallel_for_simd:
10913 if (OpenMPVersion <= 45)
10914 break;
10915 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10916 CaptureRegion = OMPD_parallel;
10917 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050010918 case OMPD_target_simd:
10919 if (OpenMPVersion >= 50 &&
10920 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10921 CaptureRegion = OMPD_target;
10922 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050010923 case OMPD_teams_distribute_simd:
Alexey Bataev411e81a2019-12-16 11:16:46 -050010924 case OMPD_target_teams_distribute_simd:
Alexey Bataev7b774b72019-12-11 11:20:47 -050010925 if (OpenMPVersion >= 50 &&
10926 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10927 CaptureRegion = OMPD_teams;
10928 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010929 case OMPD_cancel:
10930 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010931 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010932 case OMPD_parallel_sections:
10933 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010934 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010935 case OMPD_target_teams:
10936 case OMPD_target_teams_distribute:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010937 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010938 case OMPD_task:
10939 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010940 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010941 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010942 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010943 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050010944 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010945 // Do not capture if-clause expressions.
10946 break;
10947 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010948 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010949 case OMPD_taskyield:
10950 case OMPD_barrier:
10951 case OMPD_taskwait:
10952 case OMPD_cancellation_point:
10953 case OMPD_flush:
10954 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010955 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010956 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010957 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010958 case OMPD_declare_target:
10959 case OMPD_end_declare_target:
10960 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010961 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010962 case OMPD_sections:
10963 case OMPD_section:
10964 case OMPD_single:
10965 case OMPD_master:
10966 case OMPD_critical:
10967 case OMPD_taskgroup:
10968 case OMPD_distribute:
10969 case OMPD_ordered:
10970 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010971 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000010972 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010973 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10974 case OMPD_unknown:
10975 llvm_unreachable("Unknown OpenMP directive");
10976 }
10977 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010978 case OMPC_num_threads:
10979 switch (DKind) {
10980 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010981 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010982 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010983 CaptureRegion = OMPD_target;
10984 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010985 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010986 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010987 case OMPD_target_teams_distribute_parallel_for:
10988 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010989 CaptureRegion = OMPD_teams;
10990 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010991 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010992 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010993 case OMPD_parallel_sections:
10994 case OMPD_parallel_for:
10995 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010996 case OMPD_distribute_parallel_for:
10997 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010998 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010999 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011000 // Do not capture num_threads-clause expressions.
11001 break;
11002 case OMPD_target_data:
11003 case OMPD_target_enter_data:
11004 case OMPD_target_exit_data:
11005 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011006 case OMPD_target:
11007 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011008 case OMPD_target_teams:
11009 case OMPD_target_teams_distribute:
11010 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011011 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011012 case OMPD_task:
11013 case OMPD_taskloop:
11014 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011015 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011016 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011017 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011018 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011019 case OMPD_taskyield:
11020 case OMPD_barrier:
11021 case OMPD_taskwait:
11022 case OMPD_cancellation_point:
11023 case OMPD_flush:
11024 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011025 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011026 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011027 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011028 case OMPD_declare_target:
11029 case OMPD_end_declare_target:
11030 case OMPD_teams:
11031 case OMPD_simd:
11032 case OMPD_for:
11033 case OMPD_for_simd:
11034 case OMPD_sections:
11035 case OMPD_section:
11036 case OMPD_single:
11037 case OMPD_master:
11038 case OMPD_critical:
11039 case OMPD_taskgroup:
11040 case OMPD_distribute:
11041 case OMPD_ordered:
11042 case OMPD_atomic:
11043 case OMPD_distribute_simd:
11044 case OMPD_teams_distribute:
11045 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011046 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011047 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11048 case OMPD_unknown:
11049 llvm_unreachable("Unknown OpenMP directive");
11050 }
11051 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011052 case OMPC_num_teams:
11053 switch (DKind) {
11054 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011055 case OMPD_target_teams_distribute:
11056 case OMPD_target_teams_distribute_simd:
11057 case OMPD_target_teams_distribute_parallel_for:
11058 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011059 CaptureRegion = OMPD_target;
11060 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011061 case OMPD_teams_distribute_parallel_for:
11062 case OMPD_teams_distribute_parallel_for_simd:
11063 case OMPD_teams:
11064 case OMPD_teams_distribute:
11065 case OMPD_teams_distribute_simd:
11066 // Do not capture num_teams-clause expressions.
11067 break;
11068 case OMPD_distribute_parallel_for:
11069 case OMPD_distribute_parallel_for_simd:
11070 case OMPD_task:
11071 case OMPD_taskloop:
11072 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011073 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011074 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011075 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011076 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011077 case OMPD_target_data:
11078 case OMPD_target_enter_data:
11079 case OMPD_target_exit_data:
11080 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011081 case OMPD_cancel:
11082 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011083 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011084 case OMPD_parallel_sections:
11085 case OMPD_parallel_for:
11086 case OMPD_parallel_for_simd:
11087 case OMPD_target:
11088 case OMPD_target_simd:
11089 case OMPD_target_parallel:
11090 case OMPD_target_parallel_for:
11091 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011092 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011093 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011094 case OMPD_taskyield:
11095 case OMPD_barrier:
11096 case OMPD_taskwait:
11097 case OMPD_cancellation_point:
11098 case OMPD_flush:
11099 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011100 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011101 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011102 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011103 case OMPD_declare_target:
11104 case OMPD_end_declare_target:
11105 case OMPD_simd:
11106 case OMPD_for:
11107 case OMPD_for_simd:
11108 case OMPD_sections:
11109 case OMPD_section:
11110 case OMPD_single:
11111 case OMPD_master:
11112 case OMPD_critical:
11113 case OMPD_taskgroup:
11114 case OMPD_distribute:
11115 case OMPD_ordered:
11116 case OMPD_atomic:
11117 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011118 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011119 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11120 case OMPD_unknown:
11121 llvm_unreachable("Unknown OpenMP directive");
11122 }
11123 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011124 case OMPC_thread_limit:
11125 switch (DKind) {
11126 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011127 case OMPD_target_teams_distribute:
11128 case OMPD_target_teams_distribute_simd:
11129 case OMPD_target_teams_distribute_parallel_for:
11130 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011131 CaptureRegion = OMPD_target;
11132 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011133 case OMPD_teams_distribute_parallel_for:
11134 case OMPD_teams_distribute_parallel_for_simd:
11135 case OMPD_teams:
11136 case OMPD_teams_distribute:
11137 case OMPD_teams_distribute_simd:
11138 // Do not capture thread_limit-clause expressions.
11139 break;
11140 case OMPD_distribute_parallel_for:
11141 case OMPD_distribute_parallel_for_simd:
11142 case OMPD_task:
11143 case OMPD_taskloop:
11144 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011145 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011146 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011147 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011148 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011149 case OMPD_target_data:
11150 case OMPD_target_enter_data:
11151 case OMPD_target_exit_data:
11152 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011153 case OMPD_cancel:
11154 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011155 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011156 case OMPD_parallel_sections:
11157 case OMPD_parallel_for:
11158 case OMPD_parallel_for_simd:
11159 case OMPD_target:
11160 case OMPD_target_simd:
11161 case OMPD_target_parallel:
11162 case OMPD_target_parallel_for:
11163 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011164 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011165 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011166 case OMPD_taskyield:
11167 case OMPD_barrier:
11168 case OMPD_taskwait:
11169 case OMPD_cancellation_point:
11170 case OMPD_flush:
11171 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011172 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011173 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011174 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011175 case OMPD_declare_target:
11176 case OMPD_end_declare_target:
11177 case OMPD_simd:
11178 case OMPD_for:
11179 case OMPD_for_simd:
11180 case OMPD_sections:
11181 case OMPD_section:
11182 case OMPD_single:
11183 case OMPD_master:
11184 case OMPD_critical:
11185 case OMPD_taskgroup:
11186 case OMPD_distribute:
11187 case OMPD_ordered:
11188 case OMPD_atomic:
11189 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011190 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011191 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11192 case OMPD_unknown:
11193 llvm_unreachable("Unknown OpenMP directive");
11194 }
11195 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011196 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011197 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011198 case OMPD_parallel_for:
11199 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011200 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011201 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011202 case OMPD_teams_distribute_parallel_for:
11203 case OMPD_teams_distribute_parallel_for_simd:
11204 case OMPD_target_parallel_for:
11205 case OMPD_target_parallel_for_simd:
11206 case OMPD_target_teams_distribute_parallel_for:
11207 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011208 CaptureRegion = OMPD_parallel;
11209 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011210 case OMPD_for:
11211 case OMPD_for_simd:
11212 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011213 break;
11214 case OMPD_task:
11215 case OMPD_taskloop:
11216 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011217 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011218 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011219 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011220 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011221 case OMPD_target_data:
11222 case OMPD_target_enter_data:
11223 case OMPD_target_exit_data:
11224 case OMPD_target_update:
11225 case OMPD_teams:
11226 case OMPD_teams_distribute:
11227 case OMPD_teams_distribute_simd:
11228 case OMPD_target_teams_distribute:
11229 case OMPD_target_teams_distribute_simd:
11230 case OMPD_target:
11231 case OMPD_target_simd:
11232 case OMPD_target_parallel:
11233 case OMPD_cancel:
11234 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011235 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011236 case OMPD_parallel_sections:
11237 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011238 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011239 case OMPD_taskyield:
11240 case OMPD_barrier:
11241 case OMPD_taskwait:
11242 case OMPD_cancellation_point:
11243 case OMPD_flush:
11244 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011245 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011246 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011247 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011248 case OMPD_declare_target:
11249 case OMPD_end_declare_target:
11250 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011251 case OMPD_sections:
11252 case OMPD_section:
11253 case OMPD_single:
11254 case OMPD_master:
11255 case OMPD_critical:
11256 case OMPD_taskgroup:
11257 case OMPD_distribute:
11258 case OMPD_ordered:
11259 case OMPD_atomic:
11260 case OMPD_distribute_simd:
11261 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011262 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011263 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11264 case OMPD_unknown:
11265 llvm_unreachable("Unknown OpenMP directive");
11266 }
11267 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011268 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011269 switch (DKind) {
11270 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011271 case OMPD_teams_distribute_parallel_for_simd:
11272 case OMPD_teams_distribute:
11273 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011274 case OMPD_target_teams_distribute_parallel_for:
11275 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011276 case OMPD_target_teams_distribute:
11277 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011278 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011279 break;
11280 case OMPD_distribute_parallel_for:
11281 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011282 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011283 case OMPD_distribute_simd:
11284 // Do not capture thread_limit-clause expressions.
11285 break;
11286 case OMPD_parallel_for:
11287 case OMPD_parallel_for_simd:
11288 case OMPD_target_parallel_for_simd:
11289 case OMPD_target_parallel_for:
11290 case OMPD_task:
11291 case OMPD_taskloop:
11292 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011293 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011294 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011295 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011296 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011297 case OMPD_target_data:
11298 case OMPD_target_enter_data:
11299 case OMPD_target_exit_data:
11300 case OMPD_target_update:
11301 case OMPD_teams:
11302 case OMPD_target:
11303 case OMPD_target_simd:
11304 case OMPD_target_parallel:
11305 case OMPD_cancel:
11306 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011307 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011308 case OMPD_parallel_sections:
11309 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011310 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011311 case OMPD_taskyield:
11312 case OMPD_barrier:
11313 case OMPD_taskwait:
11314 case OMPD_cancellation_point:
11315 case OMPD_flush:
11316 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011317 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011318 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011319 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011320 case OMPD_declare_target:
11321 case OMPD_end_declare_target:
11322 case OMPD_simd:
11323 case OMPD_for:
11324 case OMPD_for_simd:
11325 case OMPD_sections:
11326 case OMPD_section:
11327 case OMPD_single:
11328 case OMPD_master:
11329 case OMPD_critical:
11330 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011331 case OMPD_ordered:
11332 case OMPD_atomic:
11333 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011334 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011335 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11336 case OMPD_unknown:
11337 llvm_unreachable("Unknown OpenMP directive");
11338 }
11339 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011340 case OMPC_device:
11341 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011342 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011343 case OMPD_target_enter_data:
11344 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011345 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011346 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011347 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011348 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011349 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011350 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011351 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011352 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011353 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011354 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011355 CaptureRegion = OMPD_task;
11356 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011357 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011358 // Do not capture device-clause expressions.
11359 break;
11360 case OMPD_teams_distribute_parallel_for:
11361 case OMPD_teams_distribute_parallel_for_simd:
11362 case OMPD_teams:
11363 case OMPD_teams_distribute:
11364 case OMPD_teams_distribute_simd:
11365 case OMPD_distribute_parallel_for:
11366 case OMPD_distribute_parallel_for_simd:
11367 case OMPD_task:
11368 case OMPD_taskloop:
11369 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011370 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011371 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011372 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011373 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011374 case OMPD_cancel:
11375 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011376 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011377 case OMPD_parallel_sections:
11378 case OMPD_parallel_for:
11379 case OMPD_parallel_for_simd:
11380 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011381 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011382 case OMPD_taskyield:
11383 case OMPD_barrier:
11384 case OMPD_taskwait:
11385 case OMPD_cancellation_point:
11386 case OMPD_flush:
11387 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011388 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011389 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011390 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011391 case OMPD_declare_target:
11392 case OMPD_end_declare_target:
11393 case OMPD_simd:
11394 case OMPD_for:
11395 case OMPD_for_simd:
11396 case OMPD_sections:
11397 case OMPD_section:
11398 case OMPD_single:
11399 case OMPD_master:
11400 case OMPD_critical:
11401 case OMPD_taskgroup:
11402 case OMPD_distribute:
11403 case OMPD_ordered:
11404 case OMPD_atomic:
11405 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011406 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011407 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11408 case OMPD_unknown:
11409 llvm_unreachable("Unknown OpenMP directive");
11410 }
11411 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011412 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011413 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011414 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011415 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011416 switch (DKind) {
11417 case OMPD_task:
11418 case OMPD_taskloop:
11419 case OMPD_taskloop_simd:
11420 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011421 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011422 break;
11423 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011424 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011425 CaptureRegion = OMPD_parallel;
11426 break;
11427 case OMPD_target_update:
11428 case OMPD_target_enter_data:
11429 case OMPD_target_exit_data:
11430 case OMPD_target:
11431 case OMPD_target_simd:
11432 case OMPD_target_teams:
11433 case OMPD_target_parallel:
11434 case OMPD_target_teams_distribute:
11435 case OMPD_target_teams_distribute_simd:
11436 case OMPD_target_parallel_for:
11437 case OMPD_target_parallel_for_simd:
11438 case OMPD_target_teams_distribute_parallel_for:
11439 case OMPD_target_teams_distribute_parallel_for_simd:
11440 case OMPD_target_data:
11441 case OMPD_teams_distribute_parallel_for:
11442 case OMPD_teams_distribute_parallel_for_simd:
11443 case OMPD_teams:
11444 case OMPD_teams_distribute:
11445 case OMPD_teams_distribute_simd:
11446 case OMPD_distribute_parallel_for:
11447 case OMPD_distribute_parallel_for_simd:
11448 case OMPD_cancel:
11449 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011450 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011451 case OMPD_parallel_sections:
11452 case OMPD_parallel_for:
11453 case OMPD_parallel_for_simd:
11454 case OMPD_threadprivate:
11455 case OMPD_allocate:
11456 case OMPD_taskyield:
11457 case OMPD_barrier:
11458 case OMPD_taskwait:
11459 case OMPD_cancellation_point:
11460 case OMPD_flush:
11461 case OMPD_declare_reduction:
11462 case OMPD_declare_mapper:
11463 case OMPD_declare_simd:
11464 case OMPD_declare_variant:
11465 case OMPD_declare_target:
11466 case OMPD_end_declare_target:
11467 case OMPD_simd:
11468 case OMPD_for:
11469 case OMPD_for_simd:
11470 case OMPD_sections:
11471 case OMPD_section:
11472 case OMPD_single:
11473 case OMPD_master:
11474 case OMPD_critical:
11475 case OMPD_taskgroup:
11476 case OMPD_distribute:
11477 case OMPD_ordered:
11478 case OMPD_atomic:
11479 case OMPD_distribute_simd:
11480 case OMPD_requires:
11481 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11482 case OMPD_unknown:
11483 llvm_unreachable("Unknown OpenMP directive");
11484 }
11485 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011486 case OMPC_firstprivate:
11487 case OMPC_lastprivate:
11488 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011489 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011490 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011491 case OMPC_linear:
11492 case OMPC_default:
11493 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011494 case OMPC_safelen:
11495 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011496 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011497 case OMPC_collapse:
11498 case OMPC_private:
11499 case OMPC_shared:
11500 case OMPC_aligned:
11501 case OMPC_copyin:
11502 case OMPC_copyprivate:
11503 case OMPC_ordered:
11504 case OMPC_nowait:
11505 case OMPC_untied:
11506 case OMPC_mergeable:
11507 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011508 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011509 case OMPC_flush:
11510 case OMPC_read:
11511 case OMPC_write:
11512 case OMPC_update:
11513 case OMPC_capture:
11514 case OMPC_seq_cst:
11515 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011516 case OMPC_threads:
11517 case OMPC_simd:
11518 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011519 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011520 case OMPC_hint:
11521 case OMPC_defaultmap:
11522 case OMPC_unknown:
11523 case OMPC_uniform:
11524 case OMPC_to:
11525 case OMPC_from:
11526 case OMPC_use_device_ptr:
11527 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011528 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011529 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011530 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011531 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011532 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011533 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011534 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011535 case OMPC_nontemporal:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011536 llvm_unreachable("Unexpected OpenMP clause.");
11537 }
11538 return CaptureRegion;
11539}
11540
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011541OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11542 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011543 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011544 SourceLocation NameModifierLoc,
11545 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011546 SourceLocation EndLoc) {
11547 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011548 Stmt *HelperValStmt = nullptr;
11549 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011550 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11551 !Condition->isInstantiationDependent() &&
11552 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011553 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011554 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011555 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011556
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011557 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011558
11559 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011560 CaptureRegion = getOpenMPCaptureRegionForClause(
11561 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011562 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011563 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011564 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011565 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11566 HelperValStmt = buildPreInits(Context, Captures);
11567 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011568 }
11569
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011570 return new (Context)
11571 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11572 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011573}
11574
Alexey Bataev3778b602014-07-17 07:32:53 +000011575OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11576 SourceLocation StartLoc,
11577 SourceLocation LParenLoc,
11578 SourceLocation EndLoc) {
11579 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011580 Stmt *HelperValStmt = nullptr;
11581 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011582 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11583 !Condition->isInstantiationDependent() &&
11584 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011585 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011586 if (Val.isInvalid())
11587 return nullptr;
11588
Richard Smith03a4aa32016-06-23 19:02:52 +000011589 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011590
11591 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011592 CaptureRegion =
11593 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011594 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11595 ValExpr = MakeFullExpr(ValExpr).get();
11596 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11597 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11598 HelperValStmt = buildPreInits(Context, Captures);
11599 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011600 }
11601
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011602 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11603 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011604}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011605
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011606ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11607 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011608 if (!Op)
11609 return ExprError();
11610
11611 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11612 public:
11613 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011614 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011615 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11616 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011617 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11618 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011619 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11620 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011621 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11622 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011623 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11624 QualType T,
11625 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011626 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11627 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011628 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11629 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011630 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011631 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011632 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011633 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11634 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011635 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11636 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011637 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11638 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011639 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011640 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011641 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011642 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11643 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011644 llvm_unreachable("conversion functions are permitted");
11645 }
11646 } ConvertDiagnoser;
11647 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11648}
11649
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011650static bool
11651isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11652 bool StrictlyPositive, bool BuildCapture = false,
11653 OpenMPDirectiveKind DKind = OMPD_unknown,
11654 OpenMPDirectiveKind *CaptureRegion = nullptr,
11655 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011656 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11657 !ValExpr->isInstantiationDependent()) {
11658 SourceLocation Loc = ValExpr->getExprLoc();
11659 ExprResult Value =
11660 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11661 if (Value.isInvalid())
11662 return false;
11663
11664 ValExpr = Value.get();
11665 // The expression must evaluate to a non-negative integer value.
11666 llvm::APSInt Result;
11667 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011668 Result.isSigned() &&
11669 !((!StrictlyPositive && Result.isNonNegative()) ||
11670 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011671 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011672 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11673 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011674 return false;
11675 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011676 if (!BuildCapture)
11677 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011678 *CaptureRegion =
11679 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011680 if (*CaptureRegion != OMPD_unknown &&
11681 !SemaRef.CurContext->isDependentContext()) {
11682 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11683 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11684 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11685 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11686 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011687 }
11688 return true;
11689}
11690
Alexey Bataev568a8332014-03-06 06:15:19 +000011691OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11692 SourceLocation StartLoc,
11693 SourceLocation LParenLoc,
11694 SourceLocation EndLoc) {
11695 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011696 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011697
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011698 // OpenMP [2.5, Restrictions]
11699 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011700 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011701 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011702 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011703
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011704 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011705 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011706 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011707 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011708 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011709 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011710 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11711 HelperValStmt = buildPreInits(Context, Captures);
11712 }
11713
11714 return new (Context) OMPNumThreadsClause(
11715 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011716}
11717
Alexey Bataev62c87d22014-03-21 04:51:18 +000011718ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011719 OpenMPClauseKind CKind,
11720 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011721 if (!E)
11722 return ExprError();
11723 if (E->isValueDependent() || E->isTypeDependent() ||
11724 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011725 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011726 llvm::APSInt Result;
11727 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11728 if (ICE.isInvalid())
11729 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011730 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11731 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011732 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011733 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11734 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011735 return ExprError();
11736 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011737 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11738 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11739 << E->getSourceRange();
11740 return ExprError();
11741 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011742 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11743 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011744 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011745 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011746 return ICE;
11747}
11748
11749OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11750 SourceLocation LParenLoc,
11751 SourceLocation EndLoc) {
11752 // OpenMP [2.8.1, simd construct, Description]
11753 // The parameter of the safelen clause must be a constant
11754 // positive integer expression.
11755 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11756 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011757 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011758 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011759 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011760}
11761
Alexey Bataev66b15b52015-08-21 11:14:16 +000011762OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11763 SourceLocation LParenLoc,
11764 SourceLocation EndLoc) {
11765 // OpenMP [2.8.1, simd construct, Description]
11766 // The parameter of the simdlen clause must be a constant
11767 // positive integer expression.
11768 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11769 if (Simdlen.isInvalid())
11770 return nullptr;
11771 return new (Context)
11772 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11773}
11774
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011775/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011776static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11777 DSAStackTy *Stack) {
11778 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011779 if (!OMPAllocatorHandleT.isNull())
11780 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011781 // Build the predefined allocator expressions.
11782 bool ErrorFound = false;
11783 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11784 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11785 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11786 StringRef Allocator =
11787 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11788 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11789 auto *VD = dyn_cast_or_null<ValueDecl>(
11790 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11791 if (!VD) {
11792 ErrorFound = true;
11793 break;
11794 }
11795 QualType AllocatorType =
11796 VD->getType().getNonLValueExprType(S.getASTContext());
11797 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11798 if (!Res.isUsable()) {
11799 ErrorFound = true;
11800 break;
11801 }
11802 if (OMPAllocatorHandleT.isNull())
11803 OMPAllocatorHandleT = AllocatorType;
11804 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11805 ErrorFound = true;
11806 break;
11807 }
11808 Stack->setAllocator(AllocatorKind, Res.get());
11809 }
11810 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011811 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11812 return false;
11813 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011814 OMPAllocatorHandleT.addConst();
11815 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011816 return true;
11817}
11818
11819OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11820 SourceLocation LParenLoc,
11821 SourceLocation EndLoc) {
11822 // OpenMP [2.11.3, allocate Directive, Description]
11823 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011824 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011825 return nullptr;
11826
11827 ExprResult Allocator = DefaultLvalueConversion(A);
11828 if (Allocator.isInvalid())
11829 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011830 Allocator = PerformImplicitConversion(Allocator.get(),
11831 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011832 Sema::AA_Initializing,
11833 /*AllowExplicit=*/true);
11834 if (Allocator.isInvalid())
11835 return nullptr;
11836 return new (Context)
11837 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11838}
11839
Alexander Musman64d33f12014-06-04 07:53:32 +000011840OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11841 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011842 SourceLocation LParenLoc,
11843 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011844 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011845 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011846 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011847 // The parameter of the collapse clause must be a constant
11848 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011849 ExprResult NumForLoopsResult =
11850 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11851 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011852 return nullptr;
11853 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011854 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011855}
11856
Alexey Bataev10e775f2015-07-30 11:36:16 +000011857OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11858 SourceLocation EndLoc,
11859 SourceLocation LParenLoc,
11860 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011861 // OpenMP [2.7.1, loop construct, Description]
11862 // OpenMP [2.8.1, simd construct, Description]
11863 // OpenMP [2.9.6, distribute construct, Description]
11864 // The parameter of the ordered clause must be a constant
11865 // positive integer expression if any.
11866 if (NumForLoops && LParenLoc.isValid()) {
11867 ExprResult NumForLoopsResult =
11868 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11869 if (NumForLoopsResult.isInvalid())
11870 return nullptr;
11871 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011872 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011873 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011874 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011875 auto *Clause = OMPOrderedClause::Create(
11876 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11877 StartLoc, LParenLoc, EndLoc);
11878 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11879 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011880}
11881
Alexey Bataeved09d242014-05-28 05:53:51 +000011882OMPClause *Sema::ActOnOpenMPSimpleClause(
11883 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11884 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011885 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011886 switch (Kind) {
11887 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011888 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011889 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11890 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011891 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011892 case OMPC_proc_bind:
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011893 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
11894 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011895 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011896 case OMPC_atomic_default_mem_order:
11897 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11898 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11899 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11900 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011901 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011902 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011903 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011904 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011905 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011906 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011907 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011908 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011909 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011910 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011911 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011912 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011913 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011914 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011915 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011916 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011917 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011918 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011919 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011920 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011921 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011922 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011923 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011924 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011925 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011926 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011927 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011928 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011929 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011930 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011931 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011932 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011933 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011934 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011935 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011936 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011937 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011938 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011939 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011940 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011941 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011942 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011943 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011944 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011945 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011946 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011947 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011948 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011949 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011950 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011951 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011952 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011953 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011954 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011955 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011956 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011957 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011958 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011959 llvm_unreachable("Clause is not allowed.");
11960 }
11961 return Res;
11962}
11963
Alexey Bataev6402bca2015-12-28 07:25:51 +000011964static std::string
11965getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11966 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011967 SmallString<256> Buffer;
11968 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011969 unsigned Skipped = Exclude.size();
11970 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011971 for (unsigned I = First; I < Last; ++I) {
11972 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011973 --Skipped;
11974 continue;
11975 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011976 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
Alexey Bataev87a004d2020-01-02 09:26:32 -050011977 if (I + Skipped + 2 == Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000011978 Out << " or ";
Alexey Bataev87a004d2020-01-02 09:26:32 -050011979 else if (I + Skipped + 1 != Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000011980 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011981 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011982 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011983}
11984
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011985OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11986 SourceLocation KindKwLoc,
11987 SourceLocation StartLoc,
11988 SourceLocation LParenLoc,
11989 SourceLocation EndLoc) {
11990 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011991 static_assert(OMPC_DEFAULT_unknown > 0,
11992 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011993 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011994 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11995 /*Last=*/OMPC_DEFAULT_unknown)
11996 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011997 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011998 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011999 switch (Kind) {
12000 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012001 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012002 break;
12003 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012004 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012005 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012006 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012007 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000012008 break;
12009 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012010 return new (Context)
12011 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012012}
12013
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012014OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012015 SourceLocation KindKwLoc,
12016 SourceLocation StartLoc,
12017 SourceLocation LParenLoc,
12018 SourceLocation EndLoc) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012019 if (Kind == OMP_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012020 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012021 << getListOfPossibleValues(OMPC_proc_bind,
12022 /*First=*/unsigned(OMP_PROC_BIND_master),
12023 /*Last=*/5)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012024 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012025 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012026 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012027 return new (Context)
12028 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012029}
12030
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012031OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12032 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12033 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12034 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12035 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12036 << getListOfPossibleValues(
12037 OMPC_atomic_default_mem_order, /*First=*/0,
12038 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12039 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12040 return nullptr;
12041 }
12042 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12043 LParenLoc, EndLoc);
12044}
12045
Alexey Bataev56dafe82014-06-20 07:16:17 +000012046OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012047 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012048 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012049 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012050 SourceLocation EndLoc) {
12051 OMPClause *Res = nullptr;
12052 switch (Kind) {
12053 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012054 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12055 assert(Argument.size() == NumberOfElements &&
12056 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012057 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012058 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12059 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12060 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12061 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12062 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012063 break;
12064 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012065 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12066 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12067 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12068 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000012069 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012070 case OMPC_dist_schedule:
12071 Res = ActOnOpenMPDistScheduleClause(
12072 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12073 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12074 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012075 case OMPC_defaultmap:
12076 enum { Modifier, DefaultmapKind };
12077 Res = ActOnOpenMPDefaultmapClause(
12078 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12079 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000012080 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12081 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012082 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000012083 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012084 case OMPC_num_threads:
12085 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012086 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012087 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012088 case OMPC_collapse:
12089 case OMPC_default:
12090 case OMPC_proc_bind:
12091 case OMPC_private:
12092 case OMPC_firstprivate:
12093 case OMPC_lastprivate:
12094 case OMPC_shared:
12095 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012096 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012097 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012098 case OMPC_linear:
12099 case OMPC_aligned:
12100 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012101 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012102 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012103 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012104 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012105 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012106 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012107 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012108 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012109 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012110 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012111 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012112 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012113 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012114 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012115 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012116 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012117 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012118 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012119 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012120 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012121 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012122 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012123 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012124 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012125 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012126 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012127 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012128 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012129 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012130 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012131 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012132 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012133 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012134 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012135 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012136 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012137 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012138 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012139 case OMPC_nontemporal:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012140 llvm_unreachable("Clause is not allowed.");
12141 }
12142 return Res;
12143}
12144
Alexey Bataev6402bca2015-12-28 07:25:51 +000012145static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12146 OpenMPScheduleClauseModifier M2,
12147 SourceLocation M1Loc, SourceLocation M2Loc) {
12148 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12149 SmallVector<unsigned, 2> Excluded;
12150 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12151 Excluded.push_back(M2);
12152 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12153 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12154 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12155 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12156 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12157 << getListOfPossibleValues(OMPC_schedule,
12158 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12159 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12160 Excluded)
12161 << getOpenMPClauseName(OMPC_schedule);
12162 return true;
12163 }
12164 return false;
12165}
12166
Alexey Bataev56dafe82014-06-20 07:16:17 +000012167OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012168 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012169 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012170 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12171 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12172 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12173 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12174 return nullptr;
12175 // OpenMP, 2.7.1, Loop Construct, Restrictions
12176 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12177 // but not both.
12178 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12179 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12180 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12181 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12182 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12183 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12184 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12185 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12186 return nullptr;
12187 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012188 if (Kind == OMPC_SCHEDULE_unknown) {
12189 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012190 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12191 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12192 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12193 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12194 Exclude);
12195 } else {
12196 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12197 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012198 }
12199 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12200 << Values << getOpenMPClauseName(OMPC_schedule);
12201 return nullptr;
12202 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012203 // OpenMP, 2.7.1, Loop Construct, Restrictions
12204 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12205 // schedule(guided).
12206 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12207 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12208 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12209 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12210 diag::err_omp_schedule_nonmonotonic_static);
12211 return nullptr;
12212 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012213 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012214 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012215 if (ChunkSize) {
12216 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12217 !ChunkSize->isInstantiationDependent() &&
12218 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012219 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012220 ExprResult Val =
12221 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12222 if (Val.isInvalid())
12223 return nullptr;
12224
12225 ValExpr = Val.get();
12226
12227 // OpenMP [2.7.1, Restrictions]
12228 // chunk_size must be a loop invariant integer expression with a positive
12229 // value.
12230 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012231 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12232 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12233 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012234 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012235 return nullptr;
12236 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012237 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012238 DSAStack->getCurrentDirective(), OMPC_schedule,
12239 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012240 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012241 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012242 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012243 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12244 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012245 }
12246 }
12247 }
12248
Alexey Bataev6402bca2015-12-28 07:25:51 +000012249 return new (Context)
12250 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012251 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012252}
12253
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012254OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12255 SourceLocation StartLoc,
12256 SourceLocation EndLoc) {
12257 OMPClause *Res = nullptr;
12258 switch (Kind) {
12259 case OMPC_ordered:
12260 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12261 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012262 case OMPC_nowait:
12263 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12264 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012265 case OMPC_untied:
12266 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12267 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012268 case OMPC_mergeable:
12269 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12270 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012271 case OMPC_read:
12272 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12273 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012274 case OMPC_write:
12275 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12276 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012277 case OMPC_update:
12278 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12279 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012280 case OMPC_capture:
12281 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12282 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012283 case OMPC_seq_cst:
12284 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12285 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012286 case OMPC_threads:
12287 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12288 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012289 case OMPC_simd:
12290 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12291 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012292 case OMPC_nogroup:
12293 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12294 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012295 case OMPC_unified_address:
12296 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12297 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012298 case OMPC_unified_shared_memory:
12299 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12300 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012301 case OMPC_reverse_offload:
12302 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12303 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012304 case OMPC_dynamic_allocators:
12305 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12306 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012307 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012308 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012309 case OMPC_num_threads:
12310 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012311 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012312 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012313 case OMPC_collapse:
12314 case OMPC_schedule:
12315 case OMPC_private:
12316 case OMPC_firstprivate:
12317 case OMPC_lastprivate:
12318 case OMPC_shared:
12319 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012320 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012321 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012322 case OMPC_linear:
12323 case OMPC_aligned:
12324 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012325 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012326 case OMPC_default:
12327 case OMPC_proc_bind:
12328 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012329 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012330 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012331 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012332 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012333 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012334 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012335 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012336 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012337 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012338 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012339 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012340 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012341 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012342 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012343 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012344 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012345 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012346 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012347 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012348 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012349 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012350 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012351 case OMPC_nontemporal:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012352 llvm_unreachable("Clause is not allowed.");
12353 }
12354 return Res;
12355}
12356
Alexey Bataev236070f2014-06-20 11:19:47 +000012357OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12358 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012359 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012360 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12361}
12362
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012363OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12364 SourceLocation EndLoc) {
12365 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12366}
12367
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012368OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12369 SourceLocation EndLoc) {
12370 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12371}
12372
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012373OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12374 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012375 return new (Context) OMPReadClause(StartLoc, EndLoc);
12376}
12377
Alexey Bataevdea47612014-07-23 07:46:59 +000012378OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12379 SourceLocation EndLoc) {
12380 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12381}
12382
Alexey Bataev67a4f222014-07-23 10:25:33 +000012383OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12384 SourceLocation EndLoc) {
12385 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12386}
12387
Alexey Bataev459dec02014-07-24 06:46:57 +000012388OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12389 SourceLocation EndLoc) {
12390 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12391}
12392
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012393OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12394 SourceLocation EndLoc) {
12395 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12396}
12397
Alexey Bataev346265e2015-09-25 10:37:12 +000012398OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12399 SourceLocation EndLoc) {
12400 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12401}
12402
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012403OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12404 SourceLocation EndLoc) {
12405 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12406}
12407
Alexey Bataevb825de12015-12-07 10:51:44 +000012408OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12409 SourceLocation EndLoc) {
12410 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12411}
12412
Kelvin Li1408f912018-09-26 04:28:39 +000012413OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12414 SourceLocation EndLoc) {
12415 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12416}
12417
Patrick Lyster4a370b92018-10-01 13:47:43 +000012418OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12419 SourceLocation EndLoc) {
12420 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12421}
12422
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012423OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12424 SourceLocation EndLoc) {
12425 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12426}
12427
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012428OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12429 SourceLocation EndLoc) {
12430 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12431}
12432
Alexey Bataevc5e02582014-06-16 07:08:35 +000012433OMPClause *Sema::ActOnOpenMPVarListClause(
12434 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012435 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12436 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012437 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
Kelvin Lief579432018-12-18 22:18:41 +000012438 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012439 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
12440 SourceLocation DepLinMapLastLoc) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012441 SourceLocation StartLoc = Locs.StartLoc;
12442 SourceLocation LParenLoc = Locs.LParenLoc;
12443 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012444 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012445 switch (Kind) {
12446 case OMPC_private:
12447 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12448 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012449 case OMPC_firstprivate:
12450 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12451 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012452 case OMPC_lastprivate:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012453 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
12454 "Unexpected lastprivate modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012455 Res = ActOnOpenMPLastprivateClause(
12456 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
12457 DepLinMapLastLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012458 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012459 case OMPC_shared:
12460 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12461 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012462 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012463 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012464 EndLoc, ReductionOrMapperIdScopeSpec,
12465 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012466 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012467 case OMPC_task_reduction:
12468 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012469 EndLoc, ReductionOrMapperIdScopeSpec,
12470 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012471 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012472 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012473 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12474 EndLoc, ReductionOrMapperIdScopeSpec,
12475 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012476 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012477 case OMPC_linear:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012478 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
12479 "Unexpected linear modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012480 Res = ActOnOpenMPLinearClause(
12481 VarList, TailExpr, StartLoc, LParenLoc,
12482 static_cast<OpenMPLinearClauseKind>(ExtraModifier), DepLinMapLastLoc,
12483 ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012484 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012485 case OMPC_aligned:
12486 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12487 ColonLoc, EndLoc);
12488 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012489 case OMPC_copyin:
12490 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12491 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012492 case OMPC_copyprivate:
12493 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12494 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012495 case OMPC_flush:
12496 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12497 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012498 case OMPC_depend:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012499 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
12500 "Unexpected depend modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012501 Res = ActOnOpenMPDependClause(
12502 static_cast<OpenMPDependClauseKind>(ExtraModifier), DepLinMapLastLoc,
12503 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012504 break;
12505 case OMPC_map:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012506 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
12507 "Unexpected map modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012508 Res = ActOnOpenMPMapClause(
12509 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
12510 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
12511 IsMapTypeImplicit, DepLinMapLastLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012512 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012513 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012514 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12515 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012516 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012517 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012518 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12519 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012520 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012521 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012522 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012523 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012524 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012525 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012526 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012527 case OMPC_allocate:
12528 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12529 ColonLoc, EndLoc);
12530 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012531 case OMPC_nontemporal:
12532 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12533 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012534 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012535 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012536 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012537 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012538 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012539 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012540 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012541 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012542 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012543 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012544 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012545 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012546 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012547 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012548 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012549 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012550 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012551 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012552 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012553 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012554 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012555 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012556 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012557 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012558 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012559 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012560 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012561 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012562 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012563 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012564 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012565 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012566 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012567 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012568 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012569 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012570 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012571 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012572 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012573 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012574 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012575 llvm_unreachable("Clause is not allowed.");
12576 }
12577 return Res;
12578}
12579
Alexey Bataev90c228f2016-02-08 09:29:13 +000012580ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012581 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012582 ExprResult Res = BuildDeclRefExpr(
12583 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12584 if (!Res.isUsable())
12585 return ExprError();
12586 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12587 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12588 if (!Res.isUsable())
12589 return ExprError();
12590 }
12591 if (VK != VK_LValue && Res.get()->isGLValue()) {
12592 Res = DefaultLvalueConversion(Res.get());
12593 if (!Res.isUsable())
12594 return ExprError();
12595 }
12596 return Res;
12597}
12598
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012599OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12600 SourceLocation StartLoc,
12601 SourceLocation LParenLoc,
12602 SourceLocation EndLoc) {
12603 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012604 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012605 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012606 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012607 SourceLocation ELoc;
12608 SourceRange ERange;
12609 Expr *SimpleRefExpr = RefExpr;
12610 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012611 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012612 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012613 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012614 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012615 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012616 ValueDecl *D = Res.first;
12617 if (!D)
12618 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012619
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012620 QualType Type = D->getType();
12621 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012622
12623 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12624 // A variable that appears in a private clause must not have an incomplete
12625 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012626 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012627 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012628 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012629
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012630 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12631 // A variable that is privatized must not have a const-qualified type
12632 // unless it is of class type with a mutable member. This restriction does
12633 // not apply to the firstprivate clause.
12634 //
12635 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12636 // A variable that appears in a private clause must not have a
12637 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012638 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012639 continue;
12640
Alexey Bataev758e55e2013-09-06 18:03:48 +000012641 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12642 // in a Construct]
12643 // Variables with the predetermined data-sharing attributes may not be
12644 // listed in data-sharing attributes clauses, except for the cases
12645 // listed below. For these exceptions only, listing a predetermined
12646 // variable in a data-sharing attribute clause is allowed and overrides
12647 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012648 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012649 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012650 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12651 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012652 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012653 continue;
12654 }
12655
Alexey Bataeve3727102018-04-18 15:57:46 +000012656 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012657 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012658 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012659 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012660 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12661 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012662 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012663 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012664 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012665 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012666 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012667 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012668 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012669 continue;
12670 }
12671
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012672 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12673 // A list item cannot appear in both a map clause and a data-sharing
12674 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012675 //
12676 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12677 // A list item cannot appear in both a map clause and a data-sharing
12678 // attribute clause on the same construct unless the construct is a
12679 // combined construct.
12680 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12681 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012682 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012683 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012684 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012685 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12686 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12687 ConflictKind = WhereFoundClauseKind;
12688 return true;
12689 })) {
12690 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012691 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012692 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012693 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012694 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012695 continue;
12696 }
12697 }
12698
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012699 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12700 // A variable of class type (or array thereof) that appears in a private
12701 // clause requires an accessible, unambiguous default constructor for the
12702 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012703 // Generate helper private variable and initialize it with the default
12704 // value. The address of the original variable is replaced by the address of
12705 // the new private variable in CodeGen. This new variable is not added to
12706 // IdResolver, so the code in the OpenMP region uses original variable for
12707 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012708 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012709 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012710 buildVarDecl(*this, ELoc, Type, D->getName(),
12711 D->hasAttrs() ? &D->getAttrs() : nullptr,
12712 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012713 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012714 if (VDPrivate->isInvalidDecl())
12715 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012716 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012717 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012718
Alexey Bataev90c228f2016-02-08 09:29:13 +000012719 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012720 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012721 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012722 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012723 Vars.push_back((VD || CurContext->isDependentContext())
12724 ? RefExpr->IgnoreParens()
12725 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012726 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012727 }
12728
Alexey Bataeved09d242014-05-28 05:53:51 +000012729 if (Vars.empty())
12730 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012731
Alexey Bataev03b340a2014-10-21 03:16:40 +000012732 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12733 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012734}
12735
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012736namespace {
12737class DiagsUninitializedSeveretyRAII {
12738private:
12739 DiagnosticsEngine &Diags;
12740 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012741 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012742
12743public:
12744 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12745 bool IsIgnored)
12746 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12747 if (!IsIgnored) {
12748 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12749 /*Map*/ diag::Severity::Ignored, Loc);
12750 }
12751 }
12752 ~DiagsUninitializedSeveretyRAII() {
12753 if (!IsIgnored)
12754 Diags.popMappings(SavedLoc);
12755 }
12756};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012757}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012758
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012759OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12760 SourceLocation StartLoc,
12761 SourceLocation LParenLoc,
12762 SourceLocation EndLoc) {
12763 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012764 SmallVector<Expr *, 8> PrivateCopies;
12765 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012766 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012767 bool IsImplicitClause =
12768 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012769 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012770
Alexey Bataeve3727102018-04-18 15:57:46 +000012771 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012772 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012773 SourceLocation ELoc;
12774 SourceRange ERange;
12775 Expr *SimpleRefExpr = RefExpr;
12776 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012777 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012778 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012779 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012780 PrivateCopies.push_back(nullptr);
12781 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012782 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012783 ValueDecl *D = Res.first;
12784 if (!D)
12785 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012786
Alexey Bataev60da77e2016-02-29 05:54:20 +000012787 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012788 QualType Type = D->getType();
12789 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012790
12791 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12792 // A variable that appears in a private clause must not have an incomplete
12793 // type or a reference type.
12794 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012795 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012796 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012797 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012798
12799 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12800 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012801 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012802 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012803 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012804
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012805 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012806 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012807 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012808 DSAStackTy::DSAVarData DVar =
12809 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012810 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012811 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012812 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012813 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12814 // A list item that specifies a given variable may not appear in more
12815 // than one clause on the same directive, except that a variable may be
12816 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012817 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12818 // A list item may appear in a firstprivate or lastprivate clause but not
12819 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012820 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012821 (isOpenMPDistributeDirective(CurrDir) ||
12822 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012823 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012824 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012825 << getOpenMPClauseName(DVar.CKind)
12826 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012827 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012828 continue;
12829 }
12830
12831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12832 // in a Construct]
12833 // Variables with the predetermined data-sharing attributes may not be
12834 // listed in data-sharing attributes clauses, except for the cases
12835 // listed below. For these exceptions only, listing a predetermined
12836 // variable in a data-sharing attribute clause is allowed and overrides
12837 // the variable's predetermined data-sharing attributes.
12838 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12839 // in a Construct, C/C++, p.2]
12840 // Variables with const-qualified type having no mutable member may be
12841 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012842 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012843 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12844 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012845 << getOpenMPClauseName(DVar.CKind)
12846 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012847 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012848 continue;
12849 }
12850
12851 // OpenMP [2.9.3.4, Restrictions, p.2]
12852 // A list item that is private within a parallel region must not appear
12853 // in a firstprivate clause on a worksharing construct if any of the
12854 // worksharing regions arising from the worksharing construct ever bind
12855 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012856 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12857 // A list item that is private within a teams region must not appear in a
12858 // firstprivate clause on a distribute construct if any of the distribute
12859 // regions arising from the distribute construct ever bind to any of the
12860 // teams regions arising from the teams construct.
12861 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12862 // A list item that appears in a reduction clause of a teams construct
12863 // must not appear in a firstprivate clause on a distribute construct if
12864 // any of the distribute regions arising from the distribute construct
12865 // ever bind to any of the teams regions arising from the teams construct.
12866 if ((isOpenMPWorksharingDirective(CurrDir) ||
12867 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012868 !isOpenMPParallelDirective(CurrDir) &&
12869 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012870 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012871 if (DVar.CKind != OMPC_shared &&
12872 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012873 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012874 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012875 Diag(ELoc, diag::err_omp_required_access)
12876 << getOpenMPClauseName(OMPC_firstprivate)
12877 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012878 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012879 continue;
12880 }
12881 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012882 // OpenMP [2.9.3.4, Restrictions, p.3]
12883 // A list item that appears in a reduction clause of a parallel construct
12884 // must not appear in a firstprivate clause on a worksharing or task
12885 // construct if any of the worksharing or task regions arising from the
12886 // worksharing or task construct ever bind to any of the parallel regions
12887 // arising from the parallel construct.
12888 // OpenMP [2.9.3.4, Restrictions, p.4]
12889 // A list item that appears in a reduction clause in worksharing
12890 // construct must not appear in a firstprivate clause in a task construct
12891 // encountered during execution of any of the worksharing regions arising
12892 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012893 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012894 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012895 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12896 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012897 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012898 isOpenMPWorksharingDirective(K) ||
12899 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012900 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012901 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012902 if (DVar.CKind == OMPC_reduction &&
12903 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012904 isOpenMPWorksharingDirective(DVar.DKind) ||
12905 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012906 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12907 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012908 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012909 continue;
12910 }
12911 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012912
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012913 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12914 // A list item cannot appear in both a map clause and a data-sharing
12915 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012916 //
12917 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12918 // A list item cannot appear in both a map clause and a data-sharing
12919 // attribute clause on the same construct unless the construct is a
12920 // combined construct.
12921 if ((LangOpts.OpenMP <= 45 &&
12922 isOpenMPTargetExecutionDirective(CurrDir)) ||
12923 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012924 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012925 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012926 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012927 [&ConflictKind](
12928 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12929 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012930 ConflictKind = WhereFoundClauseKind;
12931 return true;
12932 })) {
12933 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012934 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012935 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012936 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012937 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012938 continue;
12939 }
12940 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012941 }
12942
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012943 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012944 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012945 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012946 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12947 << getOpenMPClauseName(OMPC_firstprivate) << Type
12948 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12949 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012950 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012951 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012952 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012953 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012954 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012955 continue;
12956 }
12957
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012958 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012959 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012960 buildVarDecl(*this, ELoc, Type, D->getName(),
12961 D->hasAttrs() ? &D->getAttrs() : nullptr,
12962 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012963 // Generate helper private variable and initialize it with the value of the
12964 // original variable. The address of the original variable is replaced by
12965 // the address of the new private variable in the CodeGen. This new variable
12966 // is not added to IdResolver, so the code in the OpenMP region uses
12967 // original variable for proper diagnostics and variable capturing.
12968 Expr *VDInitRefExpr = nullptr;
12969 // For arrays generate initializer for single element and replace it by the
12970 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012971 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012972 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012973 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012974 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012975 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012976 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012977 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12978 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012979 InitializedEntity Entity =
12980 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012981 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12982
12983 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12984 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12985 if (Result.isInvalid())
12986 VDPrivate->setInvalidDecl();
12987 else
12988 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012989 // Remove temp variable declaration.
12990 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012991 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012992 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12993 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012994 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12995 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012996 AddInitializerToDecl(VDPrivate,
12997 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012998 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012999 }
13000 if (VDPrivate->isInvalidDecl()) {
13001 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000013002 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013003 diag::note_omp_task_predetermined_firstprivate_here);
13004 }
13005 continue;
13006 }
13007 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013008 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000013009 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
13010 RefExpr->getExprLoc());
13011 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013012 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013013 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013014 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013015 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013016 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013017 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013018 ExprCaptures.push_back(Ref->getDecl());
13019 }
Alexey Bataev417089f2016-02-17 13:19:37 +000013020 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000013021 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013022 Vars.push_back((VD || CurContext->isDependentContext())
13023 ? RefExpr->IgnoreParens()
13024 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013025 PrivateCopies.push_back(VDPrivateRefExpr);
13026 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013027 }
13028
Alexey Bataeved09d242014-05-28 05:53:51 +000013029 if (Vars.empty())
13030 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013031
13032 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013033 Vars, PrivateCopies, Inits,
13034 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013035}
13036
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013037OMPClause *Sema::ActOnOpenMPLastprivateClause(
13038 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13039 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13040 SourceLocation LParenLoc, SourceLocation EndLoc) {
13041 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13042 assert(ColonLoc.isValid() && "Colon location must be valid.");
13043 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13044 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13045 /*Last=*/OMPC_LASTPRIVATE_unknown)
13046 << getOpenMPClauseName(OMPC_lastprivate);
13047 return nullptr;
13048 }
13049
Alexander Musman1bb328c2014-06-04 13:06:39 +000013050 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000013051 SmallVector<Expr *, 8> SrcExprs;
13052 SmallVector<Expr *, 8> DstExprs;
13053 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013054 SmallVector<Decl *, 4> ExprCaptures;
13055 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013056 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013057 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013058 SourceLocation ELoc;
13059 SourceRange ERange;
13060 Expr *SimpleRefExpr = RefExpr;
13061 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013062 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013063 // It will be analyzed later.
13064 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013065 SrcExprs.push_back(nullptr);
13066 DstExprs.push_back(nullptr);
13067 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013068 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013069 ValueDecl *D = Res.first;
13070 if (!D)
13071 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013072
Alexey Bataev74caaf22016-02-20 04:09:36 +000013073 QualType Type = D->getType();
13074 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013075
13076 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13077 // A variable that appears in a lastprivate clause must not have an
13078 // incomplete type or a reference type.
13079 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013080 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013081 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013082 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013083
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013084 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13085 // A variable that is privatized must not have a const-qualified type
13086 // unless it is of class type with a mutable member. This restriction does
13087 // not apply to the firstprivate clause.
13088 //
13089 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13090 // A variable that appears in a lastprivate clause must not have a
13091 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013092 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013093 continue;
13094
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013095 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
13096 // A list item that appears in a lastprivate clause with the conditional
13097 // modifier must be a scalar variable.
13098 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
13099 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
13100 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13101 VarDecl::DeclarationOnly;
13102 Diag(D->getLocation(),
13103 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13104 << D;
13105 continue;
13106 }
13107
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013108 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013109 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13110 // in a Construct]
13111 // Variables with the predetermined data-sharing attributes may not be
13112 // listed in data-sharing attributes clauses, except for the cases
13113 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013114 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13115 // A list item may appear in a firstprivate or lastprivate clause but not
13116 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013117 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013118 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013119 (isOpenMPDistributeDirective(CurrDir) ||
13120 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013121 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13122 Diag(ELoc, diag::err_omp_wrong_dsa)
13123 << getOpenMPClauseName(DVar.CKind)
13124 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013125 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013126 continue;
13127 }
13128
Alexey Bataevf29276e2014-06-18 04:14:57 +000013129 // OpenMP [2.14.3.5, Restrictions, p.2]
13130 // A list item that is private within a parallel region, or that appears in
13131 // the reduction clause of a parallel construct, must not appear in a
13132 // lastprivate clause on a worksharing construct if any of the corresponding
13133 // worksharing regions ever binds to any of the corresponding parallel
13134 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013135 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013136 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013137 !isOpenMPParallelDirective(CurrDir) &&
13138 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013139 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013140 if (DVar.CKind != OMPC_shared) {
13141 Diag(ELoc, diag::err_omp_required_access)
13142 << getOpenMPClauseName(OMPC_lastprivate)
13143 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013144 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013145 continue;
13146 }
13147 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013148
Alexander Musman1bb328c2014-06-04 13:06:39 +000013149 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013150 // A variable of class type (or array thereof) that appears in a
13151 // lastprivate clause requires an accessible, unambiguous default
13152 // constructor for the class type, unless the list item is also specified
13153 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013154 // A variable of class type (or array thereof) that appears in a
13155 // lastprivate clause requires an accessible, unambiguous copy assignment
13156 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013157 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013158 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13159 Type.getUnqualifiedType(), ".lastprivate.src",
13160 D->hasAttrs() ? &D->getAttrs() : nullptr);
13161 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013162 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013163 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013164 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013165 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013166 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013167 // For arrays generate assignment operation for single element and replace
13168 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013169 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13170 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013171 if (AssignmentOp.isInvalid())
13172 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013173 AssignmentOp =
13174 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013175 if (AssignmentOp.isInvalid())
13176 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013177
Alexey Bataev74caaf22016-02-20 04:09:36 +000013178 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013179 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013180 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013181 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013182 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013183 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013184 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013185 ExprCaptures.push_back(Ref->getDecl());
13186 }
13187 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013188 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013189 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013190 ExprResult RefRes = DefaultLvalueConversion(Ref);
13191 if (!RefRes.isUsable())
13192 continue;
13193 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013194 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13195 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013196 if (!PostUpdateRes.isUsable())
13197 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013198 ExprPostUpdates.push_back(
13199 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013200 }
13201 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013202 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013203 Vars.push_back((VD || CurContext->isDependentContext())
13204 ? RefExpr->IgnoreParens()
13205 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013206 SrcExprs.push_back(PseudoSrcExpr);
13207 DstExprs.push_back(PseudoDstExpr);
13208 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013209 }
13210
13211 if (Vars.empty())
13212 return nullptr;
13213
13214 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013215 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013216 LPKind, LPKindLoc, ColonLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013217 buildPreInits(Context, ExprCaptures),
13218 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013219}
13220
Alexey Bataev758e55e2013-09-06 18:03:48 +000013221OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13222 SourceLocation StartLoc,
13223 SourceLocation LParenLoc,
13224 SourceLocation EndLoc) {
13225 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013226 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013227 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013228 SourceLocation ELoc;
13229 SourceRange ERange;
13230 Expr *SimpleRefExpr = RefExpr;
13231 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013232 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013233 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013234 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013235 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013236 ValueDecl *D = Res.first;
13237 if (!D)
13238 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013239
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013240 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013241 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13242 // in a Construct]
13243 // Variables with the predetermined data-sharing attributes may not be
13244 // listed in data-sharing attributes clauses, except for the cases
13245 // listed below. For these exceptions only, listing a predetermined
13246 // variable in a data-sharing attribute clause is allowed and overrides
13247 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013248 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013249 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13250 DVar.RefExpr) {
13251 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13252 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013253 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013254 continue;
13255 }
13256
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013257 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013258 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013259 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013260 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013261 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13262 ? RefExpr->IgnoreParens()
13263 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013264 }
13265
Alexey Bataeved09d242014-05-28 05:53:51 +000013266 if (Vars.empty())
13267 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013268
13269 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13270}
13271
Alexey Bataevc5e02582014-06-16 07:08:35 +000013272namespace {
13273class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13274 DSAStackTy *Stack;
13275
13276public:
13277 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013278 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13279 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013280 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13281 return false;
13282 if (DVar.CKind != OMPC_unknown)
13283 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013284 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013285 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013286 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013287 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013288 }
13289 return false;
13290 }
13291 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013292 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013293 if (Child && Visit(Child))
13294 return true;
13295 }
13296 return false;
13297 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013298 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013299};
Alexey Bataev23b69422014-06-18 07:08:49 +000013300} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013301
Alexey Bataev60da77e2016-02-29 05:54:20 +000013302namespace {
13303// Transform MemberExpression for specified FieldDecl of current class to
13304// DeclRefExpr to specified OMPCapturedExprDecl.
13305class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13306 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013307 ValueDecl *Field = nullptr;
13308 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013309
13310public:
13311 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13312 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13313
13314 ExprResult TransformMemberExpr(MemberExpr *E) {
13315 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13316 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013317 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013318 return CapturedExpr;
13319 }
13320 return BaseTransform::TransformMemberExpr(E);
13321 }
13322 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13323};
13324} // namespace
13325
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013326template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013327static T filterLookupForUDReductionAndMapper(
13328 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013329 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013330 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013331 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013332 return Res;
13333 }
13334 }
13335 return T();
13336}
13337
Alexey Bataev43b90b72018-09-12 16:31:59 +000013338static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13339 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13340
13341 for (auto RD : D->redecls()) {
13342 // Don't bother with extra checks if we already know this one isn't visible.
13343 if (RD == D)
13344 continue;
13345
13346 auto ND = cast<NamedDecl>(RD);
13347 if (LookupResult::isVisible(SemaRef, ND))
13348 return ND;
13349 }
13350
13351 return nullptr;
13352}
13353
13354static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013355argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013356 SourceLocation Loc, QualType Ty,
13357 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13358 // Find all of the associated namespaces and classes based on the
13359 // arguments we have.
13360 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13361 Sema::AssociatedClassSet AssociatedClasses;
13362 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13363 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13364 AssociatedClasses);
13365
13366 // C++ [basic.lookup.argdep]p3:
13367 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13368 // and let Y be the lookup set produced by argument dependent
13369 // lookup (defined as follows). If X contains [...] then Y is
13370 // empty. Otherwise Y is the set of declarations found in the
13371 // namespaces associated with the argument types as described
13372 // below. The set of declarations found by the lookup of the name
13373 // is the union of X and Y.
13374 //
13375 // Here, we compute Y and add its members to the overloaded
13376 // candidate set.
13377 for (auto *NS : AssociatedNamespaces) {
13378 // When considering an associated namespace, the lookup is the
13379 // same as the lookup performed when the associated namespace is
13380 // used as a qualifier (3.4.3.2) except that:
13381 //
13382 // -- Any using-directives in the associated namespace are
13383 // ignored.
13384 //
13385 // -- Any namespace-scope friend functions declared in
13386 // associated classes are visible within their respective
13387 // namespaces even if they are not visible during an ordinary
13388 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013389 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013390 for (auto *D : R) {
13391 auto *Underlying = D;
13392 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13393 Underlying = USD->getTargetDecl();
13394
Michael Kruse4304e9d2019-02-19 16:38:20 +000013395 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13396 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013397 continue;
13398
13399 if (!SemaRef.isVisible(D)) {
13400 D = findAcceptableDecl(SemaRef, D);
13401 if (!D)
13402 continue;
13403 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13404 Underlying = USD->getTargetDecl();
13405 }
13406 Lookups.emplace_back();
13407 Lookups.back().addDecl(Underlying);
13408 }
13409 }
13410}
13411
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013412static ExprResult
13413buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13414 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13415 const DeclarationNameInfo &ReductionId, QualType Ty,
13416 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13417 if (ReductionIdScopeSpec.isInvalid())
13418 return ExprError();
13419 SmallVector<UnresolvedSet<8>, 4> Lookups;
13420 if (S) {
13421 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13422 Lookup.suppressDiagnostics();
13423 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013424 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013425 do {
13426 S = S->getParent();
13427 } while (S && !S->isDeclScope(D));
13428 if (S)
13429 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013430 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013431 Lookups.back().append(Lookup.begin(), Lookup.end());
13432 Lookup.clear();
13433 }
13434 } else if (auto *ULE =
13435 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13436 Lookups.push_back(UnresolvedSet<8>());
13437 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013438 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013439 if (D == PrevD)
13440 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013441 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013442 Lookups.back().addDecl(DRD);
13443 PrevD = D;
13444 }
13445 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013446 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13447 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013448 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013449 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013450 return !D->isInvalidDecl() &&
13451 (D->getType()->isDependentType() ||
13452 D->getType()->isInstantiationDependentType() ||
13453 D->getType()->containsUnexpandedParameterPack());
13454 })) {
13455 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013456 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013457 if (Set.empty())
13458 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013459 ResSet.append(Set.begin(), Set.end());
13460 // The last item marks the end of all declarations at the specified scope.
13461 ResSet.addDecl(Set[Set.size() - 1]);
13462 }
13463 return UnresolvedLookupExpr::Create(
13464 SemaRef.Context, /*NamingClass=*/nullptr,
13465 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13466 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13467 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013468 // Lookup inside the classes.
13469 // C++ [over.match.oper]p3:
13470 // For a unary operator @ with an operand of a type whose
13471 // cv-unqualified version is T1, and for a binary operator @ with
13472 // a left operand of a type whose cv-unqualified version is T1 and
13473 // a right operand of a type whose cv-unqualified version is T2,
13474 // three sets of candidate functions, designated member
13475 // candidates, non-member candidates and built-in candidates, are
13476 // constructed as follows:
13477 // -- If T1 is a complete class type or a class currently being
13478 // defined, the set of member candidates is the result of the
13479 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13480 // the set of member candidates is empty.
13481 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13482 Lookup.suppressDiagnostics();
13483 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13484 // Complete the type if it can be completed.
13485 // If the type is neither complete nor being defined, bail out now.
13486 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13487 TyRec->getDecl()->getDefinition()) {
13488 Lookup.clear();
13489 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13490 if (Lookup.empty()) {
13491 Lookups.emplace_back();
13492 Lookups.back().append(Lookup.begin(), Lookup.end());
13493 }
13494 }
13495 }
13496 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013497 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013498 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013499 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13500 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13501 if (!D->isInvalidDecl() &&
13502 SemaRef.Context.hasSameType(D->getType(), Ty))
13503 return D;
13504 return nullptr;
13505 }))
13506 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13507 VK_LValue, Loc);
13508 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013509 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13510 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13511 if (!D->isInvalidDecl() &&
13512 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13513 !Ty.isMoreQualifiedThan(D->getType()))
13514 return D;
13515 return nullptr;
13516 })) {
13517 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13518 /*DetectVirtual=*/false);
13519 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13520 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13521 VD->getType().getUnqualifiedType()))) {
13522 if (SemaRef.CheckBaseClassAccess(
13523 Loc, VD->getType(), Ty, Paths.front(),
13524 /*DiagID=*/0) != Sema::AR_inaccessible) {
13525 SemaRef.BuildBasePathArray(Paths, BasePath);
13526 return SemaRef.BuildDeclRefExpr(
13527 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13528 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013529 }
13530 }
13531 }
13532 }
13533 if (ReductionIdScopeSpec.isSet()) {
Alexey Bataevadd743b2020-01-03 11:58:16 -050013534 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
13535 << Ty << Range;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013536 return ExprError();
13537 }
13538 return ExprEmpty();
13539}
13540
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013541namespace {
13542/// Data for the reduction-based clauses.
13543struct ReductionData {
13544 /// List of original reduction items.
13545 SmallVector<Expr *, 8> Vars;
13546 /// List of private copies of the reduction items.
13547 SmallVector<Expr *, 8> Privates;
13548 /// LHS expressions for the reduction_op expressions.
13549 SmallVector<Expr *, 8> LHSs;
13550 /// RHS expressions for the reduction_op expressions.
13551 SmallVector<Expr *, 8> RHSs;
13552 /// Reduction operation expression.
13553 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013554 /// Taskgroup descriptors for the corresponding reduction items in
13555 /// in_reduction clauses.
13556 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013557 /// List of captures for clause.
13558 SmallVector<Decl *, 4> ExprCaptures;
13559 /// List of postupdate expressions.
13560 SmallVector<Expr *, 4> ExprPostUpdates;
13561 ReductionData() = delete;
13562 /// Reserves required memory for the reduction data.
13563 ReductionData(unsigned Size) {
13564 Vars.reserve(Size);
13565 Privates.reserve(Size);
13566 LHSs.reserve(Size);
13567 RHSs.reserve(Size);
13568 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013569 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013570 ExprCaptures.reserve(Size);
13571 ExprPostUpdates.reserve(Size);
13572 }
13573 /// Stores reduction item and reduction operation only (required for dependent
13574 /// reduction item).
13575 void push(Expr *Item, Expr *ReductionOp) {
13576 Vars.emplace_back(Item);
13577 Privates.emplace_back(nullptr);
13578 LHSs.emplace_back(nullptr);
13579 RHSs.emplace_back(nullptr);
13580 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013581 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013582 }
13583 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013584 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13585 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013586 Vars.emplace_back(Item);
13587 Privates.emplace_back(Private);
13588 LHSs.emplace_back(LHS);
13589 RHSs.emplace_back(RHS);
13590 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013591 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013592 }
13593};
13594} // namespace
13595
Alexey Bataeve3727102018-04-18 15:57:46 +000013596static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013597 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13598 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13599 const Expr *Length = OASE->getLength();
13600 if (Length == nullptr) {
13601 // For array sections of the form [1:] or [:], we would need to analyze
13602 // the lower bound...
13603 if (OASE->getColonLoc().isValid())
13604 return false;
13605
13606 // This is an array subscript which has implicit length 1!
13607 SingleElement = true;
13608 ArraySizes.push_back(llvm::APSInt::get(1));
13609 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013610 Expr::EvalResult Result;
13611 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013612 return false;
13613
Fangrui Song407659a2018-11-30 23:41:18 +000013614 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013615 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13616 ArraySizes.push_back(ConstantLengthValue);
13617 }
13618
13619 // Get the base of this array section and walk up from there.
13620 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13621
13622 // We require length = 1 for all array sections except the right-most to
13623 // guarantee that the memory region is contiguous and has no holes in it.
13624 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13625 Length = TempOASE->getLength();
13626 if (Length == nullptr) {
13627 // For array sections of the form [1:] or [:], we would need to analyze
13628 // the lower bound...
13629 if (OASE->getColonLoc().isValid())
13630 return false;
13631
13632 // This is an array subscript which has implicit length 1!
13633 ArraySizes.push_back(llvm::APSInt::get(1));
13634 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013635 Expr::EvalResult Result;
13636 if (!Length->EvaluateAsInt(Result, Context))
13637 return false;
13638
13639 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13640 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013641 return false;
13642
13643 ArraySizes.push_back(ConstantLengthValue);
13644 }
13645 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13646 }
13647
13648 // If we have a single element, we don't need to add the implicit lengths.
13649 if (!SingleElement) {
13650 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13651 // Has implicit length 1!
13652 ArraySizes.push_back(llvm::APSInt::get(1));
13653 Base = TempASE->getBase()->IgnoreParenImpCasts();
13654 }
13655 }
13656
13657 // This array section can be privatized as a single value or as a constant
13658 // sized array.
13659 return true;
13660}
13661
Alexey Bataeve3727102018-04-18 15:57:46 +000013662static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013663 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13664 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13665 SourceLocation ColonLoc, SourceLocation EndLoc,
13666 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013667 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013668 DeclarationName DN = ReductionId.getName();
13669 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013670 BinaryOperatorKind BOK = BO_Comma;
13671
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013672 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013673 // OpenMP [2.14.3.6, reduction clause]
13674 // C
13675 // reduction-identifier is either an identifier or one of the following
13676 // operators: +, -, *, &, |, ^, && and ||
13677 // C++
13678 // reduction-identifier is either an id-expression or one of the following
13679 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013680 switch (OOK) {
13681 case OO_Plus:
13682 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013683 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013684 break;
13685 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013686 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013687 break;
13688 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013689 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013690 break;
13691 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013692 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013693 break;
13694 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013695 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013696 break;
13697 case OO_AmpAmp:
13698 BOK = BO_LAnd;
13699 break;
13700 case OO_PipePipe:
13701 BOK = BO_LOr;
13702 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013703 case OO_New:
13704 case OO_Delete:
13705 case OO_Array_New:
13706 case OO_Array_Delete:
13707 case OO_Slash:
13708 case OO_Percent:
13709 case OO_Tilde:
13710 case OO_Exclaim:
13711 case OO_Equal:
13712 case OO_Less:
13713 case OO_Greater:
13714 case OO_LessEqual:
13715 case OO_GreaterEqual:
13716 case OO_PlusEqual:
13717 case OO_MinusEqual:
13718 case OO_StarEqual:
13719 case OO_SlashEqual:
13720 case OO_PercentEqual:
13721 case OO_CaretEqual:
13722 case OO_AmpEqual:
13723 case OO_PipeEqual:
13724 case OO_LessLess:
13725 case OO_GreaterGreater:
13726 case OO_LessLessEqual:
13727 case OO_GreaterGreaterEqual:
13728 case OO_EqualEqual:
13729 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013730 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013731 case OO_PlusPlus:
13732 case OO_MinusMinus:
13733 case OO_Comma:
13734 case OO_ArrowStar:
13735 case OO_Arrow:
13736 case OO_Call:
13737 case OO_Subscript:
13738 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013739 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013740 case NUM_OVERLOADED_OPERATORS:
13741 llvm_unreachable("Unexpected reduction identifier");
13742 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013743 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013744 if (II->isStr("max"))
13745 BOK = BO_GT;
13746 else if (II->isStr("min"))
13747 BOK = BO_LT;
13748 }
13749 break;
13750 }
13751 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013752 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013753 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013754 else
13755 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013756 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013757
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013758 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13759 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013760 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013761 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013762 // OpenMP [2.1, C/C++]
13763 // A list item is a variable or array section, subject to the restrictions
13764 // specified in Section 2.4 on page 42 and in each of the sections
13765 // describing clauses and directives for which a list appears.
13766 // OpenMP [2.14.3.3, Restrictions, p.1]
13767 // A variable that is part of another variable (as an array or
13768 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013769 if (!FirstIter && IR != ER)
13770 ++IR;
13771 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013772 SourceLocation ELoc;
13773 SourceRange ERange;
13774 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013775 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013776 /*AllowArraySection=*/true);
13777 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013778 // Try to find 'declare reduction' corresponding construct before using
13779 // builtin/overloaded operators.
13780 QualType Type = Context.DependentTy;
13781 CXXCastPath BasePath;
13782 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013783 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013784 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013785 Expr *ReductionOp = nullptr;
13786 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013787 (DeclareReductionRef.isUnset() ||
13788 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013789 ReductionOp = DeclareReductionRef.get();
13790 // It will be analyzed later.
13791 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013792 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013793 ValueDecl *D = Res.first;
13794 if (!D)
13795 continue;
13796
Alexey Bataev88202be2017-07-27 13:20:36 +000013797 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013798 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013799 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13800 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013801 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013802 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013803 } else if (OASE) {
13804 QualType BaseType =
13805 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13806 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013807 Type = ATy->getElementType();
13808 else
13809 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013810 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013811 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013812 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013813 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013814 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013815
Alexey Bataevc5e02582014-06-16 07:08:35 +000013816 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13817 // A variable that appears in a private clause must not have an incomplete
13818 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013819 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013820 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013821 continue;
13822 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013823 // A list item that appears in a reduction clause must not be
13824 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013825 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13826 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013827 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013828
13829 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013830 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13831 // If a list-item is a reference type then it must bind to the same object
13832 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013833 if (!ASE && !OASE) {
13834 if (VD) {
13835 VarDecl *VDDef = VD->getDefinition();
13836 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13837 DSARefChecker Check(Stack);
13838 if (Check.Visit(VDDef->getInit())) {
13839 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13840 << getOpenMPClauseName(ClauseKind) << ERange;
13841 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13842 continue;
13843 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013844 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013845 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013846
Alexey Bataevbc529672018-09-28 19:33:14 +000013847 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13848 // in a Construct]
13849 // Variables with the predetermined data-sharing attributes may not be
13850 // listed in data-sharing attributes clauses, except for the cases
13851 // listed below. For these exceptions only, listing a predetermined
13852 // variable in a data-sharing attribute clause is allowed and overrides
13853 // the variable's predetermined data-sharing attributes.
13854 // OpenMP [2.14.3.6, Restrictions, p.3]
13855 // Any number of reduction clauses can be specified on the directive,
13856 // but a list item can appear only once in the reduction clauses for that
13857 // directive.
13858 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13859 if (DVar.CKind == OMPC_reduction) {
13860 S.Diag(ELoc, diag::err_omp_once_referenced)
13861 << getOpenMPClauseName(ClauseKind);
13862 if (DVar.RefExpr)
13863 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13864 continue;
13865 }
13866 if (DVar.CKind != OMPC_unknown) {
13867 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13868 << getOpenMPClauseName(DVar.CKind)
13869 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013870 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013871 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013872 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013873
13874 // OpenMP [2.14.3.6, Restrictions, p.1]
13875 // A list item that appears in a reduction clause of a worksharing
13876 // construct must be shared in the parallel regions to which any of the
13877 // worksharing regions arising from the worksharing construct bind.
13878 if (isOpenMPWorksharingDirective(CurrDir) &&
13879 !isOpenMPParallelDirective(CurrDir) &&
13880 !isOpenMPTeamsDirective(CurrDir)) {
13881 DVar = Stack->getImplicitDSA(D, true);
13882 if (DVar.CKind != OMPC_shared) {
13883 S.Diag(ELoc, diag::err_omp_required_access)
13884 << getOpenMPClauseName(OMPC_reduction)
13885 << getOpenMPClauseName(OMPC_shared);
13886 reportOriginalDsa(S, Stack, D, DVar);
13887 continue;
13888 }
13889 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013890 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013891
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013892 // Try to find 'declare reduction' corresponding construct before using
13893 // builtin/overloaded operators.
13894 CXXCastPath BasePath;
13895 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013896 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013897 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13898 if (DeclareReductionRef.isInvalid())
13899 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013900 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013901 (DeclareReductionRef.isUnset() ||
13902 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013903 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013904 continue;
13905 }
13906 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13907 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013908 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013909 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013910 << Type << ReductionIdRange;
13911 continue;
13912 }
13913
13914 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13915 // The type of a list item that appears in a reduction clause must be valid
13916 // for the reduction-identifier. For a max or min reduction in C, the type
13917 // of the list item must be an allowed arithmetic data type: char, int,
13918 // float, double, or _Bool, possibly modified with long, short, signed, or
13919 // unsigned. For a max or min reduction in C++, the type of the list item
13920 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13921 // double, or bool, possibly modified with long, short, signed, or unsigned.
13922 if (DeclareReductionRef.isUnset()) {
13923 if ((BOK == BO_GT || BOK == BO_LT) &&
13924 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013925 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13926 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013927 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013928 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013929 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13930 VarDecl::DeclarationOnly;
13931 S.Diag(D->getLocation(),
13932 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013933 << D;
13934 }
13935 continue;
13936 }
13937 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013938 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013939 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13940 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013941 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013942 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13943 VarDecl::DeclarationOnly;
13944 S.Diag(D->getLocation(),
13945 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013946 << D;
13947 }
13948 continue;
13949 }
13950 }
13951
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013952 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013953 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13954 D->hasAttrs() ? &D->getAttrs() : nullptr);
13955 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13956 D->hasAttrs() ? &D->getAttrs() : nullptr);
13957 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013958
13959 // Try if we can determine constant lengths for all array sections and avoid
13960 // the VLA.
13961 bool ConstantLengthOASE = false;
13962 if (OASE) {
13963 bool SingleElement;
13964 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013965 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013966 Context, OASE, SingleElement, ArraySizes);
13967
13968 // If we don't have a single element, we must emit a constant array type.
13969 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013970 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013971 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13972 ArrayType::Normal,
13973 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013974 }
13975 }
13976
13977 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013978 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013979 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013980 if (!Context.getTargetInfo().isVLASupported()) {
13981 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13982 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13983 S.Diag(ELoc, diag::note_vla_unsupported);
13984 } else {
13985 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13986 S.targetDiag(ELoc, diag::note_vla_unsupported);
13987 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013988 continue;
13989 }
David Majnemer9d168222016-08-05 17:44:54 +000013990 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013991 // Create pseudo array type for private copy. The size for this array will
13992 // be generated during codegen.
13993 // For array subscripts or single variables Private Ty is the same as Type
13994 // (type of the variable or single array element).
13995 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013996 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013997 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013998 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013999 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014000 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014001 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014002 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014003 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014004 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014005 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
14006 D->hasAttrs() ? &D->getAttrs() : nullptr,
14007 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014008 // Add initializer for private variable.
14009 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014010 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
14011 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014012 if (DeclareReductionRef.isUsable()) {
14013 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
14014 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
14015 if (DRD->getInitializer()) {
14016 Init = DRDRef;
14017 RHSVD->setInit(DRDRef);
14018 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014019 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014020 } else {
14021 switch (BOK) {
14022 case BO_Add:
14023 case BO_Xor:
14024 case BO_Or:
14025 case BO_LOr:
14026 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
14027 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014028 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014029 break;
14030 case BO_Mul:
14031 case BO_LAnd:
14032 if (Type->isScalarType() || Type->isAnyComplexType()) {
14033 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014034 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014035 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014036 break;
14037 case BO_And: {
14038 // '&' reduction op - initializer is '~0'.
14039 QualType OrigType = Type;
14040 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14041 Type = ComplexTy->getElementType();
14042 if (Type->isRealFloatingType()) {
14043 llvm::APFloat InitValue =
14044 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
14045 /*isIEEE=*/true);
14046 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14047 Type, ELoc);
14048 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014049 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014050 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14051 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14052 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14053 }
14054 if (Init && OrigType->isAnyComplexType()) {
14055 // Init = 0xFFFF + 0xFFFFi;
14056 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014057 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014058 }
14059 Type = OrigType;
14060 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014061 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014062 case BO_LT:
14063 case BO_GT: {
14064 // 'min' reduction op - initializer is 'Largest representable number in
14065 // the reduction list item type'.
14066 // 'max' reduction op - initializer is 'Least representable number in
14067 // the reduction list item type'.
14068 if (Type->isIntegerType() || Type->isPointerType()) {
14069 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014070 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014071 QualType IntTy =
14072 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14073 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014074 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14075 : llvm::APInt::getMinValue(Size)
14076 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14077 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014078 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14079 if (Type->isPointerType()) {
14080 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014081 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014082 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014083 if (CastExpr.isInvalid())
14084 continue;
14085 Init = CastExpr.get();
14086 }
14087 } else if (Type->isRealFloatingType()) {
14088 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14089 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14090 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14091 Type, ELoc);
14092 }
14093 break;
14094 }
14095 case BO_PtrMemD:
14096 case BO_PtrMemI:
14097 case BO_MulAssign:
14098 case BO_Div:
14099 case BO_Rem:
14100 case BO_Sub:
14101 case BO_Shl:
14102 case BO_Shr:
14103 case BO_LE:
14104 case BO_GE:
14105 case BO_EQ:
14106 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014107 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014108 case BO_AndAssign:
14109 case BO_XorAssign:
14110 case BO_OrAssign:
14111 case BO_Assign:
14112 case BO_AddAssign:
14113 case BO_SubAssign:
14114 case BO_DivAssign:
14115 case BO_RemAssign:
14116 case BO_ShlAssign:
14117 case BO_ShrAssign:
14118 case BO_Comma:
14119 llvm_unreachable("Unexpected reduction operation");
14120 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014121 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014122 if (Init && DeclareReductionRef.isUnset())
14123 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14124 else if (!Init)
14125 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014126 if (RHSVD->isInvalidDecl())
14127 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014128 if (!RHSVD->hasInit() &&
14129 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014130 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14131 << Type << ReductionIdRange;
14132 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14133 VarDecl::DeclarationOnly;
14134 S.Diag(D->getLocation(),
14135 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014136 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014137 continue;
14138 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014139 // Store initializer for single element in private copy. Will be used during
14140 // codegen.
14141 PrivateVD->setInit(RHSVD->getInit());
14142 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014143 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014144 ExprResult ReductionOp;
14145 if (DeclareReductionRef.isUsable()) {
14146 QualType RedTy = DeclareReductionRef.get()->getType();
14147 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014148 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14149 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014150 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014151 LHS = S.DefaultLvalueConversion(LHS.get());
14152 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014153 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14154 CK_UncheckedDerivedToBase, LHS.get(),
14155 &BasePath, LHS.get()->getValueKind());
14156 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14157 CK_UncheckedDerivedToBase, RHS.get(),
14158 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014159 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014160 FunctionProtoType::ExtProtoInfo EPI;
14161 QualType Params[] = {PtrRedTy, PtrRedTy};
14162 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14163 auto *OVE = new (Context) OpaqueValueExpr(
14164 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014165 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014166 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014167 ReductionOp =
14168 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014169 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014170 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014171 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014172 if (ReductionOp.isUsable()) {
14173 if (BOK != BO_LT && BOK != BO_GT) {
14174 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014175 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014176 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014177 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014178 auto *ConditionalOp = new (Context)
14179 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14180 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014181 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014182 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014183 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014184 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014185 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014186 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14187 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014188 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014189 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014190 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014191 }
14192
Alexey Bataevfa312f32017-07-21 18:48:21 +000014193 // OpenMP [2.15.4.6, Restrictions, p.2]
14194 // A list item that appears in an in_reduction clause of a task construct
14195 // must appear in a task_reduction clause of a construct associated with a
14196 // taskgroup region that includes the participating task in its taskgroup
14197 // set. The construct associated with the innermost region that meets this
14198 // condition must specify the same reduction-identifier as the in_reduction
14199 // clause.
14200 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014201 SourceRange ParentSR;
14202 BinaryOperatorKind ParentBOK;
14203 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014204 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014205 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014206 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14207 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014208 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014209 Stack->getTopMostTaskgroupReductionData(
14210 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014211 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14212 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14213 if (!IsParentBOK && !IsParentReductionOp) {
14214 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14215 continue;
14216 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014217 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14218 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14219 IsParentReductionOp) {
14220 bool EmitError = true;
14221 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14222 llvm::FoldingSetNodeID RedId, ParentRedId;
14223 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14224 DeclareReductionRef.get()->Profile(RedId, Context,
14225 /*Canonical=*/true);
14226 EmitError = RedId != ParentRedId;
14227 }
14228 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014229 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014230 diag::err_omp_reduction_identifier_mismatch)
14231 << ReductionIdRange << RefExpr->getSourceRange();
14232 S.Diag(ParentSR.getBegin(),
14233 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014234 << ParentSR
14235 << (IsParentBOK ? ParentBOKDSA.RefExpr
14236 : ParentReductionOpDSA.RefExpr)
14237 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014238 continue;
14239 }
14240 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014241 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14242 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014243 }
14244
Alexey Bataev60da77e2016-02-29 05:54:20 +000014245 DeclRefExpr *Ref = nullptr;
14246 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014247 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014248 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014249 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014250 VarsExpr =
14251 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14252 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014253 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014254 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014255 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014256 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014257 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014258 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014259 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014260 if (!RefRes.isUsable())
14261 continue;
14262 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014263 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14264 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014265 if (!PostUpdateRes.isUsable())
14266 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014267 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14268 Stack->getCurrentDirective() == OMPD_taskgroup) {
14269 S.Diag(RefExpr->getExprLoc(),
14270 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014271 << RefExpr->getSourceRange();
14272 continue;
14273 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014274 RD.ExprPostUpdates.emplace_back(
14275 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014276 }
14277 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014278 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014279 // All reduction items are still marked as reduction (to do not increase
14280 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014281 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014282 if (CurrDir == OMPD_taskgroup) {
14283 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014284 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14285 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014286 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014287 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014288 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014289 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14290 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014291 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014292 return RD.Vars.empty();
14293}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014294
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014295OMPClause *Sema::ActOnOpenMPReductionClause(
14296 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14297 SourceLocation ColonLoc, SourceLocation EndLoc,
14298 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14299 ArrayRef<Expr *> UnresolvedReductions) {
14300 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014301 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014302 StartLoc, LParenLoc, ColonLoc, EndLoc,
14303 ReductionIdScopeSpec, ReductionId,
14304 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014305 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014306
Alexey Bataevc5e02582014-06-16 07:08:35 +000014307 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014308 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14309 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14310 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14311 buildPreInits(Context, RD.ExprCaptures),
14312 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014313}
14314
Alexey Bataev169d96a2017-07-18 20:17:46 +000014315OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14316 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14317 SourceLocation ColonLoc, SourceLocation EndLoc,
14318 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14319 ArrayRef<Expr *> UnresolvedReductions) {
14320 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014321 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14322 StartLoc, LParenLoc, ColonLoc, EndLoc,
14323 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014324 UnresolvedReductions, RD))
14325 return nullptr;
14326
14327 return OMPTaskReductionClause::Create(
14328 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14329 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14330 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14331 buildPreInits(Context, RD.ExprCaptures),
14332 buildPostUpdate(*this, RD.ExprPostUpdates));
14333}
14334
Alexey Bataevfa312f32017-07-21 18:48:21 +000014335OMPClause *Sema::ActOnOpenMPInReductionClause(
14336 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14337 SourceLocation ColonLoc, SourceLocation EndLoc,
14338 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14339 ArrayRef<Expr *> UnresolvedReductions) {
14340 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014341 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014342 StartLoc, LParenLoc, ColonLoc, EndLoc,
14343 ReductionIdScopeSpec, ReductionId,
14344 UnresolvedReductions, RD))
14345 return nullptr;
14346
14347 return OMPInReductionClause::Create(
14348 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14349 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014350 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014351 buildPreInits(Context, RD.ExprCaptures),
14352 buildPostUpdate(*this, RD.ExprPostUpdates));
14353}
14354
Alexey Bataevecba70f2016-04-12 11:02:11 +000014355bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14356 SourceLocation LinLoc) {
14357 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14358 LinKind == OMPC_LINEAR_unknown) {
14359 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14360 return true;
14361 }
14362 return false;
14363}
14364
Alexey Bataeve3727102018-04-18 15:57:46 +000014365bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014366 OpenMPLinearClauseKind LinKind,
14367 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014368 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014369 // A variable must not have an incomplete type or a reference type.
14370 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14371 return true;
14372 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14373 !Type->isReferenceType()) {
14374 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14375 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14376 return true;
14377 }
14378 Type = Type.getNonReferenceType();
14379
Joel E. Dennybae586f2019-01-04 22:12:13 +000014380 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14381 // A variable that is privatized must not have a const-qualified type
14382 // unless it is of class type with a mutable member. This restriction does
14383 // not apply to the firstprivate clause.
14384 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014385 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014386
14387 // A list item must be of integral or pointer type.
14388 Type = Type.getUnqualifiedType().getCanonicalType();
14389 const auto *Ty = Type.getTypePtrOrNull();
Alexey Bataev3f2e3dc2020-01-07 09:26:10 -050014390 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
14391 !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
Alexey Bataevecba70f2016-04-12 11:02:11 +000014392 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14393 if (D) {
14394 bool IsDecl =
14395 !VD ||
14396 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14397 Diag(D->getLocation(),
14398 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14399 << D;
14400 }
14401 return true;
14402 }
14403 return false;
14404}
14405
Alexey Bataev182227b2015-08-20 10:54:39 +000014406OMPClause *Sema::ActOnOpenMPLinearClause(
14407 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14408 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14409 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014410 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014411 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014412 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014413 SmallVector<Decl *, 4> ExprCaptures;
14414 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014415 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014416 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014417 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014418 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014419 SourceLocation ELoc;
14420 SourceRange ERange;
14421 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014422 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014423 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014424 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014425 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014426 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014427 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014428 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014429 ValueDecl *D = Res.first;
14430 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014431 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014432
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014433 QualType Type = D->getType();
14434 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014435
14436 // OpenMP [2.14.3.7, linear clause]
14437 // A list-item cannot appear in more than one linear clause.
14438 // A list-item that appears in a linear clause cannot appear in any
14439 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014440 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014441 if (DVar.RefExpr) {
14442 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14443 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014444 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014445 continue;
14446 }
14447
Alexey Bataevecba70f2016-04-12 11:02:11 +000014448 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014449 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014450 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014451
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014452 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014453 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014454 buildVarDecl(*this, ELoc, Type, D->getName(),
14455 D->hasAttrs() ? &D->getAttrs() : nullptr,
14456 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014457 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014458 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014459 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014460 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014461 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014462 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014463 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014464 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014465 ExprCaptures.push_back(Ref->getDecl());
14466 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14467 ExprResult RefRes = DefaultLvalueConversion(Ref);
14468 if (!RefRes.isUsable())
14469 continue;
14470 ExprResult PostUpdateRes =
14471 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14472 SimpleRefExpr, RefRes.get());
14473 if (!PostUpdateRes.isUsable())
14474 continue;
14475 ExprPostUpdates.push_back(
14476 IgnoredValueConversions(PostUpdateRes.get()).get());
14477 }
14478 }
14479 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014480 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014481 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014482 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014483 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014484 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014485 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014486 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014487
14488 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014489 Vars.push_back((VD || CurContext->isDependentContext())
14490 ? RefExpr->IgnoreParens()
14491 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014492 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014493 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014494 }
14495
14496 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014497 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014498
14499 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014500 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014501 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14502 !Step->isInstantiationDependent() &&
14503 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014504 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014505 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014506 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014507 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014508 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014509
Alexander Musman3276a272015-03-21 10:12:56 +000014510 // Build var to save the step value.
14511 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014512 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014513 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014514 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014515 ExprResult CalcStep =
14516 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014517 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014518
Alexander Musman8dba6642014-04-22 13:09:42 +000014519 // Warn about zero linear step (it would be probably better specified as
14520 // making corresponding variables 'const').
14521 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014522 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14523 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014524 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14525 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014526 if (!IsConstant && CalcStep.isUsable()) {
14527 // Calculate the step beforehand instead of doing this on each iteration.
14528 // (This is not used if the number of iterations may be kfold-ed).
14529 CalcStepExpr = CalcStep.get();
14530 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014531 }
14532
Alexey Bataev182227b2015-08-20 10:54:39 +000014533 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14534 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014535 StepExpr, CalcStepExpr,
14536 buildPreInits(Context, ExprCaptures),
14537 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014538}
14539
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014540static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14541 Expr *NumIterations, Sema &SemaRef,
14542 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014543 // Walk the vars and build update/final expressions for the CodeGen.
14544 SmallVector<Expr *, 8> Updates;
14545 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014546 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014547 Expr *Step = Clause.getStep();
14548 Expr *CalcStep = Clause.getCalcStep();
14549 // OpenMP [2.14.3.7, linear clause]
14550 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014551 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014552 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014553 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014554 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14555 bool HasErrors = false;
14556 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014557 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014558 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14559 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014560 SourceLocation ELoc;
14561 SourceRange ERange;
14562 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014563 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014564 ValueDecl *D = Res.first;
14565 if (Res.second || !D) {
14566 Updates.push_back(nullptr);
14567 Finals.push_back(nullptr);
14568 HasErrors = true;
14569 continue;
14570 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014571 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014572 // OpenMP [2.15.11, distribute simd Construct]
14573 // A list item may not appear in a linear clause, unless it is the loop
14574 // iteration variable.
14575 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14576 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14577 SemaRef.Diag(ELoc,
14578 diag::err_omp_linear_distribute_var_non_loop_iteration);
14579 Updates.push_back(nullptr);
14580 Finals.push_back(nullptr);
14581 HasErrors = true;
14582 continue;
14583 }
Alexander Musman3276a272015-03-21 10:12:56 +000014584 Expr *InitExpr = *CurInit;
14585
14586 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014587 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014588 Expr *CapturedRef;
14589 if (LinKind == OMPC_LINEAR_uval)
14590 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14591 else
14592 CapturedRef =
14593 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14594 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14595 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014596
14597 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014598 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014599 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014600 Update = buildCounterUpdate(
14601 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14602 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014603 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014604 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014605 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014606 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014607
14608 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014609 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014610 if (!Info.first)
14611 Final =
14612 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014613 InitExpr, NumIterations, Step, /*Subtract=*/false,
14614 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014615 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014616 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014617 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014618 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014619
Alexander Musman3276a272015-03-21 10:12:56 +000014620 if (!Update.isUsable() || !Final.isUsable()) {
14621 Updates.push_back(nullptr);
14622 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014623 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014624 HasErrors = true;
14625 } else {
14626 Updates.push_back(Update.get());
14627 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014628 if (!Info.first)
14629 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014630 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014631 ++CurInit;
14632 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014633 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014634 if (Expr *S = Clause.getStep())
14635 UsedExprs.push_back(S);
14636 // Fill the remaining part with the nullptr.
14637 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014638 Clause.setUpdates(Updates);
14639 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014640 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014641 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014642}
14643
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014644OMPClause *Sema::ActOnOpenMPAlignedClause(
14645 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14646 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014647 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014648 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014649 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14650 SourceLocation ELoc;
14651 SourceRange ERange;
14652 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014653 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014654 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014655 // It will be analyzed later.
14656 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014657 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014658 ValueDecl *D = Res.first;
14659 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014660 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014661
Alexey Bataev1efd1662016-03-29 10:59:56 +000014662 QualType QType = D->getType();
14663 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014664
14665 // OpenMP [2.8.1, simd construct, Restrictions]
14666 // The type of list items appearing in the aligned clause must be
14667 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014668 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014669 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014670 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014671 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014672 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014673 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014674 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014675 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014676 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014677 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014678 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014679 continue;
14680 }
14681
14682 // OpenMP [2.8.1, simd construct, Restrictions]
14683 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014684 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014685 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14686 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014687 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14688 << getOpenMPClauseName(OMPC_aligned);
14689 continue;
14690 }
14691
Alexey Bataev1efd1662016-03-29 10:59:56 +000014692 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014693 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014694 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14695 Vars.push_back(DefaultFunctionArrayConversion(
14696 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14697 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014698 }
14699
14700 // OpenMP [2.8.1, simd construct, Description]
14701 // The parameter of the aligned clause, alignment, must be a constant
14702 // positive integer expression.
14703 // If no optional parameter is specified, implementation-defined default
14704 // alignments for SIMD instructions on the target platforms are assumed.
14705 if (Alignment != nullptr) {
14706 ExprResult AlignResult =
14707 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14708 if (AlignResult.isInvalid())
14709 return nullptr;
14710 Alignment = AlignResult.get();
14711 }
14712 if (Vars.empty())
14713 return nullptr;
14714
14715 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14716 EndLoc, Vars, Alignment);
14717}
14718
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014719OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14720 SourceLocation StartLoc,
14721 SourceLocation LParenLoc,
14722 SourceLocation EndLoc) {
14723 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014724 SmallVector<Expr *, 8> SrcExprs;
14725 SmallVector<Expr *, 8> DstExprs;
14726 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014727 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014728 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14729 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014730 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014731 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014732 SrcExprs.push_back(nullptr);
14733 DstExprs.push_back(nullptr);
14734 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014735 continue;
14736 }
14737
Alexey Bataeved09d242014-05-28 05:53:51 +000014738 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014739 // OpenMP [2.1, C/C++]
14740 // A list item is a variable name.
14741 // OpenMP [2.14.4.1, Restrictions, p.1]
14742 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014743 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014744 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014745 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14746 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014747 continue;
14748 }
14749
14750 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014751 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014752
14753 QualType Type = VD->getType();
14754 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14755 // It will be analyzed later.
14756 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014757 SrcExprs.push_back(nullptr);
14758 DstExprs.push_back(nullptr);
14759 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014760 continue;
14761 }
14762
14763 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14764 // A list item that appears in a copyin clause must be threadprivate.
14765 if (!DSAStack->isThreadPrivate(VD)) {
14766 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014767 << getOpenMPClauseName(OMPC_copyin)
14768 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014769 continue;
14770 }
14771
14772 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14773 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014774 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014775 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014776 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14777 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014778 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014779 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014780 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014781 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014782 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014783 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014784 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014785 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014786 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014787 // For arrays generate assignment operation for single element and replace
14788 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014789 ExprResult AssignmentOp =
14790 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14791 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014792 if (AssignmentOp.isInvalid())
14793 continue;
14794 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014795 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014796 if (AssignmentOp.isInvalid())
14797 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014798
14799 DSAStack->addDSA(VD, DE, OMPC_copyin);
14800 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014801 SrcExprs.push_back(PseudoSrcExpr);
14802 DstExprs.push_back(PseudoDstExpr);
14803 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014804 }
14805
Alexey Bataeved09d242014-05-28 05:53:51 +000014806 if (Vars.empty())
14807 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014808
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014809 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14810 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014811}
14812
Alexey Bataevbae9a792014-06-27 10:37:06 +000014813OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14814 SourceLocation StartLoc,
14815 SourceLocation LParenLoc,
14816 SourceLocation EndLoc) {
14817 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014818 SmallVector<Expr *, 8> SrcExprs;
14819 SmallVector<Expr *, 8> DstExprs;
14820 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014821 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014822 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14823 SourceLocation ELoc;
14824 SourceRange ERange;
14825 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014826 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014827 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014828 // It will be analyzed later.
14829 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014830 SrcExprs.push_back(nullptr);
14831 DstExprs.push_back(nullptr);
14832 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014833 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014834 ValueDecl *D = Res.first;
14835 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014836 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014837
Alexey Bataeve122da12016-03-17 10:50:17 +000014838 QualType Type = D->getType();
14839 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014840
14841 // OpenMP [2.14.4.2, Restrictions, p.2]
14842 // A list item that appears in a copyprivate clause may not appear in a
14843 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014844 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014845 DSAStackTy::DSAVarData DVar =
14846 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014847 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14848 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014849 Diag(ELoc, diag::err_omp_wrong_dsa)
14850 << getOpenMPClauseName(DVar.CKind)
14851 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014852 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014853 continue;
14854 }
14855
14856 // OpenMP [2.11.4.2, Restrictions, p.1]
14857 // All list items that appear in a copyprivate clause must be either
14858 // threadprivate or private in the enclosing context.
14859 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014860 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014861 if (DVar.CKind == OMPC_shared) {
14862 Diag(ELoc, diag::err_omp_required_access)
14863 << getOpenMPClauseName(OMPC_copyprivate)
14864 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014865 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014866 continue;
14867 }
14868 }
14869 }
14870
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014871 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014872 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014873 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014874 << getOpenMPClauseName(OMPC_copyprivate) << Type
14875 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014876 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014877 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014878 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014879 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014880 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014881 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014882 continue;
14883 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014884
Alexey Bataevbae9a792014-06-27 10:37:06 +000014885 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14886 // A variable of class type (or array thereof) that appears in a
14887 // copyin clause requires an accessible, unambiguous copy assignment
14888 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014889 Type = Context.getBaseElementType(Type.getNonReferenceType())
14890 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014891 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014892 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014893 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014894 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14895 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014896 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014897 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014898 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14899 ExprResult AssignmentOp = BuildBinOp(
14900 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014901 if (AssignmentOp.isInvalid())
14902 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014903 AssignmentOp =
14904 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014905 if (AssignmentOp.isInvalid())
14906 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014907
14908 // No need to mark vars as copyprivate, they are already threadprivate or
14909 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014910 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014911 Vars.push_back(
14912 VD ? RefExpr->IgnoreParens()
14913 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014914 SrcExprs.push_back(PseudoSrcExpr);
14915 DstExprs.push_back(PseudoDstExpr);
14916 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014917 }
14918
14919 if (Vars.empty())
14920 return nullptr;
14921
Alexey Bataeva63048e2015-03-23 06:18:07 +000014922 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14923 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014924}
14925
Alexey Bataev6125da92014-07-21 11:26:11 +000014926OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14927 SourceLocation StartLoc,
14928 SourceLocation LParenLoc,
14929 SourceLocation EndLoc) {
14930 if (VarList.empty())
14931 return nullptr;
14932
14933 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14934}
Alexey Bataevdea47612014-07-23 07:46:59 +000014935
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014936OMPClause *
14937Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14938 SourceLocation DepLoc, SourceLocation ColonLoc,
14939 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14940 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014941 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014942 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014943 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014944 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014945 return nullptr;
14946 }
14947 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014948 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14949 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014950 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014951 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014952 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14953 /*Last=*/OMPC_DEPEND_unknown, Except)
14954 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014955 return nullptr;
14956 }
14957 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014958 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014959 llvm::APSInt DepCounter(/*BitWidth=*/32);
14960 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014961 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14962 if (const Expr *OrderedCountExpr =
14963 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014964 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14965 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014966 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014967 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014968 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014969 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14970 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14971 // It will be analyzed later.
14972 Vars.push_back(RefExpr);
14973 continue;
14974 }
14975
14976 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014977 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014978 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014979 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014980 DepCounter >= TotalDepCount) {
14981 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14982 continue;
14983 }
14984 ++DepCounter;
14985 // OpenMP [2.13.9, Summary]
14986 // depend(dependence-type : vec), where dependence-type is:
14987 // 'sink' and where vec is the iteration vector, which has the form:
14988 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14989 // where n is the value specified by the ordered clause in the loop
14990 // directive, xi denotes the loop iteration variable of the i-th nested
14991 // loop associated with the loop directive, and di is a constant
14992 // non-negative integer.
14993 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014994 // It will be analyzed later.
14995 Vars.push_back(RefExpr);
14996 continue;
14997 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014998 SimpleExpr = SimpleExpr->IgnoreImplicit();
14999 OverloadedOperatorKind OOK = OO_None;
15000 SourceLocation OOLoc;
15001 Expr *LHS = SimpleExpr;
15002 Expr *RHS = nullptr;
15003 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
15004 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
15005 OOLoc = BO->getOperatorLoc();
15006 LHS = BO->getLHS()->IgnoreParenImpCasts();
15007 RHS = BO->getRHS()->IgnoreParenImpCasts();
15008 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
15009 OOK = OCE->getOperator();
15010 OOLoc = OCE->getOperatorLoc();
15011 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
15012 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
15013 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
15014 OOK = MCE->getMethodDecl()
15015 ->getNameInfo()
15016 .getName()
15017 .getCXXOverloadedOperator();
15018 OOLoc = MCE->getCallee()->getExprLoc();
15019 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
15020 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015021 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015022 SourceLocation ELoc;
15023 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000015024 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015025 if (Res.second) {
15026 // It will be analyzed later.
15027 Vars.push_back(RefExpr);
15028 }
15029 ValueDecl *D = Res.first;
15030 if (!D)
15031 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015032
Alexey Bataev17daedf2018-02-15 22:42:57 +000015033 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
15034 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
15035 continue;
15036 }
15037 if (RHS) {
15038 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
15039 RHS, OMPC_depend, /*StrictlyPositive=*/false);
15040 if (RHSRes.isInvalid())
15041 continue;
15042 }
15043 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015044 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015045 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015046 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000015047 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000015048 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000015049 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
15050 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000015051 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000015052 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000015053 continue;
15054 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015055 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015056 } else {
Kelvin Li427ffa22020-01-03 11:55:37 -050015057 // OpenMP 5.0 [2.17.11, Restrictions]
15058 // List items used in depend clauses cannot be zero-length array sections.
15059 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
15060 if (OASE) {
15061 const Expr *Length = OASE->getLength();
15062 Expr::EvalResult Result;
15063 if (Length && !Length->isValueDependent() &&
15064 Length->EvaluateAsInt(Result, Context) &&
15065 Result.Val.getInt().isNullValue()) {
15066 Diag(ELoc,
15067 diag::err_omp_depend_zero_length_array_section_not_allowed)
15068 << SimpleExpr->getSourceRange();
15069 continue;
15070 }
15071 }
15072
Alexey Bataev17daedf2018-02-15 22:42:57 +000015073 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
15074 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
15075 (ASE &&
15076 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
15077 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
15078 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15079 << RefExpr->getSourceRange();
15080 continue;
15081 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000015082
15083 ExprResult Res;
15084 {
15085 Sema::TentativeAnalysisScope Trap(*this);
15086 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15087 RefExpr->IgnoreParenImpCasts());
15088 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015089 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15090 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15091 << RefExpr->getSourceRange();
15092 continue;
15093 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015094 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015095 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015096 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015097
15098 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15099 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015100 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015101 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15102 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15103 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15104 }
15105 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15106 Vars.empty())
15107 return nullptr;
15108
Alexey Bataev8b427062016-05-25 12:36:08 +000015109 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015110 DepKind, DepLoc, ColonLoc, Vars,
15111 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015112 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15113 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015114 DSAStack->addDoacrossDependClause(C, OpsOffs);
15115 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015116}
Michael Wonge710d542015-08-07 16:16:36 +000015117
15118OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15119 SourceLocation LParenLoc,
15120 SourceLocation EndLoc) {
15121 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015122 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015123
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015124 // OpenMP [2.9.1, Restrictions]
15125 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015126 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015127 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015128 return nullptr;
15129
Alexey Bataev931e19b2017-10-02 16:32:39 +000015130 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015131 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015132 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015133 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015134 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015135 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015136 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15137 HelperValStmt = buildPreInits(Context, Captures);
15138 }
15139
Alexey Bataev8451efa2018-01-15 19:06:12 +000015140 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15141 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015142}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015143
Alexey Bataeve3727102018-04-18 15:57:46 +000015144static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015145 DSAStackTy *Stack, QualType QTy,
15146 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015147 NamedDecl *ND;
15148 if (QTy->isIncompleteType(&ND)) {
15149 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15150 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015151 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015152 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015153 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015154 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015155 return true;
15156}
15157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015158/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015159/// (array section or array subscript) does NOT specify the whole size of the
15160/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015161static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015162 const Expr *E,
15163 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015164 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015165
15166 // If this is an array subscript, it refers to the whole size if the size of
15167 // the dimension is constant and equals 1. Also, an array section assumes the
15168 // format of an array subscript if no colon is used.
15169 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015170 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015171 return ATy->getSize().getSExtValue() != 1;
15172 // Size can't be evaluated statically.
15173 return false;
15174 }
15175
15176 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015177 const Expr *LowerBound = OASE->getLowerBound();
15178 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015179
15180 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015181 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015182 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015183 Expr::EvalResult Result;
15184 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015185 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015186
15187 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015188 if (ConstLowerBound.getSExtValue())
15189 return true;
15190 }
15191
15192 // If we don't have a length we covering the whole dimension.
15193 if (!Length)
15194 return false;
15195
15196 // If the base is a pointer, we don't have a way to get the size of the
15197 // pointee.
15198 if (BaseQTy->isPointerType())
15199 return false;
15200
15201 // We can only check if the length is the same as the size of the dimension
15202 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015203 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015204 if (!CATy)
15205 return false;
15206
Fangrui Song407659a2018-11-30 23:41:18 +000015207 Expr::EvalResult Result;
15208 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015209 return false; // Can't get the integer value as a constant.
15210
Fangrui Song407659a2018-11-30 23:41:18 +000015211 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015212 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15213}
15214
15215// Return true if it can be proven that the provided array expression (array
15216// section or array subscript) does NOT specify a single element of the array
15217// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015218static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015219 const Expr *E,
15220 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015221 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015222
15223 // An array subscript always refer to a single element. Also, an array section
15224 // assumes the format of an array subscript if no colon is used.
15225 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15226 return false;
15227
15228 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015229 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015230
15231 // If we don't have a length we have to check if the array has unitary size
15232 // for this dimension. Also, we should always expect a length if the base type
15233 // is pointer.
15234 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015235 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015236 return ATy->getSize().getSExtValue() != 1;
15237 // We cannot assume anything.
15238 return false;
15239 }
15240
15241 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015242 Expr::EvalResult Result;
15243 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015244 return false; // Can't get the integer value as a constant.
15245
Fangrui Song407659a2018-11-30 23:41:18 +000015246 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015247 return ConstLength.getSExtValue() != 1;
15248}
15249
Samuel Antao661c0902016-05-26 17:39:58 +000015250// Return the expression of the base of the mappable expression or null if it
15251// cannot be determined and do all the necessary checks to see if the expression
15252// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015253// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015254static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015255 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015256 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015257 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015258 SourceLocation ELoc = E->getExprLoc();
15259 SourceRange ERange = E->getSourceRange();
15260
15261 // The base of elements of list in a map clause have to be either:
15262 // - a reference to variable or field.
15263 // - a member expression.
15264 // - an array expression.
15265 //
15266 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15267 // reference to 'r'.
15268 //
15269 // If we have:
15270 //
15271 // struct SS {
15272 // Bla S;
15273 // foo() {
15274 // #pragma omp target map (S.Arr[:12]);
15275 // }
15276 // }
15277 //
15278 // We want to retrieve the member expression 'this->S';
15279
Alexey Bataeve3727102018-04-18 15:57:46 +000015280 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015281
Samuel Antao5de996e2016-01-22 20:21:36 +000015282 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15283 // If a list item is an array section, it must specify contiguous storage.
15284 //
15285 // For this restriction it is sufficient that we make sure only references
15286 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015287 // exist except in the rightmost expression (unless they cover the whole
15288 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015289 //
15290 // r.ArrS[3:5].Arr[6:7]
15291 //
15292 // r.ArrS[3:5].x
15293 //
15294 // but these would be valid:
15295 // r.ArrS[3].Arr[6:7]
15296 //
15297 // r.ArrS[3].x
15298
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015299 bool AllowUnitySizeArraySection = true;
15300 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015301
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015302 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015303 E = E->IgnoreParenImpCasts();
15304
15305 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15306 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015307 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015308
15309 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015310
15311 // If we got a reference to a declaration, we should not expect any array
15312 // section before that.
15313 AllowUnitySizeArraySection = false;
15314 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015315
15316 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015317 CurComponents.emplace_back(CurE, CurE->getDecl());
15318 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015319 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015320
15321 if (isa<CXXThisExpr>(BaseE))
15322 // We found a base expression: this->Val.
15323 RelevantExpr = CurE;
15324 else
15325 E = BaseE;
15326
15327 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015328 if (!NoDiagnose) {
15329 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15330 << CurE->getSourceRange();
15331 return nullptr;
15332 }
15333 if (RelevantExpr)
15334 return nullptr;
15335 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015336 }
15337
15338 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15339
15340 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15341 // A bit-field cannot appear in a map clause.
15342 //
15343 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015344 if (!NoDiagnose) {
15345 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15346 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15347 return nullptr;
15348 }
15349 if (RelevantExpr)
15350 return nullptr;
15351 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015352 }
15353
15354 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15355 // If the type of a list item is a reference to a type T then the type
15356 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015357 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015358
15359 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15360 // A list item cannot be a variable that is a member of a structure with
15361 // a union type.
15362 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015363 if (CurType->isUnionType()) {
15364 if (!NoDiagnose) {
15365 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15366 << CurE->getSourceRange();
15367 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015368 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015369 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015370 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015371
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015372 // If we got a member expression, we should not expect any array section
15373 // before that:
15374 //
15375 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15376 // If a list item is an element of a structure, only the rightmost symbol
15377 // of the variable reference can be an array section.
15378 //
15379 AllowUnitySizeArraySection = false;
15380 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015381
15382 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015383 CurComponents.emplace_back(CurE, FD);
15384 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015385 E = CurE->getBase()->IgnoreParenImpCasts();
15386
15387 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015388 if (!NoDiagnose) {
15389 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15390 << 0 << CurE->getSourceRange();
15391 return nullptr;
15392 }
15393 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015394 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015395
15396 // If we got an array subscript that express the whole dimension we
15397 // can have any array expressions before. If it only expressing part of
15398 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015399 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015400 E->getType()))
15401 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015402
Patrick Lystere13b1e32019-01-02 19:28:48 +000015403 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15404 Expr::EvalResult Result;
15405 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15406 if (!Result.Val.getInt().isNullValue()) {
15407 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15408 diag::err_omp_invalid_map_this_expr);
15409 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15410 diag::note_omp_invalid_subscript_on_this_ptr_map);
15411 }
15412 }
15413 RelevantExpr = TE;
15414 }
15415
Samuel Antao90927002016-04-26 14:54:23 +000015416 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015417 CurComponents.emplace_back(CurE, nullptr);
15418 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015419 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015420 E = CurE->getBase()->IgnoreParenImpCasts();
15421
Alexey Bataev27041fa2017-12-05 15:22:49 +000015422 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015423 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15424
Samuel Antao5de996e2016-01-22 20:21:36 +000015425 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15426 // If the type of a list item is a reference to a type T then the type
15427 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015428 if (CurType->isReferenceType())
15429 CurType = CurType->getPointeeType();
15430
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015431 bool IsPointer = CurType->isAnyPointerType();
15432
15433 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015434 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15435 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015436 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015437 }
15438
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015439 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015440 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015441 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015442 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015443
Samuel Antaodab51bb2016-07-18 23:22:11 +000015444 if (AllowWholeSizeArraySection) {
15445 // Any array section is currently allowed. Allowing a whole size array
15446 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015447 //
15448 // If this array section refers to the whole dimension we can still
15449 // accept other array sections before this one, except if the base is a
15450 // pointer. Otherwise, only unitary sections are accepted.
15451 if (NotWhole || IsPointer)
15452 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015453 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015454 // A unity or whole array section is not allowed and that is not
15455 // compatible with the properties of the current array section.
15456 SemaRef.Diag(
15457 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15458 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015459 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015460 }
Samuel Antao90927002016-04-26 14:54:23 +000015461
Patrick Lystere13b1e32019-01-02 19:28:48 +000015462 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15463 Expr::EvalResult ResultR;
15464 Expr::EvalResult ResultL;
15465 if (CurE->getLength()->EvaluateAsInt(ResultR,
15466 SemaRef.getASTContext())) {
15467 if (!ResultR.Val.getInt().isOneValue()) {
15468 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15469 diag::err_omp_invalid_map_this_expr);
15470 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15471 diag::note_omp_invalid_length_on_this_ptr_mapping);
15472 }
15473 }
15474 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15475 ResultL, SemaRef.getASTContext())) {
15476 if (!ResultL.Val.getInt().isNullValue()) {
15477 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15478 diag::err_omp_invalid_map_this_expr);
15479 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15480 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15481 }
15482 }
15483 RelevantExpr = TE;
15484 }
15485
Samuel Antao90927002016-04-26 14:54:23 +000015486 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015487 CurComponents.emplace_back(CurE, nullptr);
15488 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015489 if (!NoDiagnose) {
15490 // If nothing else worked, this is not a valid map clause expression.
15491 SemaRef.Diag(
15492 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15493 << ERange;
15494 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015495 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015496 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015497 }
15498
15499 return RelevantExpr;
15500}
15501
15502// Return true if expression E associated with value VD has conflicts with other
15503// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015504static bool checkMapConflicts(
15505 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015506 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015507 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15508 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015509 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015510 SourceLocation ELoc = E->getExprLoc();
15511 SourceRange ERange = E->getSourceRange();
15512
15513 // In order to easily check the conflicts we need to match each component of
15514 // the expression under test with the components of the expressions that are
15515 // already in the stack.
15516
Samuel Antao5de996e2016-01-22 20:21:36 +000015517 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015518 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015519 "Map clause expression with unexpected base!");
15520
15521 // Variables to help detecting enclosing problems in data environment nests.
15522 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015523 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015524
Samuel Antao90927002016-04-26 14:54:23 +000015525 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15526 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015527 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15528 ERange, CKind, &EnclosingExpr,
15529 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15530 StackComponents,
15531 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015532 assert(!StackComponents.empty() &&
15533 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015534 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015535 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015536 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015537
Samuel Antao90927002016-04-26 14:54:23 +000015538 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015539 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015540
Samuel Antao5de996e2016-01-22 20:21:36 +000015541 // Expressions must start from the same base. Here we detect at which
15542 // point both expressions diverge from each other and see if we can
15543 // detect if the memory referred to both expressions is contiguous and
15544 // do not overlap.
15545 auto CI = CurComponents.rbegin();
15546 auto CE = CurComponents.rend();
15547 auto SI = StackComponents.rbegin();
15548 auto SE = StackComponents.rend();
15549 for (; CI != CE && SI != SE; ++CI, ++SI) {
15550
15551 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15552 // At most one list item can be an array item derived from a given
15553 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015554 if (CurrentRegionOnly &&
15555 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15556 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15557 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15558 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15559 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015560 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015561 << CI->getAssociatedExpression()->getSourceRange();
15562 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15563 diag::note_used_here)
15564 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015565 return true;
15566 }
15567
15568 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015569 if (CI->getAssociatedExpression()->getStmtClass() !=
15570 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015571 break;
15572
15573 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015574 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015575 break;
15576 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015577 // Check if the extra components of the expressions in the enclosing
15578 // data environment are redundant for the current base declaration.
15579 // If they are, the maps completely overlap, which is legal.
15580 for (; SI != SE; ++SI) {
15581 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015582 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015583 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015584 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015585 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015586 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015587 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015588 Type =
15589 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15590 }
15591 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015592 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015593 SemaRef, SI->getAssociatedExpression(), Type))
15594 break;
15595 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015596
15597 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15598 // List items of map clauses in the same construct must not share
15599 // original storage.
15600 //
15601 // If the expressions are exactly the same or one is a subset of the
15602 // other, it means they are sharing storage.
15603 if (CI == CE && SI == SE) {
15604 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015605 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015606 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015607 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015608 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015609 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15610 << ERange;
15611 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015612 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15613 << RE->getSourceRange();
15614 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015615 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015616 // If we find the same expression in the enclosing data environment,
15617 // that is legal.
15618 IsEnclosedByDataEnvironmentExpr = true;
15619 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015620 }
15621
Samuel Antao90927002016-04-26 14:54:23 +000015622 QualType DerivedType =
15623 std::prev(CI)->getAssociatedDeclaration()->getType();
15624 SourceLocation DerivedLoc =
15625 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015626
15627 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15628 // If the type of a list item is a reference to a type T then the type
15629 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015630 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015631
15632 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15633 // A variable for which the type is pointer and an array section
15634 // derived from that variable must not appear as list items of map
15635 // clauses of the same construct.
15636 //
15637 // Also, cover one of the cases in:
15638 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15639 // If any part of the original storage of a list item has corresponding
15640 // storage in the device data environment, all of the original storage
15641 // must have corresponding storage in the device data environment.
15642 //
15643 if (DerivedType->isAnyPointerType()) {
15644 if (CI == CE || SI == SE) {
15645 SemaRef.Diag(
15646 DerivedLoc,
15647 diag::err_omp_pointer_mapped_along_with_derived_section)
15648 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015649 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15650 << RE->getSourceRange();
15651 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015652 }
15653 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015654 SI->getAssociatedExpression()->getStmtClass() ||
15655 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15656 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015657 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015658 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015659 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015660 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15661 << RE->getSourceRange();
15662 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015663 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015664 }
15665
15666 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15667 // List items of map clauses in the same construct must not share
15668 // original storage.
15669 //
15670 // An expression is a subset of the other.
15671 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015672 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015673 if (CI != CE || SI != SE) {
15674 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15675 // a pointer.
15676 auto Begin =
15677 CI != CE ? CurComponents.begin() : StackComponents.begin();
15678 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15679 auto It = Begin;
15680 while (It != End && !It->getAssociatedDeclaration())
15681 std::advance(It, 1);
15682 assert(It != End &&
15683 "Expected at least one component with the declaration.");
15684 if (It != Begin && It->getAssociatedDeclaration()
15685 ->getType()
15686 .getCanonicalType()
15687 ->isAnyPointerType()) {
15688 IsEnclosedByDataEnvironmentExpr = false;
15689 EnclosingExpr = nullptr;
15690 return false;
15691 }
15692 }
Samuel Antao661c0902016-05-26 17:39:58 +000015693 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015694 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015695 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015696 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15697 << ERange;
15698 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015699 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15700 << RE->getSourceRange();
15701 return true;
15702 }
15703
15704 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015705 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015706 if (!CurrentRegionOnly && SI != SE)
15707 EnclosingExpr = RE;
15708
15709 // The current expression is a subset of the expression in the data
15710 // environment.
15711 IsEnclosedByDataEnvironmentExpr |=
15712 (!CurrentRegionOnly && CI != CE && SI == SE);
15713
15714 return false;
15715 });
15716
15717 if (CurrentRegionOnly)
15718 return FoundError;
15719
15720 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15721 // If any part of the original storage of a list item has corresponding
15722 // storage in the device data environment, all of the original storage must
15723 // have corresponding storage in the device data environment.
15724 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15725 // If a list item is an element of a structure, and a different element of
15726 // the structure has a corresponding list item in the device data environment
15727 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015728 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015729 // data environment prior to the task encountering the construct.
15730 //
15731 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15732 SemaRef.Diag(ELoc,
15733 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15734 << ERange;
15735 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15736 << EnclosingExpr->getSourceRange();
15737 return true;
15738 }
15739
15740 return FoundError;
15741}
15742
Michael Kruse4304e9d2019-02-19 16:38:20 +000015743// Look up the user-defined mapper given the mapper name and mapped type, and
15744// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015745static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15746 CXXScopeSpec &MapperIdScopeSpec,
15747 const DeclarationNameInfo &MapperId,
15748 QualType Type,
15749 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015750 if (MapperIdScopeSpec.isInvalid())
15751 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015752 // Get the actual type for the array type.
15753 if (Type->isArrayType()) {
15754 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15755 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15756 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015757 // Find all user-defined mappers with the given MapperId.
15758 SmallVector<UnresolvedSet<8>, 4> Lookups;
15759 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15760 Lookup.suppressDiagnostics();
15761 if (S) {
15762 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15763 NamedDecl *D = Lookup.getRepresentativeDecl();
15764 while (S && !S->isDeclScope(D))
15765 S = S->getParent();
15766 if (S)
15767 S = S->getParent();
15768 Lookups.emplace_back();
15769 Lookups.back().append(Lookup.begin(), Lookup.end());
15770 Lookup.clear();
15771 }
15772 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15773 // Extract the user-defined mappers with the given MapperId.
15774 Lookups.push_back(UnresolvedSet<8>());
15775 for (NamedDecl *D : ULE->decls()) {
15776 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15777 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15778 Lookups.back().addDecl(DMD);
15779 }
15780 }
15781 // Defer the lookup for dependent types. The results will be passed through
15782 // UnresolvedMapper on instantiation.
15783 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15784 Type->isInstantiationDependentType() ||
15785 Type->containsUnexpandedParameterPack() ||
15786 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15787 return !D->isInvalidDecl() &&
15788 (D->getType()->isDependentType() ||
15789 D->getType()->isInstantiationDependentType() ||
15790 D->getType()->containsUnexpandedParameterPack());
15791 })) {
15792 UnresolvedSet<8> URS;
15793 for (const UnresolvedSet<8> &Set : Lookups) {
15794 if (Set.empty())
15795 continue;
15796 URS.append(Set.begin(), Set.end());
15797 }
15798 return UnresolvedLookupExpr::Create(
15799 SemaRef.Context, /*NamingClass=*/nullptr,
15800 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15801 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15802 }
Michael Kruse945249b2019-09-26 22:53:01 +000015803 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015804 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15805 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015806 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15807 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15808 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15809 return ExprError();
15810 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015811 // Perform argument dependent lookup.
15812 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15813 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15814 // Return the first user-defined mapper with the desired type.
15815 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15816 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15817 if (!D->isInvalidDecl() &&
15818 SemaRef.Context.hasSameType(D->getType(), Type))
15819 return D;
15820 return nullptr;
15821 }))
15822 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15823 // Find the first user-defined mapper with a type derived from the desired
15824 // type.
15825 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15826 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15827 if (!D->isInvalidDecl() &&
15828 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15829 !Type.isMoreQualifiedThan(D->getType()))
15830 return D;
15831 return nullptr;
15832 })) {
15833 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15834 /*DetectVirtual=*/false);
15835 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15836 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15837 VD->getType().getUnqualifiedType()))) {
15838 if (SemaRef.CheckBaseClassAccess(
15839 Loc, VD->getType(), Type, Paths.front(),
15840 /*DiagID=*/0) != Sema::AR_inaccessible) {
15841 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15842 }
15843 }
15844 }
15845 }
15846 // Report error if a mapper is specified, but cannot be found.
15847 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15848 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15849 << Type << MapperId.getName();
15850 return ExprError();
15851 }
15852 return ExprEmpty();
15853}
15854
Samuel Antao661c0902016-05-26 17:39:58 +000015855namespace {
15856// Utility struct that gathers all the related lists associated with a mappable
15857// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015858struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015859 // The list of expressions.
15860 ArrayRef<Expr *> VarList;
15861 // The list of processed expressions.
15862 SmallVector<Expr *, 16> ProcessedVarList;
15863 // The mappble components for each expression.
15864 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15865 // The base declaration of the variable.
15866 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015867 // The reference to the user-defined mapper associated with every expression.
15868 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015869
15870 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15871 // We have a list of components and base declarations for each entry in the
15872 // variable list.
15873 VarComponents.reserve(VarList.size());
15874 VarBaseDeclarations.reserve(VarList.size());
15875 }
15876};
15877}
15878
15879// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015880// \a CKind. In the check process the valid expressions, mappable expression
15881// components, variables, and user-defined mappers are extracted and used to
15882// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15883// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15884// and \a MapperId are expected to be valid if the clause kind is 'map'.
15885static void checkMappableExpressionList(
15886 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15887 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015888 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15889 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015890 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015891 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015892 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15893 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015894 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015895
15896 // If the identifier of user-defined mapper is not specified, it is "default".
15897 // We do not change the actual name in this clause to distinguish whether a
15898 // mapper is specified explicitly, i.e., it is not explicitly specified when
15899 // MapperId.getName() is empty.
15900 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15901 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15902 MapperId.setName(DeclNames.getIdentifier(
15903 &SemaRef.getASTContext().Idents.get("default")));
15904 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015905
15906 // Iterators to find the current unresolved mapper expression.
15907 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15908 bool UpdateUMIt = false;
15909 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015910
Samuel Antao90927002016-04-26 14:54:23 +000015911 // Keep track of the mappable components and base declarations in this clause.
15912 // Each entry in the list is going to have a list of components associated. We
15913 // record each set of the components so that we can build the clause later on.
15914 // In the end we should have the same amount of declarations and component
15915 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015916
Alexey Bataeve3727102018-04-18 15:57:46 +000015917 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015918 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015919 SourceLocation ELoc = RE->getExprLoc();
15920
Michael Kruse4304e9d2019-02-19 16:38:20 +000015921 // Find the current unresolved mapper expression.
15922 if (UpdateUMIt && UMIt != UMEnd) {
15923 UMIt++;
15924 assert(
15925 UMIt != UMEnd &&
15926 "Expect the size of UnresolvedMappers to match with that of VarList");
15927 }
15928 UpdateUMIt = true;
15929 if (UMIt != UMEnd)
15930 UnresolvedMapper = *UMIt;
15931
Alexey Bataeve3727102018-04-18 15:57:46 +000015932 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015933
15934 if (VE->isValueDependent() || VE->isTypeDependent() ||
15935 VE->isInstantiationDependent() ||
15936 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015937 // Try to find the associated user-defined mapper.
15938 ExprResult ER = buildUserDefinedMapperRef(
15939 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15940 VE->getType().getCanonicalType(), UnresolvedMapper);
15941 if (ER.isInvalid())
15942 continue;
15943 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015944 // We can only analyze this information once the missing information is
15945 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015946 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015947 continue;
15948 }
15949
Alexey Bataeve3727102018-04-18 15:57:46 +000015950 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015951
Samuel Antao5de996e2016-01-22 20:21:36 +000015952 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015953 SemaRef.Diag(ELoc,
15954 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015955 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015956 continue;
15957 }
15958
Samuel Antao90927002016-04-26 14:54:23 +000015959 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15960 ValueDecl *CurDeclaration = nullptr;
15961
15962 // Obtain the array or member expression bases if required. Also, fill the
15963 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015964 const Expr *BE = checkMapClauseExpressionBase(
15965 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015966 if (!BE)
15967 continue;
15968
Samuel Antao90927002016-04-26 14:54:23 +000015969 assert(!CurComponents.empty() &&
15970 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015971
Patrick Lystere13b1e32019-01-02 19:28:48 +000015972 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15973 // Add store "this" pointer to class in DSAStackTy for future checking
15974 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015975 // Try to find the associated user-defined mapper.
15976 ExprResult ER = buildUserDefinedMapperRef(
15977 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15978 VE->getType().getCanonicalType(), UnresolvedMapper);
15979 if (ER.isInvalid())
15980 continue;
15981 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015982 // Skip restriction checking for variable or field declarations
15983 MVLI.ProcessedVarList.push_back(RE);
15984 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15985 MVLI.VarComponents.back().append(CurComponents.begin(),
15986 CurComponents.end());
15987 MVLI.VarBaseDeclarations.push_back(nullptr);
15988 continue;
15989 }
15990
Samuel Antao90927002016-04-26 14:54:23 +000015991 // For the following checks, we rely on the base declaration which is
15992 // expected to be associated with the last component. The declaration is
15993 // expected to be a variable or a field (if 'this' is being mapped).
15994 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15995 assert(CurDeclaration && "Null decl on map clause.");
15996 assert(
15997 CurDeclaration->isCanonicalDecl() &&
15998 "Expecting components to have associated only canonical declarations.");
15999
16000 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000016001 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000016002
16003 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000016004 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000016005
16006 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000016007 // threadprivate variables cannot appear in a map clause.
16008 // OpenMP 4.5 [2.10.5, target update Construct]
16009 // threadprivate variables cannot appear in a from clause.
16010 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016011 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016012 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
16013 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000016014 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016015 continue;
16016 }
16017
Samuel Antao5de996e2016-01-22 20:21:36 +000016018 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
16019 // A list item cannot appear in both a map clause and a data-sharing
16020 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000016021
Samuel Antao5de996e2016-01-22 20:21:36 +000016022 // Check conflicts with other map clause expressions. We check the conflicts
16023 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000016024 // environment, because the restrictions are different. We only have to
16025 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000016026 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016027 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016028 break;
Samuel Antao661c0902016-05-26 17:39:58 +000016029 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000016030 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016031 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016032 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016033
Samuel Antao661c0902016-05-26 17:39:58 +000016034 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000016035 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16036 // If the type of a list item is a reference to a type T then the type will
16037 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000016038 auto I = llvm::find_if(
16039 CurComponents,
16040 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
16041 return MC.getAssociatedDeclaration();
16042 });
16043 assert(I != CurComponents.end() && "Null decl on map clause.");
Alexey Bataev48bad082020-01-14 14:13:47 -050016044 QualType Type;
16045 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
16046 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
16047 if (ASE) {
16048 Type = ASE->getType().getNonReferenceType();
16049 } else if (OASE) {
16050 QualType BaseType =
16051 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16052 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16053 Type = ATy->getElementType();
16054 else
16055 Type = BaseType->getPointeeType();
16056 Type = Type.getNonReferenceType();
16057 } else {
16058 Type = VE->getType();
16059 }
Samuel Antao5de996e2016-01-22 20:21:36 +000016060
Samuel Antao661c0902016-05-26 17:39:58 +000016061 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
16062 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000016063 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000016064 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000016065 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000016066 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000016067 continue;
16068
Alexey Bataev48bad082020-01-14 14:13:47 -050016069 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
16070
Samuel Antao661c0902016-05-26 17:39:58 +000016071 if (CKind == OMPC_map) {
16072 // target enter data
16073 // OpenMP [2.10.2, Restrictions, p. 99]
16074 // A map-type must be specified in all map clauses and must be either
16075 // to or alloc.
16076 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
16077 if (DKind == OMPD_target_enter_data &&
16078 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
16079 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16080 << (IsMapTypeImplicit ? 1 : 0)
16081 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16082 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016083 continue;
16084 }
Samuel Antao661c0902016-05-26 17:39:58 +000016085
16086 // target exit_data
16087 // OpenMP [2.10.3, Restrictions, p. 102]
16088 // A map-type must be specified in all map clauses and must be either
16089 // from, release, or delete.
16090 if (DKind == OMPD_target_exit_data &&
16091 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
16092 MapType == OMPC_MAP_delete)) {
16093 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16094 << (IsMapTypeImplicit ? 1 : 0)
16095 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16096 << getOpenMPDirectiveName(DKind);
16097 continue;
16098 }
16099
16100 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16101 // A list item cannot appear in both a map clause and a data-sharing
16102 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016103 //
16104 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16105 // A list item cannot appear in both a map clause and a data-sharing
16106 // attribute clause on the same construct unless the construct is a
16107 // combined construct.
16108 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16109 isOpenMPTargetExecutionDirective(DKind)) ||
16110 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016111 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016112 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016113 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016114 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016115 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016116 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016117 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016118 continue;
16119 }
16120 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016121 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016122
Michael Kruse01f670d2019-02-22 22:29:42 +000016123 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016124 ExprResult ER = buildUserDefinedMapperRef(
16125 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16126 Type.getCanonicalType(), UnresolvedMapper);
16127 if (ER.isInvalid())
16128 continue;
16129 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016130
Samuel Antao90927002016-04-26 14:54:23 +000016131 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016132 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016133
16134 // Store the components in the stack so that they can be used to check
16135 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016136 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16137 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016138
16139 // Save the components and declaration to create the clause. For purposes of
16140 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016141 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016142 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16143 MVLI.VarComponents.back().append(CurComponents.begin(),
16144 CurComponents.end());
16145 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16146 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016147 }
Samuel Antao661c0902016-05-26 17:39:58 +000016148}
16149
Michael Kruse4304e9d2019-02-19 16:38:20 +000016150OMPClause *Sema::ActOnOpenMPMapClause(
16151 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16152 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16153 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16154 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16155 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16156 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16157 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16158 OMPC_MAP_MODIFIER_unknown,
16159 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016160 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16161
16162 // Process map-type-modifiers, flag errors for duplicate modifiers.
16163 unsigned Count = 0;
16164 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16165 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16166 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16167 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16168 continue;
16169 }
16170 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016171 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016172 Modifiers[Count] = MapTypeModifiers[I];
16173 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16174 ++Count;
16175 }
16176
Michael Kruse4304e9d2019-02-19 16:38:20 +000016177 MappableVarListInfo MVLI(VarList);
16178 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016179 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16180 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016181
Samuel Antao5de996e2016-01-22 20:21:36 +000016182 // We need to produce a map clause even if we don't have variables so that
16183 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016184 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16185 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16186 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16187 MapperIdScopeSpec.getWithLocInContext(Context),
16188 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016189}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016190
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016191QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16192 TypeResult ParsedType) {
16193 assert(ParsedType.isUsable());
16194
16195 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16196 if (ReductionType.isNull())
16197 return QualType();
16198
16199 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16200 // A type name in a declare reduction directive cannot be a function type, an
16201 // array type, a reference type, or a type qualified with const, volatile or
16202 // restrict.
16203 if (ReductionType.hasQualifiers()) {
16204 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16205 return QualType();
16206 }
16207
16208 if (ReductionType->isFunctionType()) {
16209 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16210 return QualType();
16211 }
16212 if (ReductionType->isReferenceType()) {
16213 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16214 return QualType();
16215 }
16216 if (ReductionType->isArrayType()) {
16217 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16218 return QualType();
16219 }
16220 return ReductionType;
16221}
16222
16223Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16224 Scope *S, DeclContext *DC, DeclarationName Name,
16225 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16226 AccessSpecifier AS, Decl *PrevDeclInScope) {
16227 SmallVector<Decl *, 8> Decls;
16228 Decls.reserve(ReductionTypes.size());
16229
16230 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016231 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016232 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16233 // A reduction-identifier may not be re-declared in the current scope for the
16234 // same type or for a type that is compatible according to the base language
16235 // rules.
16236 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16237 OMPDeclareReductionDecl *PrevDRD = nullptr;
16238 bool InCompoundScope = true;
16239 if (S != nullptr) {
16240 // Find previous declaration with the same name not referenced in other
16241 // declarations.
16242 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16243 InCompoundScope =
16244 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16245 LookupName(Lookup, S);
16246 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16247 /*AllowInlineNamespace=*/false);
16248 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016249 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016250 while (Filter.hasNext()) {
16251 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16252 if (InCompoundScope) {
16253 auto I = UsedAsPrevious.find(PrevDecl);
16254 if (I == UsedAsPrevious.end())
16255 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016256 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016257 UsedAsPrevious[D] = true;
16258 }
16259 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16260 PrevDecl->getLocation();
16261 }
16262 Filter.done();
16263 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016264 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016265 if (!PrevData.second) {
16266 PrevDRD = PrevData.first;
16267 break;
16268 }
16269 }
16270 }
16271 } else if (PrevDeclInScope != nullptr) {
16272 auto *PrevDRDInScope = PrevDRD =
16273 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16274 do {
16275 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16276 PrevDRDInScope->getLocation();
16277 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16278 } while (PrevDRDInScope != nullptr);
16279 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016280 for (const auto &TyData : ReductionTypes) {
16281 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016282 bool Invalid = false;
16283 if (I != PreviousRedeclTypes.end()) {
16284 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16285 << TyData.first;
16286 Diag(I->second, diag::note_previous_definition);
16287 Invalid = true;
16288 }
16289 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16290 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16291 Name, TyData.first, PrevDRD);
16292 DC->addDecl(DRD);
16293 DRD->setAccess(AS);
16294 Decls.push_back(DRD);
16295 if (Invalid)
16296 DRD->setInvalidDecl();
16297 else
16298 PrevDRD = DRD;
16299 }
16300
16301 return DeclGroupPtrTy::make(
16302 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16303}
16304
16305void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16306 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16307
16308 // Enter new function scope.
16309 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016310 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016311 getCurFunction()->setHasOMPDeclareReductionCombiner();
16312
16313 if (S != nullptr)
16314 PushDeclContext(S, DRD);
16315 else
16316 CurContext = DRD;
16317
Faisal Valid143a0c2017-04-01 21:30:49 +000016318 PushExpressionEvaluationContext(
16319 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016320
16321 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016322 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16323 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16324 // uses semantics of argument handles by value, but it should be passed by
16325 // reference. C lang does not support references, so pass all parameters as
16326 // pointers.
16327 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016328 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016329 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016330 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16331 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16332 // uses semantics of argument handles by value, but it should be passed by
16333 // reference. C lang does not support references, so pass all parameters as
16334 // pointers.
16335 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016336 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016337 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16338 if (S != nullptr) {
16339 PushOnScopeChains(OmpInParm, S);
16340 PushOnScopeChains(OmpOutParm, S);
16341 } else {
16342 DRD->addDecl(OmpInParm);
16343 DRD->addDecl(OmpOutParm);
16344 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016345 Expr *InE =
16346 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16347 Expr *OutE =
16348 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16349 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016350}
16351
16352void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16353 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16354 DiscardCleanupsInEvaluationContext();
16355 PopExpressionEvaluationContext();
16356
16357 PopDeclContext();
16358 PopFunctionScopeInfo();
16359
16360 if (Combiner != nullptr)
16361 DRD->setCombiner(Combiner);
16362 else
16363 DRD->setInvalidDecl();
16364}
16365
Alexey Bataev070f43a2017-09-06 14:49:58 +000016366VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016367 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16368
16369 // Enter new function scope.
16370 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016371 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016372
16373 if (S != nullptr)
16374 PushDeclContext(S, DRD);
16375 else
16376 CurContext = DRD;
16377
Faisal Valid143a0c2017-04-01 21:30:49 +000016378 PushExpressionEvaluationContext(
16379 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016380
16381 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016382 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16383 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16384 // uses semantics of argument handles by value, but it should be passed by
16385 // reference. C lang does not support references, so pass all parameters as
16386 // pointers.
16387 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016388 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016389 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016390 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16391 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16392 // uses semantics of argument handles by value, but it should be passed by
16393 // reference. C lang does not support references, so pass all parameters as
16394 // pointers.
16395 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016396 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016397 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016398 if (S != nullptr) {
16399 PushOnScopeChains(OmpPrivParm, S);
16400 PushOnScopeChains(OmpOrigParm, S);
16401 } else {
16402 DRD->addDecl(OmpPrivParm);
16403 DRD->addDecl(OmpOrigParm);
16404 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016405 Expr *OrigE =
16406 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16407 Expr *PrivE =
16408 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16409 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016410 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016411}
16412
Alexey Bataev070f43a2017-09-06 14:49:58 +000016413void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16414 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016415 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16416 DiscardCleanupsInEvaluationContext();
16417 PopExpressionEvaluationContext();
16418
16419 PopDeclContext();
16420 PopFunctionScopeInfo();
16421
Alexey Bataev070f43a2017-09-06 14:49:58 +000016422 if (Initializer != nullptr) {
16423 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16424 } else if (OmpPrivParm->hasInit()) {
16425 DRD->setInitializer(OmpPrivParm->getInit(),
16426 OmpPrivParm->isDirectInit()
16427 ? OMPDeclareReductionDecl::DirectInit
16428 : OMPDeclareReductionDecl::CopyInit);
16429 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016430 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016431 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016432}
16433
16434Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16435 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016436 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016437 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016438 if (S)
16439 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16440 /*AddToContext=*/false);
16441 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016442 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016443 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016444 }
16445 return DeclReductions;
16446}
16447
Michael Kruse251e1482019-02-01 20:25:04 +000016448TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16449 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16450 QualType T = TInfo->getType();
16451 if (D.isInvalidType())
16452 return true;
16453
16454 if (getLangOpts().CPlusPlus) {
16455 // Check that there are no default arguments (C++ only).
16456 CheckExtraCXXDefaultArguments(D);
16457 }
16458
16459 return CreateParsedType(T, TInfo);
16460}
16461
16462QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16463 TypeResult ParsedType) {
16464 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16465
16466 QualType MapperType = GetTypeFromParser(ParsedType.get());
16467 assert(!MapperType.isNull() && "Expect valid mapper type");
16468
16469 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16470 // The type must be of struct, union or class type in C and C++
16471 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16472 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16473 return QualType();
16474 }
16475 return MapperType;
16476}
16477
16478OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16479 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16480 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16481 Decl *PrevDeclInScope) {
16482 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16483 forRedeclarationInCurContext());
16484 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16485 // A mapper-identifier may not be redeclared in the current scope for the
16486 // same type or for a type that is compatible according to the base language
16487 // rules.
16488 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16489 OMPDeclareMapperDecl *PrevDMD = nullptr;
16490 bool InCompoundScope = true;
16491 if (S != nullptr) {
16492 // Find previous declaration with the same name not referenced in other
16493 // declarations.
16494 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16495 InCompoundScope =
16496 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16497 LookupName(Lookup, S);
16498 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16499 /*AllowInlineNamespace=*/false);
16500 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16501 LookupResult::Filter Filter = Lookup.makeFilter();
16502 while (Filter.hasNext()) {
16503 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16504 if (InCompoundScope) {
16505 auto I = UsedAsPrevious.find(PrevDecl);
16506 if (I == UsedAsPrevious.end())
16507 UsedAsPrevious[PrevDecl] = false;
16508 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16509 UsedAsPrevious[D] = true;
16510 }
16511 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16512 PrevDecl->getLocation();
16513 }
16514 Filter.done();
16515 if (InCompoundScope) {
16516 for (const auto &PrevData : UsedAsPrevious) {
16517 if (!PrevData.second) {
16518 PrevDMD = PrevData.first;
16519 break;
16520 }
16521 }
16522 }
16523 } else if (PrevDeclInScope) {
16524 auto *PrevDMDInScope = PrevDMD =
16525 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16526 do {
16527 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16528 PrevDMDInScope->getLocation();
16529 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16530 } while (PrevDMDInScope != nullptr);
16531 }
16532 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16533 bool Invalid = false;
16534 if (I != PreviousRedeclTypes.end()) {
16535 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16536 << MapperType << Name;
16537 Diag(I->second, diag::note_previous_definition);
16538 Invalid = true;
16539 }
16540 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16541 MapperType, VN, PrevDMD);
16542 DC->addDecl(DMD);
16543 DMD->setAccess(AS);
16544 if (Invalid)
16545 DMD->setInvalidDecl();
16546
16547 // Enter new function scope.
16548 PushFunctionScope();
16549 setFunctionHasBranchProtectedScope();
16550
16551 CurContext = DMD;
16552
16553 return DMD;
16554}
16555
16556void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16557 Scope *S,
16558 QualType MapperType,
16559 SourceLocation StartLoc,
16560 DeclarationName VN) {
16561 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16562 if (S)
16563 PushOnScopeChains(VD, S);
16564 else
16565 DMD->addDecl(VD);
16566 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16567 DMD->setMapperVarRef(MapperVarRefExpr);
16568}
16569
16570Sema::DeclGroupPtrTy
16571Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16572 ArrayRef<OMPClause *> ClauseList) {
16573 PopDeclContext();
16574 PopFunctionScopeInfo();
16575
16576 if (D) {
16577 if (S)
16578 PushOnScopeChains(D, S, /*AddToContext=*/false);
16579 D->CreateClauses(Context, ClauseList);
16580 }
16581
16582 return DeclGroupPtrTy::make(DeclGroupRef(D));
16583}
16584
David Majnemer9d168222016-08-05 17:44:54 +000016585OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016586 SourceLocation StartLoc,
16587 SourceLocation LParenLoc,
16588 SourceLocation EndLoc) {
16589 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016590 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016591
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016592 // OpenMP [teams Constrcut, Restrictions]
16593 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016594 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016595 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016596 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016597
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016598 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016599 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016600 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016601 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016602 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016603 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016604 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16605 HelperValStmt = buildPreInits(Context, Captures);
16606 }
16607
16608 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16609 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016610}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016611
16612OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16613 SourceLocation StartLoc,
16614 SourceLocation LParenLoc,
16615 SourceLocation EndLoc) {
16616 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016617 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016618
16619 // OpenMP [teams Constrcut, Restrictions]
16620 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016621 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016622 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016623 return nullptr;
16624
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016625 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016626 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16627 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016628 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016629 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016630 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016631 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16632 HelperValStmt = buildPreInits(Context, Captures);
16633 }
16634
16635 return new (Context) OMPThreadLimitClause(
16636 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016637}
Alexey Bataeva0569352015-12-01 10:17:31 +000016638
16639OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16640 SourceLocation StartLoc,
16641 SourceLocation LParenLoc,
16642 SourceLocation EndLoc) {
16643 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016644 Stmt *HelperValStmt = nullptr;
16645 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016646
16647 // OpenMP [2.9.1, task Constrcut]
16648 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016649 if (!isNonNegativeIntegerValue(
16650 ValExpr, *this, OMPC_priority,
16651 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16652 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016653 return nullptr;
16654
Alexey Bataev31ba4762019-10-16 18:09:37 +000016655 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16656 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016657}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016658
16659OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16660 SourceLocation StartLoc,
16661 SourceLocation LParenLoc,
16662 SourceLocation EndLoc) {
16663 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016664 Stmt *HelperValStmt = nullptr;
16665 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016666
16667 // OpenMP [2.9.2, taskloop Constrcut]
16668 // The parameter of the grainsize clause must be a positive integer
16669 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016670 if (!isNonNegativeIntegerValue(
16671 ValExpr, *this, OMPC_grainsize,
16672 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16673 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016674 return nullptr;
16675
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016676 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16677 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016678}
Alexey Bataev382967a2015-12-08 12:06:20 +000016679
16680OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16681 SourceLocation StartLoc,
16682 SourceLocation LParenLoc,
16683 SourceLocation EndLoc) {
16684 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016685 Stmt *HelperValStmt = nullptr;
16686 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016687
16688 // OpenMP [2.9.2, taskloop Constrcut]
16689 // The parameter of the num_tasks clause must be a positive integer
16690 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016691 if (!isNonNegativeIntegerValue(
16692 ValExpr, *this, OMPC_num_tasks,
16693 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16694 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016695 return nullptr;
16696
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016697 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16698 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016699}
16700
Alexey Bataev28c75412015-12-15 08:19:24 +000016701OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16702 SourceLocation LParenLoc,
16703 SourceLocation EndLoc) {
16704 // OpenMP [2.13.2, critical construct, Description]
16705 // ... where hint-expression is an integer constant expression that evaluates
16706 // to a valid lock hint.
16707 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16708 if (HintExpr.isInvalid())
16709 return nullptr;
16710 return new (Context)
16711 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16712}
16713
Carlo Bertollib4adf552016-01-15 18:50:31 +000016714OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16715 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16716 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16717 SourceLocation EndLoc) {
16718 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16719 std::string Values;
16720 Values += "'";
16721 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16722 Values += "'";
16723 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16724 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16725 return nullptr;
16726 }
16727 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016728 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016729 if (ChunkSize) {
16730 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16731 !ChunkSize->isInstantiationDependent() &&
16732 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016733 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016734 ExprResult Val =
16735 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16736 if (Val.isInvalid())
16737 return nullptr;
16738
16739 ValExpr = Val.get();
16740
16741 // OpenMP [2.7.1, Restrictions]
16742 // chunk_size must be a loop invariant integer expression with a positive
16743 // value.
16744 llvm::APSInt Result;
16745 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16746 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16747 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16748 << "dist_schedule" << ChunkSize->getSourceRange();
16749 return nullptr;
16750 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016751 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016752 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16753 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016754 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016755 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016756 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016757 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16758 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016759 }
16760 }
16761 }
16762
16763 return new (Context)
16764 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016765 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016766}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016767
16768OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16769 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16770 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16771 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016772 if (getLangOpts().OpenMP < 50) {
16773 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16774 Kind != OMPC_DEFAULTMAP_scalar) {
16775 std::string Value;
16776 SourceLocation Loc;
16777 Value += "'";
16778 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16779 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16780 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16781 Loc = MLoc;
16782 } else {
16783 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16784 OMPC_DEFAULTMAP_scalar);
16785 Loc = KindLoc;
16786 }
16787 Value += "'";
16788 Diag(Loc, diag::err_omp_unexpected_clause_value)
16789 << Value << getOpenMPClauseName(OMPC_defaultmap);
16790 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016791 }
cchene06f3e02019-11-15 13:02:06 -050016792 } else {
16793 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16794 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16795 if (!isDefaultmapKind || !isDefaultmapModifier) {
16796 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16797 "'firstprivate', 'none', 'default'";
16798 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16799 if (!isDefaultmapKind && isDefaultmapModifier) {
16800 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16801 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16802 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16803 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16804 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16805 } else {
16806 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16807 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16808 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16809 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16810 }
16811 return nullptr;
16812 }
16813
16814 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16815 // At most one defaultmap clause for each category can appear on the
16816 // directive.
16817 if (DSAStack->checkDefaultmapCategory(Kind)) {
16818 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16819 return nullptr;
16820 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016821 }
cchene06f3e02019-11-15 13:02:06 -050016822 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016823
16824 return new (Context)
16825 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16826}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016827
16828bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16829 DeclContext *CurLexicalContext = getCurLexicalContext();
16830 if (!CurLexicalContext->isFileContext() &&
16831 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016832 !CurLexicalContext->isExternCXXContext() &&
16833 !isa<CXXRecordDecl>(CurLexicalContext) &&
16834 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16835 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16836 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016837 Diag(Loc, diag::err_omp_region_not_file_context);
16838 return false;
16839 }
Kelvin Libc38e632018-09-10 02:07:09 +000016840 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016841 return true;
16842}
16843
16844void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016845 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016846 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016847 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016848}
16849
Alexey Bataev729e2422019-08-23 16:11:14 +000016850NamedDecl *
16851Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16852 const DeclarationNameInfo &Id,
16853 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016854 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16855 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16856
16857 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016858 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016859 Lookup.suppressDiagnostics();
16860
16861 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016862 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016863 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016864 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016865 CTK_ErrorRecovery)) {
16866 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16867 << Id.getName());
16868 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016869 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016870 }
16871
16872 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016873 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016874 }
16875
16876 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016877 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16878 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016879 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016880 return nullptr;
16881 }
16882 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16883 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16884 return ND;
16885}
16886
16887void Sema::ActOnOpenMPDeclareTargetName(
16888 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16889 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16890 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16891 isa<FunctionTemplateDecl>(ND)) &&
16892 "Expected variable, function or function template.");
16893
16894 // Diagnose marking after use as it may lead to incorrect diagnosis and
16895 // codegen.
16896 if (LangOpts.OpenMP >= 50 &&
16897 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16898 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16899
16900 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16901 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16902 if (DevTy.hasValue() && *DevTy != DT) {
16903 Diag(Loc, diag::err_omp_device_type_mismatch)
16904 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16905 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16906 return;
16907 }
16908 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16909 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16910 if (!Res) {
16911 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16912 SourceRange(Loc, Loc));
16913 ND->addAttr(A);
16914 if (ASTMutationListener *ML = Context.getASTMutationListener())
16915 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16916 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16917 } else if (*Res != MT) {
16918 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016919 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016920}
16921
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016922static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16923 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016924 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016925 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016926 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016927 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16928 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16929 if (SemaRef.LangOpts.OpenMP >= 50 &&
16930 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16931 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16932 VD->hasGlobalStorage()) {
16933 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16934 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16935 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16936 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16937 // If a lambda declaration and definition appears between a
16938 // declare target directive and the matching end declare target
16939 // directive, all variables that are captured by the lambda
16940 // expression must also appear in a to clause.
16941 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016942 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016943 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16944 << VD << 0 << SR;
16945 return;
16946 }
16947 }
16948 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016949 return;
16950 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16951 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016952}
16953
16954static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16955 Sema &SemaRef, DSAStackTy *Stack,
16956 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016957 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016958 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16959 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016960}
16961
Kelvin Li1ce87c72017-12-12 20:08:12 +000016962void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16963 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016964 if (!D || D->isInvalidDecl())
16965 return;
16966 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016967 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016968 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016969 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016970 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16971 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016972 return;
16973 // 2.10.6: threadprivate variable cannot appear in a declare target
16974 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016975 if (DSAStack->isThreadPrivate(VD)) {
16976 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016977 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016978 return;
16979 }
16980 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016981 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16982 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016983 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016984 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16985 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016986 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016987 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16988 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16989 return;
16990 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016991 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016992 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16993 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16994 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16995 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016996 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016997 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16998 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16999 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000017000 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017001 if (auto *VD = dyn_cast<ValueDecl>(D)) {
17002 // Problem if any with var declared with incomplete type will be reported
17003 // as normal, so no need to check it here.
17004 if ((E || !VD->getType()->isIncompleteType()) &&
17005 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
17006 return;
17007 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
17008 // Checking declaration inside declare target region.
17009 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
17010 isa<FunctionTemplateDecl>(D)) {
17011 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000017012 Context, OMPDeclareTargetDeclAttr::MT_To,
17013 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000017014 D->addAttr(A);
17015 if (ASTMutationListener *ML = Context.getASTMutationListener())
17016 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
17017 }
17018 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017019 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017020 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017021 if (!E)
17022 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017023 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
17024}
Samuel Antao661c0902016-05-26 17:39:58 +000017025
17026OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000017027 CXXScopeSpec &MapperIdScopeSpec,
17028 DeclarationNameInfo &MapperId,
17029 const OMPVarListLocTy &Locs,
17030 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000017031 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017032 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
17033 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000017034 if (MVLI.ProcessedVarList.empty())
17035 return nullptr;
17036
Michael Kruse01f670d2019-02-22 22:29:42 +000017037 return OMPToClause::Create(
17038 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17039 MVLI.VarComponents, MVLI.UDMapperList,
17040 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000017041}
Samuel Antaoec172c62016-05-26 17:49:04 +000017042
17043OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000017044 CXXScopeSpec &MapperIdScopeSpec,
17045 DeclarationNameInfo &MapperId,
17046 const OMPVarListLocTy &Locs,
17047 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000017048 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017049 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
17050 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000017051 if (MVLI.ProcessedVarList.empty())
17052 return nullptr;
17053
Michael Kruse0336c752019-02-25 20:34:15 +000017054 return OMPFromClause::Create(
17055 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17056 MVLI.VarComponents, MVLI.UDMapperList,
17057 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000017058}
Carlo Bertolli2404b172016-07-13 15:37:16 +000017059
17060OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017061 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000017062 MappableVarListInfo MVLI(VarList);
17063 SmallVector<Expr *, 8> PrivateCopies;
17064 SmallVector<Expr *, 8> Inits;
17065
Alexey Bataeve3727102018-04-18 15:57:46 +000017066 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017067 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
17068 SourceLocation ELoc;
17069 SourceRange ERange;
17070 Expr *SimpleRefExpr = RefExpr;
17071 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17072 if (Res.second) {
17073 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000017074 MVLI.ProcessedVarList.push_back(RefExpr);
17075 PrivateCopies.push_back(nullptr);
17076 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017077 }
17078 ValueDecl *D = Res.first;
17079 if (!D)
17080 continue;
17081
17082 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000017083 Type = Type.getNonReferenceType().getUnqualifiedType();
17084
17085 auto *VD = dyn_cast<VarDecl>(D);
17086
17087 // Item should be a pointer or reference to pointer.
17088 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017089 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
17090 << 0 << RefExpr->getSourceRange();
17091 continue;
17092 }
Samuel Antaocc10b852016-07-28 14:23:26 +000017093
17094 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000017095 auto VDPrivate =
17096 buildVarDecl(*this, ELoc, Type, D->getName(),
17097 D->hasAttrs() ? &D->getAttrs() : nullptr,
17098 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000017099 if (VDPrivate->isInvalidDecl())
17100 continue;
17101
17102 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017103 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017104 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17105
17106 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017107 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017108 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017109 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17110 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017111 AddInitializerToDecl(VDPrivate,
17112 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017113 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017114
17115 // If required, build a capture to implement the privatization initialized
17116 // with the current list item value.
17117 DeclRefExpr *Ref = nullptr;
17118 if (!VD)
17119 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17120 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17121 PrivateCopies.push_back(VDPrivateRefExpr);
17122 Inits.push_back(VDInitRefExpr);
17123
17124 // We need to add a data sharing attribute for this variable to make sure it
17125 // is correctly captured. A variable that shows up in a use_device_ptr has
17126 // similar properties of a first private variable.
17127 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17128
17129 // Create a mappable component for the list item. List items in this clause
17130 // only need a component.
17131 MVLI.VarBaseDeclarations.push_back(D);
17132 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17133 MVLI.VarComponents.back().push_back(
17134 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017135 }
17136
Samuel Antaocc10b852016-07-28 14:23:26 +000017137 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017138 return nullptr;
17139
Samuel Antaocc10b852016-07-28 14:23:26 +000017140 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017141 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17142 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017143}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017144
17145OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017146 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017147 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017148 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017149 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017150 SourceLocation ELoc;
17151 SourceRange ERange;
17152 Expr *SimpleRefExpr = RefExpr;
17153 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17154 if (Res.second) {
17155 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017156 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017157 }
17158 ValueDecl *D = Res.first;
17159 if (!D)
17160 continue;
17161
17162 QualType Type = D->getType();
17163 // item should be a pointer or array or reference to pointer or array
17164 if (!Type.getNonReferenceType()->isPointerType() &&
17165 !Type.getNonReferenceType()->isArrayType()) {
17166 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17167 << 0 << RefExpr->getSourceRange();
17168 continue;
17169 }
Samuel Antao6890b092016-07-28 14:25:09 +000017170
17171 // Check if the declaration in the clause does not show up in any data
17172 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017173 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017174 if (isOpenMPPrivate(DVar.CKind)) {
17175 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17176 << getOpenMPClauseName(DVar.CKind)
17177 << getOpenMPClauseName(OMPC_is_device_ptr)
17178 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017179 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017180 continue;
17181 }
17182
Alexey Bataeve3727102018-04-18 15:57:46 +000017183 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017184 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017185 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017186 [&ConflictExpr](
17187 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17188 OpenMPClauseKind) -> bool {
17189 ConflictExpr = R.front().getAssociatedExpression();
17190 return true;
17191 })) {
17192 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17193 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17194 << ConflictExpr->getSourceRange();
17195 continue;
17196 }
17197
17198 // Store the components in the stack so that they can be used to check
17199 // against other clauses later on.
17200 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17201 DSAStack->addMappableExpressionComponents(
17202 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17203
17204 // Record the expression we've just processed.
17205 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17206
17207 // Create a mappable component for the list item. List items in this clause
17208 // only need a component. We use a null declaration to signal fields in
17209 // 'this'.
17210 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17211 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17212 "Unexpected device pointer expression!");
17213 MVLI.VarBaseDeclarations.push_back(
17214 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17215 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17216 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017217 }
17218
Samuel Antao6890b092016-07-28 14:25:09 +000017219 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017220 return nullptr;
17221
Michael Kruse4304e9d2019-02-19 16:38:20 +000017222 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17223 MVLI.VarBaseDeclarations,
17224 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017225}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017226
17227OMPClause *Sema::ActOnOpenMPAllocateClause(
17228 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17229 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17230 if (Allocator) {
17231 // OpenMP [2.11.4 allocate Clause, Description]
17232 // allocator is an expression of omp_allocator_handle_t type.
17233 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17234 return nullptr;
17235
17236 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17237 if (AllocatorRes.isInvalid())
17238 return nullptr;
17239 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17240 DSAStack->getOMPAllocatorHandleT(),
17241 Sema::AA_Initializing,
17242 /*AllowExplicit=*/true);
17243 if (AllocatorRes.isInvalid())
17244 return nullptr;
17245 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017246 } else {
17247 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17248 // allocate clauses that appear on a target construct or on constructs in a
17249 // target region must specify an allocator expression unless a requires
17250 // directive with the dynamic_allocators clause is present in the same
17251 // compilation unit.
17252 if (LangOpts.OpenMPIsDevice &&
17253 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17254 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017255 }
17256 // Analyze and build list of variables.
17257 SmallVector<Expr *, 8> Vars;
17258 for (Expr *RefExpr : VarList) {
17259 assert(RefExpr && "NULL expr in OpenMP private clause.");
17260 SourceLocation ELoc;
17261 SourceRange ERange;
17262 Expr *SimpleRefExpr = RefExpr;
17263 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17264 if (Res.second) {
17265 // It will be analyzed later.
17266 Vars.push_back(RefExpr);
17267 }
17268 ValueDecl *D = Res.first;
17269 if (!D)
17270 continue;
17271
17272 auto *VD = dyn_cast<VarDecl>(D);
17273 DeclRefExpr *Ref = nullptr;
17274 if (!VD && !CurContext->isDependentContext())
17275 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17276 Vars.push_back((VD || CurContext->isDependentContext())
17277 ? RefExpr->IgnoreParens()
17278 : Ref);
17279 }
17280
17281 if (Vars.empty())
17282 return nullptr;
17283
Alexey Bataevf3c508f2020-01-23 10:47:16 -050017284 if (Allocator)
17285 DSAStack->addInnerAllocatorExpr(Allocator);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017286 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17287 ColonLoc, EndLoc, Vars);
17288}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017289
17290OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17291 SourceLocation StartLoc,
17292 SourceLocation LParenLoc,
17293 SourceLocation EndLoc) {
17294 SmallVector<Expr *, 8> Vars;
17295 for (Expr *RefExpr : VarList) {
17296 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
17297 SourceLocation ELoc;
17298 SourceRange ERange;
17299 Expr *SimpleRefExpr = RefExpr;
17300 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17301 if (Res.second)
17302 // It will be analyzed later.
17303 Vars.push_back(RefExpr);
17304 ValueDecl *D = Res.first;
17305 if (!D)
17306 continue;
17307
Alexey Bataevb6e70842019-12-16 15:54:17 -050017308 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17309 // A list-item cannot appear in more than one nontemporal clause.
17310 if (const Expr *PrevRef =
17311 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17312 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17313 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17314 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17315 << getOpenMPClauseName(OMPC_nontemporal);
17316 continue;
17317 }
17318
Alexey Bataev0860db92019-12-19 10:01:10 -050017319 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017320 }
17321
17322 if (Vars.empty())
17323 return nullptr;
17324
17325 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17326 Vars);
17327}