blob: 9033997afff524b5a90bb6a8be15860a3c657405 [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"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060034#include "llvm/Frontend/OpenMP/OMPConstants.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000035using namespace clang;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060036using namespace llvm::omp;
Alexey Bataeva769e072013-03-22 06:34:35 +000037
Alexey Bataev758e55e2013-09-06 18:03:48 +000038//===----------------------------------------------------------------------===//
39// Stack of data-sharing attributes for variables
40//===----------------------------------------------------------------------===//
41
Alexey Bataeve3727102018-04-18 15:57:46 +000042static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000043 Sema &SemaRef, Expr *E,
44 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000045 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000046
Alexey Bataev758e55e2013-09-06 18:03:48 +000047namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000049enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 DSA_unspecified = 0, /// Data sharing attribute not specified.
51 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
52 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000053};
54
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000056/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000057class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000058public:
Alexey Bataeve3727102018-04-18 15:57:46 +000059 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000060 OpenMPDirectiveKind DKind = OMPD_unknown;
61 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000062 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000063 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000064 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000065 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000066 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
67 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
68 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000069 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
70 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000071 };
Alexey Bataeve3727102018-04-18 15:57:46 +000072 using OperatorOffsetTy =
73 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000074 using DoacrossDependMapTy =
75 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000076
Alexey Bataev758e55e2013-09-06 18:03:48 +000077private:
Alexey Bataeve3727102018-04-18 15:57:46 +000078 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000079 OpenMPClauseKind Attributes = OMPC_unknown;
80 /// Pointer to a reference expression and a flag which shows that the
81 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000082 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000083 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000084 };
Alexey Bataeve3727102018-04-18 15:57:46 +000085 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
86 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
87 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
88 using LoopControlVariablesMapTy =
89 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000090 /// Struct that associates a component with the clause kind where they are
91 /// found.
92 struct MappedExprComponentTy {
93 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
94 OpenMPClauseKind Kind = OMPC_unknown;
95 };
Alexey Bataeve3727102018-04-18 15:57:46 +000096 using MappedExprComponentsTy =
97 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
98 using CriticalsWithHintsTy =
99 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000101 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000114 using DeclReductionMapTy =
115 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500116 struct DefaultmapInfo {
117 OpenMPDefaultmapClauseModifier ImplicitBehavior =
118 OMPC_DEFAULTMAP_MODIFIER_unknown;
119 SourceLocation SLoc;
120 DefaultmapInfo() = default;
121 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
122 : ImplicitBehavior(M), SLoc(Loc) {}
123 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000124
Alexey Bataeve3727102018-04-18 15:57:46 +0000125 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000126 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000127 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000128 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000129 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000130 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500133 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000134 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000135 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000136 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000137 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000138 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
139 /// get the data (loop counters etc.) about enclosing loop-based construct.
140 /// This data is required during codegen.
141 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000142 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000143 /// 'ordered' clause, the second one is true if the regions has 'ordered'
144 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000145 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000146 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000147 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000148 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000149 bool NowaitRegion = false;
150 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000151 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000152 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000153 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000154 /// Reference to the taskgroup task_reduction reference expression.
155 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000156 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000157 /// List of globals marked as declare target link in this target region
158 /// (isOpenMPTargetExecutionDirective(Directive) == true).
159 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000160 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000161 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000162 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
163 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000164 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000165 };
166
Alexey Bataeve3727102018-04-18 15:57:46 +0000167 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000169 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000170 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000171 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
172 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000173 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000174 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000175 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000176 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000177 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000178 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000179 /// captured by reference.
180 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000181 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000182 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000183
Richard Smith375dec52019-05-30 23:21:14 +0000184 /// Iterators over the stack iterate in order from innermost to outermost
185 /// directive.
186 using const_iterator = StackTy::const_reverse_iterator;
187 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000188 return Stack.empty() ? const_iterator()
189 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000190 }
191 const_iterator end() const {
192 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
193 }
194 using iterator = StackTy::reverse_iterator;
195 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000196 return Stack.empty() ? iterator()
197 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000198 }
199 iterator end() {
200 return Stack.empty() ? iterator() : Stack.back().first.rend();
201 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000202
Richard Smith375dec52019-05-30 23:21:14 +0000203 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000204
Alexey Bataev4b465392017-04-26 15:06:24 +0000205 bool isStackEmpty() const {
206 return Stack.empty() ||
207 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000208 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000209 }
Richard Smith375dec52019-05-30 23:21:14 +0000210 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000211 return isStackEmpty() ? 0
212 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000213 }
214
215 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000216 size_t Size = getStackSize();
217 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000218 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000219 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000220 }
221 const SharingMapTy *getTopOfStackOrNull() const {
222 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
223 }
224 SharingMapTy &getTopOfStack() {
225 assert(!isStackEmpty() && "no current directive");
226 return *getTopOfStackOrNull();
227 }
228 const SharingMapTy &getTopOfStack() const {
229 return const_cast<DSAStackTy&>(*this).getTopOfStack();
230 }
231
232 SharingMapTy *getSecondOnStackOrNull() {
233 size_t Size = getStackSize();
234 if (Size <= 1)
235 return nullptr;
236 return &Stack.back().first[Size - 2];
237 }
238 const SharingMapTy *getSecondOnStackOrNull() const {
239 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
240 }
241
242 /// Get the stack element at a certain level (previously returned by
243 /// \c getNestingLevel).
244 ///
245 /// Note that nesting levels count from outermost to innermost, and this is
246 /// the reverse of our iteration order where new inner levels are pushed at
247 /// the front of the stack.
248 SharingMapTy &getStackElemAtLevel(unsigned Level) {
249 assert(Level < getStackSize() && "no such stack element");
250 return Stack.back().first[Level];
251 }
252 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
253 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
254 }
255
256 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
257
258 /// Checks if the variable is a local for OpenMP region.
259 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000260
Kelvin Li1408f912018-09-26 04:28:39 +0000261 /// Vector of previously declared requires directives
262 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000263 /// omp_allocator_handle_t type.
264 QualType OMPAllocatorHandleT;
265 /// Expression for the predefined allocators.
266 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
267 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000268 /// Vector of previously encountered target directives
269 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000270
Alexey Bataev758e55e2013-09-06 18:03:48 +0000271public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000272 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000273
Alexey Bataev27ef9512019-03-20 20:14:22 +0000274 /// Sets omp_allocator_handle_t type.
275 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
276 /// Gets omp_allocator_handle_t type.
277 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
278 /// Sets the given default allocator.
279 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
280 Expr *Allocator) {
281 OMPPredefinedAllocators[AllocatorKind] = Allocator;
282 }
283 /// Returns the specified default allocator.
284 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
285 return OMPPredefinedAllocators[AllocatorKind];
286 }
287
Alexey Bataevaac108a2015-06-23 04:51:00 +0000288 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000289 OpenMPClauseKind getClauseParsingMode() const {
290 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
291 return ClauseKindMode;
292 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000293 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000294
Richard Smith0621a8f2019-05-31 00:45:10 +0000295 bool isBodyComplete() const {
296 const SharingMapTy *Top = getTopOfStackOrNull();
297 return Top && Top->BodyComplete;
298 }
299 void setBodyComplete() {
300 getTopOfStack().BodyComplete = true;
301 }
302
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000303 bool isForceVarCapturing() const { return ForceCapturing; }
304 void setForceVarCapturing(bool V) { ForceCapturing = V; }
305
Alexey Bataev60705422018-10-30 15:50:12 +0000306 void setForceCaptureByReferenceInTargetExecutable(bool V) {
307 ForceCaptureByReferenceInTargetExecutable = V;
308 }
309 bool isForceCaptureByReferenceInTargetExecutable() const {
310 return ForceCaptureByReferenceInTargetExecutable;
311 }
312
Alexey Bataev758e55e2013-09-06 18:03:48 +0000313 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000314 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000315 assert(!IgnoredStackElements &&
316 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000317 if (Stack.empty() ||
318 Stack.back().second != CurrentNonCapturingFunctionScope)
319 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
320 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
321 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000322 }
323
324 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000325 assert(!IgnoredStackElements &&
326 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000327 assert(!Stack.back().first.empty() &&
328 "Data-sharing attributes stack is empty!");
329 Stack.back().first.pop_back();
330 }
331
Richard Smith0621a8f2019-05-31 00:45:10 +0000332 /// RAII object to temporarily leave the scope of a directive when we want to
333 /// logically operate in its parent.
334 class ParentDirectiveScope {
335 DSAStackTy &Self;
336 bool Active;
337 public:
338 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
339 : Self(Self), Active(false) {
340 if (Activate)
341 enable();
342 }
343 ~ParentDirectiveScope() { disable(); }
344 void disable() {
345 if (Active) {
346 --Self.IgnoredStackElements;
347 Active = false;
348 }
349 }
350 void enable() {
351 if (!Active) {
352 ++Self.IgnoredStackElements;
353 Active = true;
354 }
355 }
356 };
357
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000358 /// Marks that we're started loop parsing.
359 void loopInit() {
360 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
361 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000362 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000363 }
364 /// Start capturing of the variables in the loop context.
365 void loopStart() {
366 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
367 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000368 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000369 }
370 /// true, if variables are captured, false otherwise.
371 bool isLoopStarted() const {
372 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
373 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000374 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000375 }
376 /// Marks (or clears) declaration as possibly loop counter.
377 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000378 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000379 D ? D->getCanonicalDecl() : D;
380 }
381 /// Gets the possible loop counter decl.
382 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000383 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000384 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000385 /// Start new OpenMP region stack in new non-capturing function.
386 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000387 assert(!IgnoredStackElements &&
388 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000389 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
390 assert(!isa<CapturingScopeInfo>(CurFnScope));
391 CurrentNonCapturingFunctionScope = CurFnScope;
392 }
393 /// Pop region stack for non-capturing function.
394 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000395 assert(!IgnoredStackElements &&
396 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000397 if (!Stack.empty() && Stack.back().second == OldFSI) {
398 assert(Stack.back().first.empty());
399 Stack.pop_back();
400 }
401 CurrentNonCapturingFunctionScope = nullptr;
402 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
403 if (!isa<CapturingScopeInfo>(FSI)) {
404 CurrentNonCapturingFunctionScope = FSI;
405 break;
406 }
407 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000408 }
409
Alexey Bataeve3727102018-04-18 15:57:46 +0000410 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000411 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000412 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000413 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000414 getCriticalWithHint(const DeclarationNameInfo &Name) const {
415 auto I = Criticals.find(Name.getAsString());
416 if (I != Criticals.end())
417 return I->second;
418 return std::make_pair(nullptr, llvm::APSInt());
419 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000420 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000421 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000422 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000423 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000426 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000427 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000428 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000431 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000433 /// parent region.
434 /// \return The index of the loop control variable in the list of associated
435 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000436 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000438 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000439 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000440
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000442 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000443 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444
Alexey Bataevfa312f32017-07-21 18:48:21 +0000445 /// Adds additional information for the reduction items with the reduction id
446 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000447 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000448 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000449 /// Adds additional information for the reduction items with the reduction id
450 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000451 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000452 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000453 /// Returns the location and reduction operation from the innermost parent
454 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000455 const DSAVarData
456 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
457 BinaryOperatorKind &BOK,
458 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000459 /// Returns the location and reduction operation from the innermost parent
460 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000461 const DSAVarData
462 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
463 const Expr *&ReductionRef,
464 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000465 /// Return reduction reference expression for the current taskgroup.
466 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000467 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000468 "taskgroup reference expression requested for non taskgroup "
469 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000470 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000471 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000472 /// Checks if the given \p VD declaration is actually a taskgroup reduction
473 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000474 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000475 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
476 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000477 ->getDecl() == VD;
478 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000479
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000480 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000481 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000482 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000483 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000484 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000485 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000486 /// match specified \a CPred predicate in any directive which matches \a DPred
487 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000488 const DSAVarData
489 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
490 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
491 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 innermost directive which
494 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000495 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000496 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000497 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
498 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000499 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000501 /// attributes which match specified \a CPred predicate at the specified
502 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000503 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000504 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000505 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000506
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000507 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000508 /// specified \a DPred predicate.
509 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000510 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000511 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000514 bool hasDirective(
515 const llvm::function_ref<bool(
516 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
517 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000518 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000519
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000521 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000522 const SharingMapTy *Top = getTopOfStackOrNull();
523 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000524 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000526 OpenMPDirectiveKind getDirective(unsigned Level) const {
527 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000528 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000529 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000530 /// Returns the capture region at the specified level.
531 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
532 unsigned OpenMPCaptureLevel) const {
533 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
534 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
535 return CaptureRegions[OpenMPCaptureLevel];
536 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000538 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000539 const SharingMapTy *Parent = getSecondOnStackOrNull();
540 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000541 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000542
Kelvin Li1408f912018-09-26 04:28:39 +0000543 /// Add requires decl to internal vector
544 void addRequiresDecl(OMPRequiresDecl *RD) {
545 RequiresDecls.push_back(RD);
546 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000547
Alexey Bataev318f431b2019-03-22 15:25:12 +0000548 /// Checks if the defined 'requires' directive has specified type of clause.
549 template <typename ClauseType>
550 bool hasRequiresDeclWithClause() {
551 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
552 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
553 return isa<ClauseType>(C);
554 });
555 });
556 }
557
Kelvin Li1408f912018-09-26 04:28:39 +0000558 /// Checks for a duplicate clause amongst previously declared requires
559 /// directives
560 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
561 bool IsDuplicate = false;
562 for (OMPClause *CNew : ClauseList) {
563 for (const OMPRequiresDecl *D : RequiresDecls) {
564 for (const OMPClause *CPrev : D->clauselists()) {
565 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
566 SemaRef.Diag(CNew->getBeginLoc(),
567 diag::err_omp_requires_clause_redeclaration)
568 << getOpenMPClauseName(CNew->getClauseKind());
569 SemaRef.Diag(CPrev->getBeginLoc(),
570 diag::note_omp_requires_previous_clause)
571 << getOpenMPClauseName(CPrev->getClauseKind());
572 IsDuplicate = true;
573 }
574 }
575 }
576 }
577 return IsDuplicate;
578 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000579
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000580 /// Add location of previously encountered target to internal vector
581 void addTargetDirLocation(SourceLocation LocStart) {
582 TargetLocations.push_back(LocStart);
583 }
584
585 // Return previously encountered target region locations.
586 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
587 return TargetLocations;
588 }
589
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000590 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000591 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000592 getTopOfStack().DefaultAttr = DSA_none;
593 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000594 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000595 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000596 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000597 getTopOfStack().DefaultAttr = DSA_shared;
598 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000599 }
cchene06f3e02019-11-15 13:02:06 -0500600 /// Set default data mapping attribute to Modifier:Kind
601 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
602 OpenMPDefaultmapClauseKind Kind,
603 SourceLocation Loc) {
604 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
605 DMI.ImplicitBehavior = M;
606 DMI.SLoc = Loc;
607 }
608 /// Check whether the implicit-behavior has been set in defaultmap
609 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
610 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
611 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000612 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613
614 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000615 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000616 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000617 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000618 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000619 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000620 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000621 }
cchene06f3e02019-11-15 13:02:06 -0500622 OpenMPDefaultmapClauseModifier
623 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
624 return isStackEmpty()
625 ? OMPC_DEFAULTMAP_MODIFIER_unknown
626 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000627 }
cchene06f3e02019-11-15 13:02:06 -0500628 OpenMPDefaultmapClauseModifier
629 getDefaultmapModifierAtLevel(unsigned Level,
630 OpenMPDefaultmapClauseKind Kind) const {
631 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000632 }
cchene06f3e02019-11-15 13:02:06 -0500633 bool isDefaultmapCapturedByRef(unsigned Level,
634 OpenMPDefaultmapClauseKind Kind) const {
635 OpenMPDefaultmapClauseModifier M =
636 getDefaultmapModifierAtLevel(Level, Kind);
637 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
638 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
639 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
640 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
641 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
642 }
643 return true;
644 }
645 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
646 OpenMPDefaultmapClauseKind Kind) {
647 switch (Kind) {
648 case OMPC_DEFAULTMAP_scalar:
649 case OMPC_DEFAULTMAP_pointer:
650 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
651 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
652 (M == OMPC_DEFAULTMAP_MODIFIER_default);
653 case OMPC_DEFAULTMAP_aggregate:
654 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000655 default:
656 break;
cchene06f3e02019-11-15 13:02:06 -0500657 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000658 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500659 }
660 bool mustBeFirstprivateAtLevel(unsigned Level,
661 OpenMPDefaultmapClauseKind Kind) const {
662 OpenMPDefaultmapClauseModifier M =
663 getDefaultmapModifierAtLevel(Level, Kind);
664 return mustBeFirstprivateBase(M, Kind);
665 }
666 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
667 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
668 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000669 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000671 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000672 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000673 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000674 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000675 }
676
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000677 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000678 void setOrderedRegion(bool IsOrdered, const Expr *Param,
679 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000680 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000681 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000682 else
Richard Smith375dec52019-05-30 23:21:14 +0000683 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000684 }
685 /// Returns true, if region is ordered (has associated 'ordered' clause),
686 /// false - otherwise.
687 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000688 if (const SharingMapTy *Top = getTopOfStackOrNull())
689 return Top->OrderedRegion.hasValue();
690 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000691 }
692 /// Returns optional parameter for the ordered region.
693 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000694 if (const SharingMapTy *Top = getTopOfStackOrNull())
695 if (Top->OrderedRegion.hasValue())
696 return Top->OrderedRegion.getValue();
697 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000698 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000699 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000700 /// 'ordered' clause), false - otherwise.
701 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000702 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
703 return Parent->OrderedRegion.hasValue();
704 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000705 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000706 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000707 std::pair<const Expr *, OMPOrderedClause *>
708 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000709 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
710 if (Parent->OrderedRegion.hasValue())
711 return Parent->OrderedRegion.getValue();
712 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000713 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000714 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000715 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000716 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000717 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000718 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000719 /// 'nowait' clause), false - otherwise.
720 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000721 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
722 return Parent->NowaitRegion;
723 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000724 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000725 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000726 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000727 if (SharingMapTy *Parent = getSecondOnStackOrNull())
728 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000729 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000730 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000731 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000732 const SharingMapTy *Top = getTopOfStackOrNull();
733 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000734 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000736 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000737 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000738 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000739 if (Val > 1)
740 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000741 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000742 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000743 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000744 const SharingMapTy *Top = getTopOfStackOrNull();
745 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000746 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000747 /// Returns true if the construct is associated with multiple loops.
748 bool hasMutipleLoops() const {
749 const SharingMapTy *Top = getTopOfStackOrNull();
750 return Top ? Top->HasMutipleLoops : false;
751 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000754 /// region.
755 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000756 if (SharingMapTy *Parent = getSecondOnStackOrNull())
757 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000758 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000760 bool hasInnerTeamsRegion() const {
761 return getInnerTeamsRegionLoc().isValid();
762 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000763 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000764 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000765 const SharingMapTy *Top = getTopOfStackOrNull();
766 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000767 }
768
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000769 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000770 const SharingMapTy *Top = getTopOfStackOrNull();
771 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000772 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000773 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000774 const SharingMapTy *Top = getTopOfStackOrNull();
775 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000776 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000777
Samuel Antao4c8035b2016-12-12 18:00:20 +0000778 /// Do the check specified in \a Check to all component lists and return true
779 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000780 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000782 const llvm::function_ref<
783 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000784 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000785 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000786 if (isStackEmpty())
787 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000788 auto SI = begin();
789 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000790
791 if (SI == SE)
792 return false;
793
Alexey Bataeve3727102018-04-18 15:57:46 +0000794 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000795 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000796 else
797 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000798
799 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000800 auto MI = SI->MappedExprComponents.find(VD);
801 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000802 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
803 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000804 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000805 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000806 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000807 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000808 }
809
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000810 /// Do the check specified in \a Check to all component lists at a given level
811 /// and return true if any issue is found.
812 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000813 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000814 const llvm::function_ref<
815 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000816 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000817 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000818 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000819 return false;
820
Richard Smith375dec52019-05-30 23:21:14 +0000821 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
822 auto MI = StackElem.MappedExprComponents.find(VD);
823 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000824 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
825 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000826 if (Check(L, MI->second.Kind))
827 return true;
828 return false;
829 }
830
Samuel Antao4c8035b2016-12-12 18:00:20 +0000831 /// Create a new mappable expression component list associated with a given
832 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000833 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000834 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000835 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
836 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000837 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000838 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000839 MEC.Components.resize(MEC.Components.size() + 1);
840 MEC.Components.back().append(Components.begin(), Components.end());
841 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000842 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000843
844 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000845 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000846 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000847 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000848 void addDoacrossDependClause(OMPDependClause *C,
849 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000850 SharingMapTy *Parent = getSecondOnStackOrNull();
851 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
852 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000853 }
854 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
855 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000856 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000857 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000858 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000859 return llvm::make_range(Ref.begin(), Ref.end());
860 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000861 return llvm::make_range(StackElem.DoacrossDepends.end(),
862 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000863 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000864
865 // Store types of classes which have been explicitly mapped
866 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000867 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000868 StackElem.MappedClassesQualTypes.insert(QT);
869 }
870
871 // Return set of mapped classes types
872 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000873 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000874 return StackElem.MappedClassesQualTypes.count(QT) != 0;
875 }
876
Alexey Bataeva495c642019-03-11 19:51:42 +0000877 /// Adds global declare target to the parent target region.
878 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
879 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
880 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
881 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000882 for (auto &Elem : *this) {
883 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
884 Elem.DeclareTargetLinkVarDecls.push_back(E);
885 return;
886 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000887 }
888 }
889
890 /// Returns the list of globals with declare target link if current directive
891 /// is target.
892 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
893 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
894 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000895 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000896 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000897};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000898
899bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
900 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
901}
902
903bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000904 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
905 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000906}
Alexey Bataeve3727102018-04-18 15:57:46 +0000907
Alexey Bataeved09d242014-05-28 05:53:51 +0000908} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000909
Alexey Bataeve3727102018-04-18 15:57:46 +0000910static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000911 if (const auto *FE = dyn_cast<FullExpr>(E))
912 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000913
Alexey Bataeve3727102018-04-18 15:57:46 +0000914 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100915 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000916
Alexey Bataeve3727102018-04-18 15:57:46 +0000917 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000918 E = Binder->getSubExpr();
919
Alexey Bataeve3727102018-04-18 15:57:46 +0000920 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000921 E = ICE->getSubExprAsWritten();
922 return E->IgnoreParens();
923}
924
Alexey Bataeve3727102018-04-18 15:57:46 +0000925static Expr *getExprAsWritten(Expr *E) {
926 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
927}
928
929static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
930 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
931 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000932 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000933 const auto *VD = dyn_cast<VarDecl>(D);
934 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000935 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000936 VD = VD->getCanonicalDecl();
937 D = VD;
938 } else {
939 assert(FD);
940 FD = FD->getCanonicalDecl();
941 D = FD;
942 }
943 return D;
944}
945
Alexey Bataeve3727102018-04-18 15:57:46 +0000946static ValueDecl *getCanonicalDecl(ValueDecl *D) {
947 return const_cast<ValueDecl *>(
948 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
949}
950
Richard Smith375dec52019-05-30 23:21:14 +0000951DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000952 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000953 D = getCanonicalDecl(D);
954 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000955 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000956 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000957 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000958 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
959 // in a region but not in construct]
960 // File-scope or namespace-scope variables referenced in called routines
961 // in the region are shared unless they appear in a threadprivate
962 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000963 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000964 DVar.CKind = OMPC_shared;
965
966 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
967 // in a region but not in construct]
968 // Variables with static storage duration that are declared in called
969 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000970 if (VD && VD->hasGlobalStorage())
971 DVar.CKind = OMPC_shared;
972
973 // Non-static data members are shared by default.
974 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000975 DVar.CKind = OMPC_shared;
976
Alexey Bataev758e55e2013-09-06 18:03:48 +0000977 return DVar;
978 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000979
Alexey Bataevec3da872014-01-31 05:15:34 +0000980 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
981 // in a Construct, C/C++, predetermined, p.1]
982 // Variables with automatic storage duration that are declared in a scope
983 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000984 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
985 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000986 DVar.CKind = OMPC_private;
987 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000988 }
989
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000990 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000991 // Explicitly specified attributes and local variables with predetermined
992 // attributes.
993 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000994 const DSAInfo &Data = Iter->SharingMap.lookup(D);
995 DVar.RefExpr = Data.RefExpr.getPointer();
996 DVar.PrivateCopy = Data.PrivateCopy;
997 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000998 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000999 return DVar;
1000 }
1001
1002 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1003 // in a Construct, C/C++, implicitly determined, p.1]
1004 // In a parallel or task construct, the data-sharing attributes of these
1005 // variables are determined by the default clause, if present.
1006 switch (Iter->DefaultAttr) {
1007 case DSA_shared:
1008 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001009 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001010 return DVar;
1011 case DSA_none:
1012 return DVar;
1013 case DSA_unspecified:
1014 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1015 // in a Construct, implicitly determined, p.2]
1016 // In a parallel construct, if no default clause is present, these
1017 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001018 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001019 if ((isOpenMPParallelDirective(DVar.DKind) &&
1020 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001021 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001022 DVar.CKind = OMPC_shared;
1023 return DVar;
1024 }
1025
1026 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1027 // in a Construct, implicitly determined, p.4]
1028 // In a task construct, if no default clause is present, a variable that in
1029 // the enclosing context is determined to be shared by all implicit tasks
1030 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001031 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001032 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001033 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001034 do {
1035 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001036 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001037 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001038 // In a task construct, if no default clause is present, a variable
1039 // whose data-sharing attribute is not determined by the rules above is
1040 // firstprivate.
1041 DVarTemp = getDSA(I, D);
1042 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001043 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001044 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001045 return DVar;
1046 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001047 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001049 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001050 return DVar;
1051 }
1052 }
1053 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1054 // in a Construct, implicitly determined, p.3]
1055 // For constructs other than task, if no default clause is present, these
1056 // variables inherit their data-sharing attributes from the enclosing
1057 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001058 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001059}
1060
Alexey Bataeve3727102018-04-18 15:57:46 +00001061const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1062 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001063 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001064 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001065 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001066 auto It = StackElem.AlignedMap.find(D);
1067 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001068 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001069 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001070 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001071 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001072 assert(It->second && "Unexpected nullptr expr in the aligned map");
1073 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001074}
1075
Alexey Bataeve3727102018-04-18 15:57:46 +00001076void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001077 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001078 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001079 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001080 StackElem.LCVMap.try_emplace(
1081 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001082}
1083
Alexey Bataeve3727102018-04-18 15:57:46 +00001084const DSAStackTy::LCDeclInfo
1085DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001086 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001087 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001088 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001089 auto It = StackElem.LCVMap.find(D);
1090 if (It != StackElem.LCVMap.end())
1091 return It->second;
1092 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001093}
1094
Alexey Bataeve3727102018-04-18 15:57:46 +00001095const DSAStackTy::LCDeclInfo
1096DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001097 const SharingMapTy *Parent = getSecondOnStackOrNull();
1098 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001099 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001100 auto It = Parent->LCVMap.find(D);
1101 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 return It->second;
1103 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001104}
1105
Alexey Bataeve3727102018-04-18 15:57:46 +00001106const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001107 const SharingMapTy *Parent = getSecondOnStackOrNull();
1108 assert(Parent && "Data-sharing attributes stack is empty");
1109 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001110 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001111 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001112 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001113 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001114 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001115}
1116
Alexey Bataeve3727102018-04-18 15:57:46 +00001117void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001118 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001119 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001120 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001121 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001122 Data.Attributes = A;
1123 Data.RefExpr.setPointer(E);
1124 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001125 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001126 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001127 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1128 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1129 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1130 (isLoopControlVariable(D).first && A == OMPC_private));
1131 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1132 Data.RefExpr.setInt(/*IntVal=*/true);
1133 return;
1134 }
1135 const bool IsLastprivate =
1136 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1137 Data.Attributes = A;
1138 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1139 Data.PrivateCopy = PrivateCopy;
1140 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001141 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001142 Data.Attributes = A;
1143 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1144 Data.PrivateCopy = nullptr;
1145 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001146 }
1147}
1148
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001149/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001150static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001151 StringRef Name, const AttrVec *Attrs = nullptr,
1152 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001153 DeclContext *DC = SemaRef.CurContext;
1154 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1155 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001156 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001157 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1158 if (Attrs) {
1159 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1160 I != E; ++I)
1161 Decl->addAttr(*I);
1162 }
1163 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001164 if (OrigRef) {
1165 Decl->addAttr(
1166 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1167 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001168 return Decl;
1169}
1170
1171static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1172 SourceLocation Loc,
1173 bool RefersToCapture = false) {
1174 D->setReferenced();
1175 D->markUsed(S.Context);
1176 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1177 SourceLocation(), D, RefersToCapture, Loc, Ty,
1178 VK_LValue);
1179}
1180
Alexey Bataeve3727102018-04-18 15:57:46 +00001181void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001182 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001183 D = getCanonicalDecl(D);
1184 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001185 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001186 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001187 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001188 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001189 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001190 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001191 "Additional reduction info may be specified only once for reduction "
1192 "items.");
1193 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001194 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001195 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001196 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001197 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1198 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001199 TaskgroupReductionRef =
1200 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001201 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001202}
1203
Alexey Bataeve3727102018-04-18 15:57:46 +00001204void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001205 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001206 D = getCanonicalDecl(D);
1207 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001208 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001209 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001210 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001211 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001212 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001213 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001214 "Additional reduction info may be specified only once for reduction "
1215 "items.");
1216 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001217 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001218 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001219 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001220 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1221 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001222 TaskgroupReductionRef =
1223 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001224 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001225}
1226
Alexey Bataeve3727102018-04-18 15:57:46 +00001227const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1228 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1229 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001230 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001231 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001232 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001233 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001234 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001235 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001236 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001237 if (!ReductionData.ReductionOp ||
1238 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001239 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001240 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001241 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001242 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1243 "expression for the descriptor is not "
1244 "set.");
1245 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001246 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1247 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001248 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001249 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001250}
1251
Alexey Bataeve3727102018-04-18 15:57:46 +00001252const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1253 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1254 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001255 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001256 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001257 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001258 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001259 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001260 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001261 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001262 if (!ReductionData.ReductionOp ||
1263 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001264 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001265 SR = ReductionData.ReductionRange;
1266 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001267 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1268 "expression for the descriptor is not "
1269 "set.");
1270 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001271 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1272 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001273 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001274 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001275}
1276
Richard Smith375dec52019-05-30 23:21:14 +00001277bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001278 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001279 for (const_iterator E = end(); I != E; ++I) {
1280 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1281 isOpenMPTargetExecutionDirective(I->Directive)) {
1282 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1283 Scope *CurScope = getCurScope();
1284 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1285 CurScope = CurScope->getParent();
1286 return CurScope != TopScope;
1287 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001288 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001289 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001290}
1291
Joel E. Dennyd2649292019-01-04 22:11:56 +00001292static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1293 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001294 bool *IsClassType = nullptr) {
1295 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001296 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001297 bool IsConstant = Type.isConstant(Context);
1298 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001299 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1300 ? Type->getAsCXXRecordDecl()
1301 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001302 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1303 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1304 RD = CTD->getTemplatedDecl();
1305 if (IsClassType)
1306 *IsClassType = RD;
1307 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1308 RD->hasDefinition() && RD->hasMutableFields());
1309}
1310
Joel E. Dennyd2649292019-01-04 22:11:56 +00001311static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1312 QualType Type, OpenMPClauseKind CKind,
1313 SourceLocation ELoc,
1314 bool AcceptIfMutable = true,
1315 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001316 ASTContext &Context = SemaRef.getASTContext();
1317 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001318 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1319 unsigned Diag = ListItemNotVar
1320 ? diag::err_omp_const_list_item
1321 : IsClassType ? diag::err_omp_const_not_mutable_variable
1322 : diag::err_omp_const_variable;
1323 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1324 if (!ListItemNotVar && D) {
1325 const VarDecl *VD = dyn_cast<VarDecl>(D);
1326 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1327 VarDecl::DeclarationOnly;
1328 SemaRef.Diag(D->getLocation(),
1329 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1330 << D;
1331 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001332 return true;
1333 }
1334 return false;
1335}
1336
Alexey Bataeve3727102018-04-18 15:57:46 +00001337const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1338 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001339 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001340 DSAVarData DVar;
1341
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001342 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001343 auto TI = Threadprivates.find(D);
1344 if (TI != Threadprivates.end()) {
1345 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001346 DVar.CKind = OMPC_threadprivate;
1347 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001348 }
1349 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001350 DVar.RefExpr = buildDeclRefExpr(
1351 SemaRef, VD, D->getType().getNonReferenceType(),
1352 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1353 DVar.CKind = OMPC_threadprivate;
1354 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001355 return DVar;
1356 }
1357 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1358 // in a Construct, C/C++, predetermined, p.1]
1359 // Variables appearing in threadprivate directives are threadprivate.
1360 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1361 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1362 SemaRef.getLangOpts().OpenMPUseTLS &&
1363 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1364 (VD && VD->getStorageClass() == SC_Register &&
1365 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1366 DVar.RefExpr = buildDeclRefExpr(
1367 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1368 DVar.CKind = OMPC_threadprivate;
1369 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1370 return DVar;
1371 }
1372 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1373 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1374 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001375 const_iterator IterTarget =
1376 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1377 return isOpenMPTargetExecutionDirective(Data.Directive);
1378 });
1379 if (IterTarget != end()) {
1380 const_iterator ParentIterTarget = IterTarget + 1;
1381 for (const_iterator Iter = begin();
1382 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001383 if (isOpenMPLocal(VD, Iter)) {
1384 DVar.RefExpr =
1385 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1386 D->getLocation());
1387 DVar.CKind = OMPC_threadprivate;
1388 return DVar;
1389 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001390 }
Richard Smith375dec52019-05-30 23:21:14 +00001391 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001392 auto DSAIter = IterTarget->SharingMap.find(D);
1393 if (DSAIter != IterTarget->SharingMap.end() &&
1394 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1395 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1396 DVar.CKind = OMPC_threadprivate;
1397 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001398 }
Richard Smith375dec52019-05-30 23:21:14 +00001399 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001400 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001401 D, std::distance(ParentIterTarget, End),
1402 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001403 DVar.RefExpr =
1404 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1405 IterTarget->ConstructLoc);
1406 DVar.CKind = OMPC_threadprivate;
1407 return DVar;
1408 }
1409 }
1410 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001411 }
1412
Alexey Bataev4b465392017-04-26 15:06:24 +00001413 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001414 // Not in OpenMP execution region and top scope was already checked.
1415 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001416
Alexey Bataev758e55e2013-09-06 18:03:48 +00001417 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001418 // in a Construct, C/C++, predetermined, p.4]
1419 // Static data members are shared.
1420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1421 // in a Construct, C/C++, predetermined, p.7]
1422 // Variables with static storage duration that are declared in a scope
1423 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001424 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001425 // Check for explicitly specified attributes.
1426 const_iterator I = begin();
1427 const_iterator EndI = end();
1428 if (FromParent && I != EndI)
1429 ++I;
1430 auto It = I->SharingMap.find(D);
1431 if (It != I->SharingMap.end()) {
1432 const DSAInfo &Data = It->getSecond();
1433 DVar.RefExpr = Data.RefExpr.getPointer();
1434 DVar.PrivateCopy = Data.PrivateCopy;
1435 DVar.CKind = Data.Attributes;
1436 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1437 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001438 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001439 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001440
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001441 DVar.CKind = OMPC_shared;
1442 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001443 }
1444
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001445 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001446 // The predetermined shared attribute for const-qualified types having no
1447 // mutable members was removed after OpenMP 3.1.
1448 if (SemaRef.LangOpts.OpenMP <= 31) {
1449 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1450 // in a Construct, C/C++, predetermined, p.6]
1451 // Variables with const qualified type having no mutable member are
1452 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001453 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001454 // Variables with const-qualified type having no mutable member may be
1455 // listed in a firstprivate clause, even if they are static data members.
1456 DSAVarData DVarTemp = hasInnermostDSA(
1457 D,
1458 [](OpenMPClauseKind C) {
1459 return C == OMPC_firstprivate || C == OMPC_shared;
1460 },
1461 MatchesAlways, FromParent);
1462 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1463 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001465 DVar.CKind = OMPC_shared;
1466 return DVar;
1467 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001468 }
1469
Alexey Bataev758e55e2013-09-06 18:03:48 +00001470 // Explicitly specified attributes and local variables with predetermined
1471 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001472 const_iterator I = begin();
1473 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001474 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001475 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001476 auto It = I->SharingMap.find(D);
1477 if (It != I->SharingMap.end()) {
1478 const DSAInfo &Data = It->getSecond();
1479 DVar.RefExpr = Data.RefExpr.getPointer();
1480 DVar.PrivateCopy = Data.PrivateCopy;
1481 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001483 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 }
1485
1486 return DVar;
1487}
1488
Alexey Bataeve3727102018-04-18 15:57:46 +00001489const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1490 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001491 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001492 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001493 return getDSA(I, D);
1494 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001495 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001496 const_iterator StartI = begin();
1497 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001498 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001499 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001500 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001501}
1502
Alexey Bataeve3727102018-04-18 15:57:46 +00001503const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001504DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001505 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1506 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001507 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001508 if (isStackEmpty())
1509 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001510 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001511 const_iterator I = begin();
1512 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001513 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001514 ++I;
1515 for (; I != EndI; ++I) {
1516 if (!DPred(I->Directive) &&
1517 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001518 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001519 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001520 DSAVarData DVar = getDSA(NewI, D);
1521 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001522 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001523 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001524 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001525}
1526
Alexey Bataeve3727102018-04-18 15:57:46 +00001527const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001528 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1529 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001530 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001531 if (isStackEmpty())
1532 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001533 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001534 const_iterator StartI = begin();
1535 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001536 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001537 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001538 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001539 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001540 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001541 DSAVarData DVar = getDSA(NewI, D);
1542 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001543}
1544
Alexey Bataevaac108a2015-06-23 04:51:00 +00001545bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001546 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1547 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001548 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001549 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001550 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001551 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1552 auto I = StackElem.SharingMap.find(D);
1553 if (I != StackElem.SharingMap.end() &&
1554 I->getSecond().RefExpr.getPointer() &&
1555 CPred(I->getSecond().Attributes) &&
1556 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001557 return true;
1558 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001559 auto LI = StackElem.LCVMap.find(D);
1560 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001561 return CPred(OMPC_private);
1562 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001563}
1564
Samuel Antao4be30e92015-10-02 17:14:03 +00001565bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001566 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1567 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001568 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001569 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001570 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1571 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001572}
1573
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001574bool DSAStackTy::hasDirective(
1575 const llvm::function_ref<bool(OpenMPDirectiveKind,
1576 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001577 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001578 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001579 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001580 size_t Skip = FromParent ? 2 : 1;
1581 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1582 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001583 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1584 return true;
1585 }
1586 return false;
1587}
1588
Alexey Bataev758e55e2013-09-06 18:03:48 +00001589void Sema::InitDataSharingAttributesStack() {
1590 VarDataSharingAttributesStack = new DSAStackTy(*this);
1591}
1592
1593#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1594
Alexey Bataev4b465392017-04-26 15:06:24 +00001595void Sema::pushOpenMPFunctionRegion() {
1596 DSAStack->pushFunction();
1597}
1598
1599void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1600 DSAStack->popFunction(OldFSI);
1601}
1602
Alexey Bataevc416e642019-02-08 18:02:25 +00001603static bool isOpenMPDeviceDelayedContext(Sema &S) {
1604 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1605 "Expected OpenMP device compilation.");
1606 return !S.isInOpenMPTargetExecutionDirective() &&
1607 !S.isInOpenMPDeclareTargetContext();
1608}
1609
Alexey Bataev729e2422019-08-23 16:11:14 +00001610namespace {
1611/// Status of the function emission on the host/device.
1612enum class FunctionEmissionStatus {
1613 Emitted,
1614 Discarded,
1615 Unknown,
1616};
1617} // anonymous namespace
1618
Alexey Bataevc416e642019-02-08 18:02:25 +00001619Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1620 unsigned DiagID) {
1621 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1622 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001623 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001624 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1625 switch (FES) {
1626 case FunctionEmissionStatus::Emitted:
1627 Kind = DeviceDiagBuilder::K_Immediate;
1628 break;
1629 case FunctionEmissionStatus::Unknown:
1630 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1631 : DeviceDiagBuilder::K_Immediate;
1632 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001633 case FunctionEmissionStatus::TemplateDiscarded:
1634 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001635 Kind = DeviceDiagBuilder::K_Nop;
1636 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001637 case FunctionEmissionStatus::CUDADiscarded:
1638 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1639 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001640 }
1641
1642 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1643}
1644
Alexey Bataev729e2422019-08-23 16:11:14 +00001645Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1646 unsigned DiagID) {
1647 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1648 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001649 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001650 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1651 switch (FES) {
1652 case FunctionEmissionStatus::Emitted:
1653 Kind = DeviceDiagBuilder::K_Immediate;
1654 break;
1655 case FunctionEmissionStatus::Unknown:
1656 Kind = DeviceDiagBuilder::K_Deferred;
1657 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001658 case FunctionEmissionStatus::TemplateDiscarded:
1659 case FunctionEmissionStatus::OMPDiscarded:
1660 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001661 Kind = DeviceDiagBuilder::K_Nop;
1662 break;
1663 }
1664
1665 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001666}
1667
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001668void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1669 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001670 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1671 "Expected OpenMP device compilation.");
1672 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001673 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001674 FunctionDecl *Caller = getCurFunctionDecl();
1675
Alexey Bataev729e2422019-08-23 16:11:14 +00001676 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001677 if (Caller) {
1678 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1679 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1680 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1681 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1682 "CUDADiscarded unexpected in OpenMP device function check");
1683 if ((CallerS == FunctionEmissionStatus::Emitted ||
1684 (!isOpenMPDeviceDelayedContext(*this) &&
1685 CallerS == FunctionEmissionStatus::Unknown)) &&
1686 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1687 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1688 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1689 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1690 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1691 diag::note_omp_marked_device_type_here)
1692 << HostDevTy;
1693 return;
1694 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001695 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001696 // If the caller is known-emitted, mark the callee as known-emitted.
1697 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001698 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1699 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001700 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001701 markKnownEmitted(*this, Caller, Callee, Loc,
1702 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001703 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001704 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001705 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001706 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001707 else if (Caller)
1708 DeviceCallGraph[Caller].insert({Callee, Loc});
1709}
1710
Alexey Bataev729e2422019-08-23 16:11:14 +00001711void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1712 bool CheckCaller) {
1713 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1714 "Expected OpenMP host compilation.");
1715 assert(Callee && "Callee may not be null.");
1716 Callee = Callee->getMostRecentDecl();
1717 FunctionDecl *Caller = getCurFunctionDecl();
1718
1719 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001720 if (Caller) {
1721 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1722 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1723 assert(
1724 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1725 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1726 "CUDADiscarded unexpected in OpenMP host function check");
1727 if (CallerS == FunctionEmissionStatus::Emitted &&
1728 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1729 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1730 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1731 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1732 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1733 diag::note_omp_marked_device_type_here)
1734 << NoHostDevTy;
1735 return;
1736 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001737 }
1738 // If the caller is known-emitted, mark the callee as known-emitted.
1739 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001740 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1741 if ((!CheckCaller && !Caller) ||
1742 (Caller &&
1743 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1744 markKnownEmitted(
1745 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1746 return CheckCaller &&
1747 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1748 });
1749 else if (Caller)
1750 DeviceCallGraph[Caller].insert({Callee, Loc});
1751 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001752}
1753
Alexey Bataev123ad192019-02-27 20:29:45 +00001754void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1755 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1756 "OpenMP device compilation mode is expected.");
1757 QualType Ty = E->getType();
1758 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001759 ((Ty->isFloat128Type() ||
1760 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1761 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001762 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1763 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001764 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1765 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1766 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001767}
1768
cchene06f3e02019-11-15 13:02:06 -05001769static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001770getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1771 if (LO.OpenMP <= 45) {
1772 if (VD->getType().getNonReferenceType()->isScalarType())
1773 return OMPC_DEFAULTMAP_scalar;
1774 return OMPC_DEFAULTMAP_aggregate;
1775 }
cchene06f3e02019-11-15 13:02:06 -05001776 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1777 return OMPC_DEFAULTMAP_pointer;
1778 if (VD->getType().getNonReferenceType()->isScalarType())
1779 return OMPC_DEFAULTMAP_scalar;
1780 return OMPC_DEFAULTMAP_aggregate;
1781}
1782
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001783bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1784 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001785 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1786
Alexey Bataeve3727102018-04-18 15:57:46 +00001787 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001788 bool IsByRef = true;
1789
1790 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001791 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001792 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001793
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001794 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001795 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001796 // This table summarizes how a given variable should be passed to the device
1797 // given its type and the clauses where it appears. This table is based on
1798 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1799 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1800 //
1801 // =========================================================================
1802 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1803 // | |(tofrom:scalar)| | pvt | | | |
1804 // =========================================================================
1805 // | scl | | | | - | | bycopy|
1806 // | scl | | - | x | - | - | bycopy|
1807 // | scl | | x | - | - | - | null |
1808 // | scl | x | | | - | | byref |
1809 // | scl | x | - | x | - | - | bycopy|
1810 // | scl | x | x | - | - | - | null |
1811 // | scl | | - | - | - | x | byref |
1812 // | scl | x | - | - | - | x | byref |
1813 //
1814 // | agg | n.a. | | | - | | byref |
1815 // | agg | n.a. | - | x | - | - | byref |
1816 // | agg | n.a. | x | - | - | - | null |
1817 // | agg | n.a. | - | - | - | x | byref |
1818 // | agg | n.a. | - | - | - | x[] | byref |
1819 //
1820 // | ptr | n.a. | | | - | | bycopy|
1821 // | ptr | n.a. | - | x | - | - | bycopy|
1822 // | ptr | n.a. | x | - | - | - | null |
1823 // | ptr | n.a. | - | - | - | x | byref |
1824 // | ptr | n.a. | - | - | - | x[] | bycopy|
1825 // | ptr | n.a. | - | - | x | | bycopy|
1826 // | ptr | n.a. | - | - | x | x | bycopy|
1827 // | ptr | n.a. | - | - | x | x[] | bycopy|
1828 // =========================================================================
1829 // Legend:
1830 // scl - scalar
1831 // ptr - pointer
1832 // agg - aggregate
1833 // x - applies
1834 // - - invalid in this combination
1835 // [] - mapped with an array section
1836 // byref - should be mapped by reference
1837 // byval - should be mapped by value
1838 // null - initialize a local variable to null on the device
1839 //
1840 // Observations:
1841 // - All scalar declarations that show up in a map clause have to be passed
1842 // by reference, because they may have been mapped in the enclosing data
1843 // environment.
1844 // - If the scalar value does not fit the size of uintptr, it has to be
1845 // passed by reference, regardless the result in the table above.
1846 // - For pointers mapped by value that have either an implicit map or an
1847 // array section, the runtime library may pass the NULL value to the
1848 // device instead of the value passed to it by the compiler.
1849
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001850 if (Ty->isReferenceType())
1851 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001852
1853 // Locate map clauses and see if the variable being captured is referred to
1854 // in any of those clauses. Here we only care about variables, not fields,
1855 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001856 bool IsVariableAssociatedWithSection = false;
1857
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001858 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001859 D, Level,
1860 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1861 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001862 MapExprComponents,
1863 OpenMPClauseKind WhereFoundClauseKind) {
1864 // Only the map clause information influences how a variable is
1865 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001866 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001867 if (WhereFoundClauseKind != OMPC_map)
1868 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001869
1870 auto EI = MapExprComponents.rbegin();
1871 auto EE = MapExprComponents.rend();
1872
1873 assert(EI != EE && "Invalid map expression!");
1874
1875 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1876 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1877
1878 ++EI;
1879 if (EI == EE)
1880 return false;
1881
1882 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1883 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1884 isa<MemberExpr>(EI->getAssociatedExpression())) {
1885 IsVariableAssociatedWithSection = true;
1886 // There is nothing more we need to know about this variable.
1887 return true;
1888 }
1889
1890 // Keep looking for more map info.
1891 return false;
1892 });
1893
1894 if (IsVariableUsedInMapClause) {
1895 // If variable is identified in a map clause it is always captured by
1896 // reference except if it is a pointer that is dereferenced somehow.
1897 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1898 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001899 // By default, all the data that has a scalar type is mapped by copy
1900 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001901 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001902 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001903 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1904 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001905 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001906 DSAStack->isDefaultmapCapturedByRef(
1907 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001908 DSAStack->hasExplicitDSA(
1909 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001910 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001911 }
1912
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001913 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001914 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001915 ((IsVariableUsedInMapClause &&
1916 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1917 OMPD_target) ||
1918 !DSAStack->hasExplicitDSA(
1919 D,
1920 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1921 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001922 // If the variable is artificial and must be captured by value - try to
1923 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001924 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1925 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001926 }
1927
Samuel Antao86ace552016-04-27 22:40:57 +00001928 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001929 // and alignment, because the runtime library only deals with uintptr types.
1930 // If it does not fit the uintptr size, we need to pass the data by reference
1931 // instead.
1932 if (!IsByRef &&
1933 (Ctx.getTypeSizeInChars(Ty) >
1934 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001935 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001936 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001937 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001938
1939 return IsByRef;
1940}
1941
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001942unsigned Sema::getOpenMPNestingLevel() const {
1943 assert(getLangOpts().OpenMP);
1944 return DSAStack->getNestingLevel();
1945}
1946
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001947bool Sema::isInOpenMPTargetExecutionDirective() const {
1948 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1949 !DSAStack->isClauseParsingMode()) ||
1950 DSAStack->hasDirective(
1951 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1952 SourceLocation) -> bool {
1953 return isOpenMPTargetExecutionDirective(K);
1954 },
1955 false);
1956}
1957
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001958VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1959 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001960 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001961 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001962
Alexey Bataev7c860692019-10-25 16:35:32 -04001963 auto *VD = dyn_cast<VarDecl>(D);
1964 // Do not capture constexpr variables.
1965 if (VD && VD->isConstexpr())
1966 return nullptr;
1967
Richard Smith0621a8f2019-05-31 00:45:10 +00001968 // If we want to determine whether the variable should be captured from the
1969 // perspective of the current capturing scope, and we've already left all the
1970 // capturing scopes of the top directive on the stack, check from the
1971 // perspective of its parent directive (if any) instead.
1972 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1973 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1974
Samuel Antao4be30e92015-10-02 17:14:03 +00001975 // If we are attempting to capture a global variable in a directive with
1976 // 'target' we return true so that this global is also mapped to the device.
1977 //
Richard Smith0621a8f2019-05-31 00:45:10 +00001978 if (VD && !VD->hasLocalStorage() &&
1979 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1980 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001981 // Try to mark variable as declare target if it is used in capturing
1982 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001983 if (LangOpts.OpenMP <= 45 &&
1984 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001985 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001986 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001987 } else if (isInOpenMPTargetExecutionDirective()) {
1988 // If the declaration is enclosed in a 'declare target' directive,
1989 // then it should not be captured.
1990 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001991 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001992 return nullptr;
1993 return VD;
1994 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001995 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001996
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001997 if (CheckScopeInfo) {
1998 bool OpenMPFound = false;
1999 for (unsigned I = StopAt + 1; I > 0; --I) {
2000 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2001 if(!isa<CapturingScopeInfo>(FSI))
2002 return nullptr;
2003 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2004 if (RSI->CapRegionKind == CR_OpenMP) {
2005 OpenMPFound = true;
2006 break;
2007 }
2008 }
2009 if (!OpenMPFound)
2010 return nullptr;
2011 }
2012
Alexey Bataev48977c32015-08-04 08:10:48 +00002013 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2014 (!DSAStack->isClauseParsingMode() ||
2015 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002016 auto &&Info = DSAStack->isLoopControlVariable(D);
2017 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002018 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002019 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002020 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002021 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002022 DSAStackTy::DSAVarData DVarPrivate =
2023 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002024 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002025 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002026 // Threadprivate variables must not be captured.
2027 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2028 return nullptr;
2029 // The variable is not private or it is the variable in the directive with
2030 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002031 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2032 [](OpenMPDirectiveKind) { return true; },
2033 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002034 if (DVarPrivate.CKind != OMPC_unknown ||
2035 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002036 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002037 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002038 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002039}
2040
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002041void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2042 unsigned Level) const {
2043 SmallVector<OpenMPDirectiveKind, 4> Regions;
2044 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2045 FunctionScopesIndex -= Regions.size();
2046}
2047
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002048void Sema::startOpenMPLoop() {
2049 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2050 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2051 DSAStack->loopInit();
2052}
2053
Alexey Bataevbef93a92019-10-07 18:54:57 +00002054void Sema::startOpenMPCXXRangeFor() {
2055 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2056 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2057 DSAStack->resetPossibleLoopCounter();
2058 DSAStack->loopStart();
2059 }
2060}
2061
Alexey Bataeve3727102018-04-18 15:57:46 +00002062bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002063 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002064 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2065 if (DSAStack->getAssociatedLoops() > 0 &&
2066 !DSAStack->isLoopStarted()) {
2067 DSAStack->resetPossibleLoopCounter(D);
2068 DSAStack->loopStart();
2069 return true;
2070 }
2071 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2072 DSAStack->isLoopControlVariable(D).first) &&
2073 !DSAStack->hasExplicitDSA(
2074 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2075 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2076 return true;
2077 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002078 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2079 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2080 DSAStack->isForceVarCapturing() &&
2081 !DSAStack->hasExplicitDSA(
2082 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2083 return true;
2084 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002085 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002086 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002087 (DSAStack->isClauseParsingMode() &&
2088 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002089 // Consider taskgroup reduction descriptor variable a private to avoid
2090 // possible capture in the region.
2091 (DSAStack->hasExplicitDirective(
2092 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2093 Level) &&
2094 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002095}
2096
Alexey Bataeve3727102018-04-18 15:57:46 +00002097void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2098 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002099 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2100 D = getCanonicalDecl(D);
2101 OpenMPClauseKind OMPC = OMPC_unknown;
2102 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2103 const unsigned NewLevel = I - 1;
2104 if (DSAStack->hasExplicitDSA(D,
2105 [&OMPC](const OpenMPClauseKind K) {
2106 if (isOpenMPPrivate(K)) {
2107 OMPC = K;
2108 return true;
2109 }
2110 return false;
2111 },
2112 NewLevel))
2113 break;
2114 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2115 D, NewLevel,
2116 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2117 OpenMPClauseKind) { return true; })) {
2118 OMPC = OMPC_map;
2119 break;
2120 }
2121 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2122 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002123 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002124 if (DSAStack->mustBeFirstprivateAtLevel(
2125 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002126 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002127 break;
2128 }
2129 }
2130 if (OMPC != OMPC_unknown)
2131 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2132}
2133
Alexey Bataeve3727102018-04-18 15:57:46 +00002134bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2135 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002136 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2137 // Return true if the current level is no longer enclosed in a target region.
2138
Alexey Bataeve3727102018-04-18 15:57:46 +00002139 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002140 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002141 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2142 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002143}
2144
Alexey Bataeved09d242014-05-28 05:53:51 +00002145void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002146
Alexey Bataev729e2422019-08-23 16:11:14 +00002147void Sema::finalizeOpenMPDelayedAnalysis() {
2148 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2149 // Diagnose implicit declare target functions and their callees.
2150 for (const auto &CallerCallees : DeviceCallGraph) {
2151 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2152 OMPDeclareTargetDeclAttr::getDeviceType(
2153 CallerCallees.getFirst()->getMostRecentDecl());
2154 // Ignore host functions during device analyzis.
2155 if (LangOpts.OpenMPIsDevice && DevTy &&
2156 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2157 continue;
2158 // Ignore nohost functions during host analyzis.
2159 if (!LangOpts.OpenMPIsDevice && DevTy &&
2160 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2161 continue;
2162 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2163 &Callee : CallerCallees.getSecond()) {
2164 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2165 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2166 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2167 if (LangOpts.OpenMPIsDevice && DevTy &&
2168 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2169 // Diagnose host function called during device codegen.
2170 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2171 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2172 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2173 << HostDevTy << 0;
2174 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2175 diag::note_omp_marked_device_type_here)
2176 << HostDevTy;
2177 continue;
2178 }
2179 if (!LangOpts.OpenMPIsDevice && DevTy &&
2180 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2181 // Diagnose nohost function called during host codegen.
2182 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2183 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2184 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2185 << NoHostDevTy << 1;
2186 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2187 diag::note_omp_marked_device_type_here)
2188 << NoHostDevTy;
2189 continue;
2190 }
2191 }
2192 }
2193}
2194
Alexey Bataev758e55e2013-09-06 18:03:48 +00002195void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2196 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002197 Scope *CurScope, SourceLocation Loc) {
2198 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002199 PushExpressionEvaluationContext(
2200 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002201}
2202
Alexey Bataevaac108a2015-06-23 04:51:00 +00002203void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2204 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002205}
2206
Alexey Bataevaac108a2015-06-23 04:51:00 +00002207void Sema::EndOpenMPClause() {
2208 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002209}
2210
Alexey Bataeve106f252019-04-01 14:25:31 +00002211static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2212 ArrayRef<OMPClause *> Clauses);
2213
Alexey Bataev758e55e2013-09-06 18:03:48 +00002214void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002215 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2216 // A variable of class type (or array thereof) that appears in a lastprivate
2217 // clause requires an accessible, unambiguous default constructor for the
2218 // class type, unless the list item is also specified in a firstprivate
2219 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002220 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2221 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002222 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2223 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002224 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002225 if (DE->isValueDependent() || DE->isTypeDependent()) {
2226 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002227 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002228 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002229 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002230 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002231 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002232 const DSAStackTy::DSAVarData DVar =
2233 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002234 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002235 // Generate helper private variable and initialize it with the
2236 // default value. The address of the original variable is replaced
2237 // by the address of the new private variable in CodeGen. This new
2238 // variable is not added to IdResolver, so the code in the OpenMP
2239 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002240 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002241 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002242 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002243 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002244 if (VDPrivate->isInvalidDecl()) {
2245 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002246 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002247 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002248 PrivateCopies.push_back(buildDeclRefExpr(
2249 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002250 } else {
2251 // The variable is also a firstprivate, so initialization sequence
2252 // for private copy is generated already.
2253 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002254 }
2255 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002256 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002257 }
2258 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002259 // Check allocate clauses.
2260 if (!CurContext->isDependentContext())
2261 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002262 }
2263
Alexey Bataev758e55e2013-09-06 18:03:48 +00002264 DSAStack->pop();
2265 DiscardCleanupsInEvaluationContext();
2266 PopExpressionEvaluationContext();
2267}
2268
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002269static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2270 Expr *NumIterations, Sema &SemaRef,
2271 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002272
Alexey Bataeva769e072013-03-22 06:34:35 +00002273namespace {
2274
Alexey Bataeve3727102018-04-18 15:57:46 +00002275class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002276private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002277 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002278
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002279public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002280 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002281 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002282 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002283 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002284 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002285 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2286 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002287 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002288 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002289 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002290
2291 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002292 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002293 }
2294
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002295};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002296
Alexey Bataeve3727102018-04-18 15:57:46 +00002297class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002298private:
2299 Sema &SemaRef;
2300
2301public:
2302 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2303 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2304 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002305 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2306 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002307 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2308 SemaRef.getCurScope());
2309 }
2310 return false;
2311 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002312
2313 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002314 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002315 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002316};
2317
Alexey Bataeved09d242014-05-28 05:53:51 +00002318} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002319
2320ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2321 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002322 const DeclarationNameInfo &Id,
2323 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002324 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2325 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2326
2327 if (Lookup.isAmbiguous())
2328 return ExprError();
2329
2330 VarDecl *VD;
2331 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002332 VarDeclFilterCCC CCC(*this);
2333 if (TypoCorrection Corrected =
2334 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2335 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002336 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002337 PDiag(Lookup.empty()
2338 ? diag::err_undeclared_var_use_suggest
2339 : diag::err_omp_expected_var_arg_suggest)
2340 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002341 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002342 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002343 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2344 : diag::err_omp_expected_var_arg)
2345 << Id.getName();
2346 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002347 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002348 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2349 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2350 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2351 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002352 }
2353 Lookup.suppressDiagnostics();
2354
2355 // OpenMP [2.9.2, Syntax, C/C++]
2356 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002357 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002358 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002359 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002360 bool IsDecl =
2361 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002362 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002363 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2364 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002365 return ExprError();
2366 }
2367
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002368 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002369 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002370 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2371 // A threadprivate directive for file-scope variables must appear outside
2372 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002373 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2374 !getCurLexicalContext()->isTranslationUnit()) {
2375 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002376 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002377 bool IsDecl =
2378 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2379 Diag(VD->getLocation(),
2380 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2381 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002382 return ExprError();
2383 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002384 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2385 // A threadprivate directive for static class member variables must appear
2386 // in the class definition, in the same scope in which the member
2387 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002388 if (CanonicalVD->isStaticDataMember() &&
2389 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2390 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002391 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002392 bool IsDecl =
2393 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2394 Diag(VD->getLocation(),
2395 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2396 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002397 return ExprError();
2398 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002399 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2400 // A threadprivate directive for namespace-scope variables must appear
2401 // outside any definition or declaration other than the namespace
2402 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002403 if (CanonicalVD->getDeclContext()->isNamespace() &&
2404 (!getCurLexicalContext()->isFileContext() ||
2405 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2406 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002407 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002408 bool IsDecl =
2409 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2410 Diag(VD->getLocation(),
2411 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2412 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002413 return ExprError();
2414 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002415 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2416 // A threadprivate directive for static block-scope variables must appear
2417 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002418 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002419 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002420 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002421 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002422 bool IsDecl =
2423 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2424 Diag(VD->getLocation(),
2425 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2426 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002427 return ExprError();
2428 }
2429
2430 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2431 // A threadprivate directive must lexically precede all references to any
2432 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002433 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2434 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002435 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002436 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002437 return ExprError();
2438 }
2439
2440 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002441 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2442 SourceLocation(), VD,
2443 /*RefersToEnclosingVariableOrCapture=*/false,
2444 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002445}
2446
Alexey Bataeved09d242014-05-28 05:53:51 +00002447Sema::DeclGroupPtrTy
2448Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2449 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002450 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002451 CurContext->addDecl(D);
2452 return DeclGroupPtrTy::make(DeclGroupRef(D));
2453 }
David Blaikie0403cb12016-01-15 23:43:25 +00002454 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002455}
2456
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002457namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002458class LocalVarRefChecker final
2459 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002460 Sema &SemaRef;
2461
2462public:
2463 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002464 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002465 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002466 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002467 diag::err_omp_local_var_in_threadprivate_init)
2468 << E->getSourceRange();
2469 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2470 << VD << VD->getSourceRange();
2471 return true;
2472 }
2473 }
2474 return false;
2475 }
2476 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002477 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002478 if (Child && Visit(Child))
2479 return true;
2480 }
2481 return false;
2482 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002483 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002484};
2485} // namespace
2486
Alexey Bataeved09d242014-05-28 05:53:51 +00002487OMPThreadPrivateDecl *
2488Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002489 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002490 for (Expr *RefExpr : VarList) {
2491 auto *DE = cast<DeclRefExpr>(RefExpr);
2492 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002493 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002494
Alexey Bataev376b4a42016-02-09 09:41:09 +00002495 // Mark variable as used.
2496 VD->setReferenced();
2497 VD->markUsed(Context);
2498
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002499 QualType QType = VD->getType();
2500 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2501 // It will be analyzed later.
2502 Vars.push_back(DE);
2503 continue;
2504 }
2505
Alexey Bataeva769e072013-03-22 06:34:35 +00002506 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2507 // A threadprivate variable must not have an incomplete type.
2508 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002509 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002510 continue;
2511 }
2512
2513 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2514 // A threadprivate variable must not have a reference type.
2515 if (VD->getType()->isReferenceType()) {
2516 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002517 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2518 bool IsDecl =
2519 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2520 Diag(VD->getLocation(),
2521 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2522 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002523 continue;
2524 }
2525
Samuel Antaof8b50122015-07-13 22:54:53 +00002526 // Check if this is a TLS variable. If TLS is not being supported, produce
2527 // the corresponding diagnostic.
2528 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2529 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2530 getLangOpts().OpenMPUseTLS &&
2531 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002532 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2533 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002534 Diag(ILoc, diag::err_omp_var_thread_local)
2535 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002536 bool IsDecl =
2537 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2538 Diag(VD->getLocation(),
2539 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2540 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002541 continue;
2542 }
2543
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002544 // Check if initial value of threadprivate variable reference variable with
2545 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002546 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002547 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002548 if (Checker.Visit(Init))
2549 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002550 }
2551
Alexey Bataeved09d242014-05-28 05:53:51 +00002552 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002553 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002554 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2555 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002556 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002557 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002558 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002559 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002560 if (!Vars.empty()) {
2561 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2562 Vars);
2563 D->setAccess(AS_public);
2564 }
2565 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002566}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002567
Alexey Bataev27ef9512019-03-20 20:14:22 +00002568static OMPAllocateDeclAttr::AllocatorTypeTy
2569getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2570 if (!Allocator)
2571 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2572 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2573 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002574 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002575 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002576 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002577 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002578 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2579 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2580 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002581 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002582 llvm::FoldingSetNodeID AEId, DAEId;
2583 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2584 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2585 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002586 AllocatorKindRes = AllocatorKind;
2587 break;
2588 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002589 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002590 return AllocatorKindRes;
2591}
2592
Alexey Bataeve106f252019-04-01 14:25:31 +00002593static bool checkPreviousOMPAllocateAttribute(
2594 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2595 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2596 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2597 return false;
2598 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2599 Expr *PrevAllocator = A->getAllocator();
2600 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2601 getAllocatorKind(S, Stack, PrevAllocator);
2602 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2603 if (AllocatorsMatch &&
2604 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2605 Allocator && PrevAllocator) {
2606 const Expr *AE = Allocator->IgnoreParenImpCasts();
2607 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2608 llvm::FoldingSetNodeID AEId, PAEId;
2609 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2610 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2611 AllocatorsMatch = AEId == PAEId;
2612 }
2613 if (!AllocatorsMatch) {
2614 SmallString<256> AllocatorBuffer;
2615 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2616 if (Allocator)
2617 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2618 SmallString<256> PrevAllocatorBuffer;
2619 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2620 if (PrevAllocator)
2621 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2622 S.getPrintingPolicy());
2623
2624 SourceLocation AllocatorLoc =
2625 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2626 SourceRange AllocatorRange =
2627 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2628 SourceLocation PrevAllocatorLoc =
2629 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2630 SourceRange PrevAllocatorRange =
2631 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2632 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2633 << (Allocator ? 1 : 0) << AllocatorStream.str()
2634 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2635 << AllocatorRange;
2636 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2637 << PrevAllocatorRange;
2638 return true;
2639 }
2640 return false;
2641}
2642
2643static void
2644applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2645 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2646 Expr *Allocator, SourceRange SR) {
2647 if (VD->hasAttr<OMPAllocateDeclAttr>())
2648 return;
2649 if (Allocator &&
2650 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2651 Allocator->isInstantiationDependent() ||
2652 Allocator->containsUnexpandedParameterPack()))
2653 return;
2654 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2655 Allocator, SR);
2656 VD->addAttr(A);
2657 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2658 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2659}
2660
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002661Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2662 SourceLocation Loc, ArrayRef<Expr *> VarList,
2663 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2664 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2665 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002666 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002667 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2668 // allocate directives that appear in a target region must specify an
2669 // allocator clause unless a requires directive with the dynamic_allocators
2670 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002671 if (LangOpts.OpenMPIsDevice &&
2672 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002673 targetDiag(Loc, diag::err_expected_allocator_clause);
2674 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002675 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002676 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002677 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2678 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002679 SmallVector<Expr *, 8> Vars;
2680 for (Expr *RefExpr : VarList) {
2681 auto *DE = cast<DeclRefExpr>(RefExpr);
2682 auto *VD = cast<VarDecl>(DE->getDecl());
2683
2684 // Check if this is a TLS variable or global register.
2685 if (VD->getTLSKind() != VarDecl::TLS_None ||
2686 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2687 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2688 !VD->isLocalVarDecl()))
2689 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002690
Alexey Bataev282555a2019-03-19 20:33:44 +00002691 // If the used several times in the allocate directive, the same allocator
2692 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002693 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2694 AllocatorKind, Allocator))
2695 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002696
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002697 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2698 // If a list item has a static storage type, the allocator expression in the
2699 // allocator clause must be a constant expression that evaluates to one of
2700 // the predefined memory allocator values.
2701 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002702 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002703 Diag(Allocator->getExprLoc(),
2704 diag::err_omp_expected_predefined_allocator)
2705 << Allocator->getSourceRange();
2706 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2707 VarDecl::DeclarationOnly;
2708 Diag(VD->getLocation(),
2709 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2710 << VD;
2711 continue;
2712 }
2713 }
2714
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002715 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002716 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2717 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002718 }
2719 if (Vars.empty())
2720 return nullptr;
2721 if (!Owner)
2722 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002723 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002724 D->setAccess(AS_public);
2725 Owner->addDecl(D);
2726 return DeclGroupPtrTy::make(DeclGroupRef(D));
2727}
2728
2729Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002730Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2731 ArrayRef<OMPClause *> ClauseList) {
2732 OMPRequiresDecl *D = nullptr;
2733 if (!CurContext->isFileContext()) {
2734 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2735 } else {
2736 D = CheckOMPRequiresDecl(Loc, ClauseList);
2737 if (D) {
2738 CurContext->addDecl(D);
2739 DSAStack->addRequiresDecl(D);
2740 }
2741 }
2742 return DeclGroupPtrTy::make(DeclGroupRef(D));
2743}
2744
2745OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2746 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002747 /// For target specific clauses, the requires directive cannot be
2748 /// specified after the handling of any of the target regions in the
2749 /// current compilation unit.
2750 ArrayRef<SourceLocation> TargetLocations =
2751 DSAStack->getEncounteredTargetLocs();
2752 if (!TargetLocations.empty()) {
2753 for (const OMPClause *CNew : ClauseList) {
2754 // Check if any of the requires clauses affect target regions.
2755 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2756 isa<OMPUnifiedAddressClause>(CNew) ||
2757 isa<OMPReverseOffloadClause>(CNew) ||
2758 isa<OMPDynamicAllocatorsClause>(CNew)) {
2759 Diag(Loc, diag::err_omp_target_before_requires)
2760 << getOpenMPClauseName(CNew->getClauseKind());
2761 for (SourceLocation TargetLoc : TargetLocations) {
2762 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2763 }
2764 }
2765 }
2766 }
2767
Kelvin Li1408f912018-09-26 04:28:39 +00002768 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2769 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2770 ClauseList);
2771 return nullptr;
2772}
2773
Alexey Bataeve3727102018-04-18 15:57:46 +00002774static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2775 const ValueDecl *D,
2776 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002777 bool IsLoopIterVar = false) {
2778 if (DVar.RefExpr) {
2779 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2780 << getOpenMPClauseName(DVar.CKind);
2781 return;
2782 }
2783 enum {
2784 PDSA_StaticMemberShared,
2785 PDSA_StaticLocalVarShared,
2786 PDSA_LoopIterVarPrivate,
2787 PDSA_LoopIterVarLinear,
2788 PDSA_LoopIterVarLastprivate,
2789 PDSA_ConstVarShared,
2790 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002791 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002792 PDSA_LocalVarPrivate,
2793 PDSA_Implicit
2794 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002795 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002796 auto ReportLoc = D->getLocation();
2797 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002798 if (IsLoopIterVar) {
2799 if (DVar.CKind == OMPC_private)
2800 Reason = PDSA_LoopIterVarPrivate;
2801 else if (DVar.CKind == OMPC_lastprivate)
2802 Reason = PDSA_LoopIterVarLastprivate;
2803 else
2804 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002805 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2806 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002807 Reason = PDSA_TaskVarFirstprivate;
2808 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002809 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002810 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002811 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002812 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002813 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002814 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002815 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002816 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002817 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002818 ReportHint = true;
2819 Reason = PDSA_LocalVarPrivate;
2820 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002821 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002822 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002823 << Reason << ReportHint
2824 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2825 } else if (DVar.ImplicitDSALoc.isValid()) {
2826 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2827 << getOpenMPClauseName(DVar.CKind);
2828 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002829}
2830
cchene06f3e02019-11-15 13:02:06 -05002831static OpenMPMapClauseKind
2832getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2833 bool IsAggregateOrDeclareTarget) {
2834 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2835 switch (M) {
2836 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2837 Kind = OMPC_MAP_alloc;
2838 break;
2839 case OMPC_DEFAULTMAP_MODIFIER_to:
2840 Kind = OMPC_MAP_to;
2841 break;
2842 case OMPC_DEFAULTMAP_MODIFIER_from:
2843 Kind = OMPC_MAP_from;
2844 break;
2845 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2846 Kind = OMPC_MAP_tofrom;
2847 break;
2848 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2849 case OMPC_DEFAULTMAP_MODIFIER_last:
2850 llvm_unreachable("Unexpected defaultmap implicit behavior");
2851 case OMPC_DEFAULTMAP_MODIFIER_none:
2852 case OMPC_DEFAULTMAP_MODIFIER_default:
2853 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2854 // IsAggregateOrDeclareTarget could be true if:
2855 // 1. the implicit behavior for aggregate is tofrom
2856 // 2. it's a declare target link
2857 if (IsAggregateOrDeclareTarget) {
2858 Kind = OMPC_MAP_tofrom;
2859 break;
2860 }
2861 llvm_unreachable("Unexpected defaultmap implicit behavior");
2862 }
2863 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2864 return Kind;
2865}
2866
Alexey Bataev758e55e2013-09-06 18:03:48 +00002867namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002868class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002869 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002870 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002871 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002872 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002873 CapturedStmt *CS = nullptr;
2874 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002875 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002876 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2877 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002878
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002879 void VisitSubCaptures(OMPExecutableDirective *S) {
2880 // Check implicitly captured variables.
2881 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2882 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002883 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002884 // Try to capture inner this->member references to generate correct mappings
2885 // and diagnostics.
2886 if (TryCaptureCXXThisMembers ||
2887 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2888 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2889 [](const CapturedStmt::Capture &C) {
2890 return C.capturesThis();
2891 }))) {
2892 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2893 TryCaptureCXXThisMembers = true;
2894 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2895 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2896 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002897 }
2898
Alexey Bataev758e55e2013-09-06 18:03:48 +00002899public:
2900 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002901 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2902 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2903 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002904 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002905 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002906 // Check the datasharing rules for the expressions in the clauses.
2907 if (!CS) {
2908 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2909 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2910 Visit(CED->getInit());
2911 return;
2912 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002913 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2914 // Do not analyze internal variables and do not enclose them into
2915 // implicit clauses.
2916 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002917 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002918 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002919 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002920 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002921
Alexey Bataeve3727102018-04-18 15:57:46 +00002922 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002923 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002924 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002925 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002926
Alexey Bataevafe50572017-10-06 17:00:28 +00002927 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002928 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002929 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002930 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002931 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2932 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002933 return;
2934
Alexey Bataeve3727102018-04-18 15:57:46 +00002935 SourceLocation ELoc = E->getExprLoc();
2936 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002937 // The default(none) clause requires that each variable that is referenced
2938 // in the construct, and does not have a predetermined data-sharing
2939 // attribute, must have its data-sharing attribute explicitly determined
2940 // by being listed in a data-sharing attribute clause.
2941 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002942 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002943 VarsWithInheritedDSA.count(VD) == 0) {
2944 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002945 return;
2946 }
2947
cchene06f3e02019-11-15 13:02:06 -05002948 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
2949 // If implicit-behavior is none, each variable referenced in the
2950 // construct that does not have a predetermined data-sharing attribute
2951 // and does not appear in a to or link clause on a declare target
2952 // directive must be listed in a data-mapping attribute clause, a
2953 // data-haring attribute clause (including a data-sharing attribute
2954 // clause on a combined construct where target. is one of the
2955 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002956 OpenMPDefaultmapClauseKind ClauseKind =
2957 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05002958 if (SemaRef.getLangOpts().OpenMP >= 50) {
2959 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
2960 OMPC_DEFAULTMAP_MODIFIER_none;
2961 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
2962 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
2963 // Only check for data-mapping attribute and is_device_ptr here
2964 // since we have already make sure that the declaration does not
2965 // have a data-sharing attribute above
2966 if (!Stack->checkMappableExprComponentListsForDecl(
2967 VD, /*CurrentRegionOnly=*/true,
2968 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
2969 MapExprComponents,
2970 OpenMPClauseKind) {
2971 auto MI = MapExprComponents.rbegin();
2972 auto ME = MapExprComponents.rend();
2973 return MI != ME && MI->getAssociatedDeclaration() == VD;
2974 })) {
2975 VarsWithInheritedDSA[VD] = E;
2976 return;
2977 }
2978 }
2979 }
2980
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002981 if (isOpenMPTargetExecutionDirective(DKind) &&
2982 !Stack->isLoopControlVariable(VD).first) {
2983 if (!Stack->checkMappableExprComponentListsForDecl(
2984 VD, /*CurrentRegionOnly=*/true,
2985 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2986 StackComponents,
2987 OpenMPClauseKind) {
2988 // Variable is used if it has been marked as an array, array
2989 // section or the variable iself.
2990 return StackComponents.size() == 1 ||
2991 std::all_of(
2992 std::next(StackComponents.rbegin()),
2993 StackComponents.rend(),
2994 [](const OMPClauseMappableExprCommon::
2995 MappableComponent &MC) {
2996 return MC.getAssociatedDeclaration() ==
2997 nullptr &&
2998 (isa<OMPArraySectionExpr>(
2999 MC.getAssociatedExpression()) ||
3000 isa<ArraySubscriptExpr>(
3001 MC.getAssociatedExpression()));
3002 });
3003 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003004 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003005 // By default lambdas are captured as firstprivates.
3006 if (const auto *RD =
3007 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003008 IsFirstprivate = RD->isLambda();
3009 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003010 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3011 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003012 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003013 } else {
3014 OpenMPDefaultmapClauseModifier M =
3015 Stack->getDefaultmapModifier(ClauseKind);
3016 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3017 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3018 ImplicitMap[Kind].emplace_back(E);
3019 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003020 return;
3021 }
3022 }
3023
Alexey Bataev758e55e2013-09-06 18:03:48 +00003024 // OpenMP [2.9.3.6, Restrictions, p.2]
3025 // A list item that appears in a reduction clause of the innermost
3026 // enclosing worksharing or parallel construct may not be accessed in an
3027 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003028 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003029 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3030 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003031 return isOpenMPParallelDirective(K) ||
3032 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3033 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003034 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003035 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003036 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003037 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003038 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003039 return;
3040 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003041
3042 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003043 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003044 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003045 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003046 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003047 return;
3048 }
3049
3050 // Store implicitly used globals with declare target link for parent
3051 // target.
3052 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3053 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3054 Stack->addToParentTargetRegionLinkGlobals(E);
3055 return;
3056 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003057 }
3058 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003059 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003060 if (E->isTypeDependent() || E->isValueDependent() ||
3061 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3062 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003063 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003064 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003065 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003066 if (!FD)
3067 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003068 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003069 // Check if the variable has explicit DSA set and stop analysis if it
3070 // so.
3071 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3072 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003073
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003074 if (isOpenMPTargetExecutionDirective(DKind) &&
3075 !Stack->isLoopControlVariable(FD).first &&
3076 !Stack->checkMappableExprComponentListsForDecl(
3077 FD, /*CurrentRegionOnly=*/true,
3078 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3079 StackComponents,
3080 OpenMPClauseKind) {
3081 return isa<CXXThisExpr>(
3082 cast<MemberExpr>(
3083 StackComponents.back().getAssociatedExpression())
3084 ->getBase()
3085 ->IgnoreParens());
3086 })) {
3087 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3088 // A bit-field cannot appear in a map clause.
3089 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003090 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003091 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003092
3093 // Check to see if the member expression is referencing a class that
3094 // has already been explicitly mapped
3095 if (Stack->isClassPreviouslyMapped(TE->getType()))
3096 return;
3097
cchene06f3e02019-11-15 13:02:06 -05003098 OpenMPDefaultmapClauseModifier Modifier =
3099 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3100 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3101 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3102 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003103 return;
3104 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003105
Alexey Bataeve3727102018-04-18 15:57:46 +00003106 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003107 // OpenMP [2.9.3.6, Restrictions, p.2]
3108 // A list item that appears in a reduction clause of the innermost
3109 // enclosing worksharing or parallel construct may not be accessed in
3110 // an explicit task.
3111 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003112 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3113 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003114 return isOpenMPParallelDirective(K) ||
3115 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3116 },
3117 /*FromParent=*/true);
3118 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3119 ErrorFound = true;
3120 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003121 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003122 return;
3123 }
3124
3125 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003126 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003127 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003128 !Stack->isLoopControlVariable(FD).first) {
3129 // Check if there is a captured expression for the current field in the
3130 // region. Do not mark it as firstprivate unless there is no captured
3131 // expression.
3132 // TODO: try to make it firstprivate.
3133 if (DVar.CKind != OMPC_unknown)
3134 ImplicitFirstprivate.push_back(E);
3135 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003136 return;
3137 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003138 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003139 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003140 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003141 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003142 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003143 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003144 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3145 if (!Stack->checkMappableExprComponentListsForDecl(
3146 VD, /*CurrentRegionOnly=*/true,
3147 [&CurComponents](
3148 OMPClauseMappableExprCommon::MappableExprComponentListRef
3149 StackComponents,
3150 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003151 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003152 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003153 for (const auto &SC : llvm::reverse(StackComponents)) {
3154 // Do both expressions have the same kind?
3155 if (CCI->getAssociatedExpression()->getStmtClass() !=
3156 SC.getAssociatedExpression()->getStmtClass())
3157 if (!(isa<OMPArraySectionExpr>(
3158 SC.getAssociatedExpression()) &&
3159 isa<ArraySubscriptExpr>(
3160 CCI->getAssociatedExpression())))
3161 return false;
3162
Alexey Bataeve3727102018-04-18 15:57:46 +00003163 const Decl *CCD = CCI->getAssociatedDeclaration();
3164 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003165 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3166 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3167 if (SCD != CCD)
3168 return false;
3169 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003170 if (CCI == CCE)
3171 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003172 }
3173 return true;
3174 })) {
3175 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003176 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003177 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003178 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003179 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003180 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003181 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003182 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003183 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003184 // for task|target directives.
3185 // Skip analysis of arguments of implicitly defined map clause for target
3186 // directives.
3187 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3188 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003189 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003190 if (CC)
3191 Visit(CC);
3192 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003193 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003194 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003195 // Check implicitly captured variables.
3196 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003197 }
3198 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003199 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003200 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003201 // Check implicitly captured variables in the task-based directives to
3202 // check if they must be firstprivatized.
3203 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003204 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003205 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003206 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003207
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003208 void visitSubCaptures(CapturedStmt *S) {
3209 for (const CapturedStmt::Capture &Cap : S->captures()) {
3210 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3211 continue;
3212 VarDecl *VD = Cap.getCapturedVar();
3213 // Do not try to map the variable if it or its sub-component was mapped
3214 // already.
3215 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3216 Stack->checkMappableExprComponentListsForDecl(
3217 VD, /*CurrentRegionOnly=*/true,
3218 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3219 OpenMPClauseKind) { return true; }))
3220 continue;
3221 DeclRefExpr *DRE = buildDeclRefExpr(
3222 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3223 Cap.getLocation(), /*RefersToCapture=*/true);
3224 Visit(DRE);
3225 }
3226 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003227 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003228 ArrayRef<Expr *> getImplicitFirstprivate() const {
3229 return ImplicitFirstprivate;
3230 }
cchene06f3e02019-11-15 13:02:06 -05003231 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3232 return ImplicitMap[Kind];
3233 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003234 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003235 return VarsWithInheritedDSA;
3236 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003237
Alexey Bataev7ff55242014-06-19 09:13:45 +00003238 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003239 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3240 // Process declare target link variables for the target directives.
3241 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3242 for (DeclRefExpr *E : Stack->getLinkGlobals())
3243 Visit(E);
3244 }
3245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003246};
Alexey Bataeved09d242014-05-28 05:53:51 +00003247} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003248
Alexey Bataevbae9a792014-06-27 10:37:06 +00003249void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003250 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003251 case OMPD_parallel:
3252 case OMPD_parallel_for:
3253 case OMPD_parallel_for_simd:
3254 case OMPD_parallel_sections:
cchen47d60942019-12-05 13:43:48 -05003255 case OMPD_parallel_master:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003256 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003257 case OMPD_teams_distribute:
3258 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003259 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003260 QualType KmpInt32PtrTy =
3261 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003262 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003263 std::make_pair(".global_tid.", KmpInt32PtrTy),
3264 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3265 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003266 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003267 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3268 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003269 break;
3270 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003271 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003272 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003273 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003274 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003275 case OMPD_target_teams_distribute:
3276 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003277 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3278 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3279 QualType KmpInt32PtrTy =
3280 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3281 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003282 FunctionProtoType::ExtProtoInfo EPI;
3283 EPI.Variadic = true;
3284 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3285 Sema::CapturedParamNameType Params[] = {
3286 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003287 std::make_pair(".part_id.", KmpInt32PtrTy),
3288 std::make_pair(".privates.", VoidPtrTy),
3289 std::make_pair(
3290 ".copy_fn.",
3291 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003292 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3293 std::make_pair(StringRef(), QualType()) // __context with shared vars
3294 };
3295 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003296 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003297 // Mark this captured region as inlined, because we don't use outlined
3298 // function directly.
3299 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3300 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003301 Context, {}, AttributeCommonInfo::AS_Keyword,
3302 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003303 Sema::CapturedParamNameType ParamsTarget[] = {
3304 std::make_pair(StringRef(), QualType()) // __context with shared vars
3305 };
3306 // Start a captured region for 'target' with no implicit parameters.
3307 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003308 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003309 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003310 std::make_pair(".global_tid.", KmpInt32PtrTy),
3311 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3312 std::make_pair(StringRef(), QualType()) // __context with shared vars
3313 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003314 // Start a captured region for 'teams' or 'parallel'. Both regions have
3315 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003316 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003317 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003318 break;
3319 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003320 case OMPD_target:
3321 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003322 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3323 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3324 QualType KmpInt32PtrTy =
3325 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3326 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003327 FunctionProtoType::ExtProtoInfo EPI;
3328 EPI.Variadic = true;
3329 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3330 Sema::CapturedParamNameType Params[] = {
3331 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003332 std::make_pair(".part_id.", KmpInt32PtrTy),
3333 std::make_pair(".privates.", VoidPtrTy),
3334 std::make_pair(
3335 ".copy_fn.",
3336 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003337 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3338 std::make_pair(StringRef(), QualType()) // __context with shared vars
3339 };
3340 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003341 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003342 // Mark this captured region as inlined, because we don't use outlined
3343 // function directly.
3344 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3345 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003346 Context, {}, AttributeCommonInfo::AS_Keyword,
3347 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003348 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003349 std::make_pair(StringRef(), QualType()),
3350 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003351 break;
3352 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003353 case OMPD_simd:
3354 case OMPD_for:
3355 case OMPD_for_simd:
3356 case OMPD_sections:
3357 case OMPD_section:
3358 case OMPD_single:
3359 case OMPD_master:
3360 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003361 case OMPD_taskgroup:
3362 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003363 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003364 case OMPD_ordered:
3365 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003366 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003367 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003368 std::make_pair(StringRef(), QualType()) // __context with shared vars
3369 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003370 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3371 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003372 break;
3373 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003374 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003375 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3376 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3377 QualType KmpInt32PtrTy =
3378 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3379 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003380 FunctionProtoType::ExtProtoInfo EPI;
3381 EPI.Variadic = true;
3382 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003383 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003384 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003385 std::make_pair(".part_id.", KmpInt32PtrTy),
3386 std::make_pair(".privates.", VoidPtrTy),
3387 std::make_pair(
3388 ".copy_fn.",
3389 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003390 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003391 std::make_pair(StringRef(), QualType()) // __context with shared vars
3392 };
3393 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3394 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003395 // Mark this captured region as inlined, because we don't use outlined
3396 // function directly.
3397 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3398 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003399 Context, {}, AttributeCommonInfo::AS_Keyword,
3400 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003401 break;
3402 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003403 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003404 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003405 case OMPD_master_taskloop:
3406 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003407 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003408 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3409 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003410 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003411 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3412 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003413 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003414 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3415 .withConst();
3416 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3417 QualType KmpInt32PtrTy =
3418 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3419 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003420 FunctionProtoType::ExtProtoInfo EPI;
3421 EPI.Variadic = true;
3422 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003423 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003424 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003425 std::make_pair(".part_id.", KmpInt32PtrTy),
3426 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003427 std::make_pair(
3428 ".copy_fn.",
3429 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3430 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3431 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003432 std::make_pair(".ub.", KmpUInt64Ty),
3433 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003434 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003435 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003436 std::make_pair(StringRef(), QualType()) // __context with shared vars
3437 };
3438 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3439 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003440 // Mark this captured region as inlined, because we don't use outlined
3441 // function directly.
3442 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3443 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003444 Context, {}, AttributeCommonInfo::AS_Keyword,
3445 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003446 break;
3447 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003448 case OMPD_parallel_master_taskloop:
3449 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003450 QualType KmpInt32Ty =
3451 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3452 .withConst();
3453 QualType KmpUInt64Ty =
3454 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3455 .withConst();
3456 QualType KmpInt64Ty =
3457 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3458 .withConst();
3459 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3460 QualType KmpInt32PtrTy =
3461 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3462 Sema::CapturedParamNameType ParamsParallel[] = {
3463 std::make_pair(".global_tid.", KmpInt32PtrTy),
3464 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3465 std::make_pair(StringRef(), QualType()) // __context with shared vars
3466 };
3467 // Start a captured region for 'parallel'.
3468 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3469 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3470 QualType Args[] = {VoidPtrTy};
3471 FunctionProtoType::ExtProtoInfo EPI;
3472 EPI.Variadic = true;
3473 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3474 Sema::CapturedParamNameType Params[] = {
3475 std::make_pair(".global_tid.", KmpInt32Ty),
3476 std::make_pair(".part_id.", KmpInt32PtrTy),
3477 std::make_pair(".privates.", VoidPtrTy),
3478 std::make_pair(
3479 ".copy_fn.",
3480 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3481 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3482 std::make_pair(".lb.", KmpUInt64Ty),
3483 std::make_pair(".ub.", KmpUInt64Ty),
3484 std::make_pair(".st.", KmpInt64Ty),
3485 std::make_pair(".liter.", KmpInt32Ty),
3486 std::make_pair(".reductions.", VoidPtrTy),
3487 std::make_pair(StringRef(), QualType()) // __context with shared vars
3488 };
3489 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3490 Params, /*OpenMPCaptureLevel=*/2);
3491 // Mark this captured region as inlined, because we don't use outlined
3492 // function directly.
3493 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3494 AlwaysInlineAttr::CreateImplicit(
3495 Context, {}, AttributeCommonInfo::AS_Keyword,
3496 AlwaysInlineAttr::Keyword_forceinline));
3497 break;
3498 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003499 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003500 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003501 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003502 QualType KmpInt32PtrTy =
3503 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3504 Sema::CapturedParamNameType Params[] = {
3505 std::make_pair(".global_tid.", KmpInt32PtrTy),
3506 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003507 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3508 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003509 std::make_pair(StringRef(), QualType()) // __context with shared vars
3510 };
3511 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3512 Params);
3513 break;
3514 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003515 case OMPD_target_teams_distribute_parallel_for:
3516 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003517 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003518 QualType KmpInt32PtrTy =
3519 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003520 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003521
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003522 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003523 FunctionProtoType::ExtProtoInfo EPI;
3524 EPI.Variadic = true;
3525 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3526 Sema::CapturedParamNameType Params[] = {
3527 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003528 std::make_pair(".part_id.", KmpInt32PtrTy),
3529 std::make_pair(".privates.", VoidPtrTy),
3530 std::make_pair(
3531 ".copy_fn.",
3532 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003533 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3534 std::make_pair(StringRef(), QualType()) // __context with shared vars
3535 };
3536 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003537 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003538 // Mark this captured region as inlined, because we don't use outlined
3539 // function directly.
3540 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3541 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003542 Context, {}, AttributeCommonInfo::AS_Keyword,
3543 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003544 Sema::CapturedParamNameType ParamsTarget[] = {
3545 std::make_pair(StringRef(), QualType()) // __context with shared vars
3546 };
3547 // Start a captured region for 'target' with no implicit parameters.
3548 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003549 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003550
3551 Sema::CapturedParamNameType ParamsTeams[] = {
3552 std::make_pair(".global_tid.", KmpInt32PtrTy),
3553 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3554 std::make_pair(StringRef(), QualType()) // __context with shared vars
3555 };
3556 // Start a captured region for 'target' with no implicit parameters.
3557 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003558 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003559
3560 Sema::CapturedParamNameType ParamsParallel[] = {
3561 std::make_pair(".global_tid.", KmpInt32PtrTy),
3562 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003563 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3564 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003565 std::make_pair(StringRef(), QualType()) // __context with shared vars
3566 };
3567 // Start a captured region for 'teams' or 'parallel'. Both regions have
3568 // the same implicit parameters.
3569 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003570 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003571 break;
3572 }
3573
Alexey Bataev46506272017-12-05 17:41:34 +00003574 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003575 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003576 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003577 QualType KmpInt32PtrTy =
3578 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3579
3580 Sema::CapturedParamNameType ParamsTeams[] = {
3581 std::make_pair(".global_tid.", KmpInt32PtrTy),
3582 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3583 std::make_pair(StringRef(), QualType()) // __context with shared vars
3584 };
3585 // Start a captured region for 'target' with no implicit parameters.
3586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003587 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003588
3589 Sema::CapturedParamNameType ParamsParallel[] = {
3590 std::make_pair(".global_tid.", KmpInt32PtrTy),
3591 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003592 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3593 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003594 std::make_pair(StringRef(), QualType()) // __context with shared vars
3595 };
3596 // Start a captured region for 'teams' or 'parallel'. Both regions have
3597 // the same implicit parameters.
3598 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003599 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003600 break;
3601 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003602 case OMPD_target_update:
3603 case OMPD_target_enter_data:
3604 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003605 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3606 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3607 QualType KmpInt32PtrTy =
3608 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3609 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003610 FunctionProtoType::ExtProtoInfo EPI;
3611 EPI.Variadic = true;
3612 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3613 Sema::CapturedParamNameType Params[] = {
3614 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003615 std::make_pair(".part_id.", KmpInt32PtrTy),
3616 std::make_pair(".privates.", VoidPtrTy),
3617 std::make_pair(
3618 ".copy_fn.",
3619 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003620 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3621 std::make_pair(StringRef(), QualType()) // __context with shared vars
3622 };
3623 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3624 Params);
3625 // Mark this captured region as inlined, because we don't use outlined
3626 // function directly.
3627 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3628 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003629 Context, {}, AttributeCommonInfo::AS_Keyword,
3630 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003631 break;
3632 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003633 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003634 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003635 case OMPD_taskyield:
3636 case OMPD_barrier:
3637 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003638 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003639 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003640 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003641 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003642 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003643 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003644 case OMPD_declare_target:
3645 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003646 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003647 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003648 llvm_unreachable("OpenMP Directive is not allowed");
3649 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003650 llvm_unreachable("Unknown OpenMP directive");
3651 }
3652}
3653
Alexey Bataev0e100032019-10-14 16:44:01 +00003654int Sema::getNumberOfConstructScopes(unsigned Level) const {
3655 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3656}
3657
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003658int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3659 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3660 getOpenMPCaptureRegions(CaptureRegions, DKind);
3661 return CaptureRegions.size();
3662}
3663
Alexey Bataev3392d762016-02-16 11:18:12 +00003664static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003665 Expr *CaptureExpr, bool WithInit,
3666 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003667 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003668 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003669 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003670 QualType Ty = Init->getType();
3671 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003672 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003673 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003674 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003675 Ty = C.getPointerType(Ty);
3676 ExprResult Res =
3677 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3678 if (!Res.isUsable())
3679 return nullptr;
3680 Init = Res.get();
3681 }
Alexey Bataev61205072016-03-02 04:57:40 +00003682 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003683 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003684 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003685 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003686 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003687 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003688 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003689 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003690 return CED;
3691}
3692
Alexey Bataev61205072016-03-02 04:57:40 +00003693static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3694 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003695 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003696 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003697 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003698 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003699 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3700 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003701 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003702 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003703}
3704
Alexey Bataev5a3af132016-03-29 08:58:54 +00003705static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003706 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003707 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003708 OMPCapturedExprDecl *CD = buildCaptureDecl(
3709 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3710 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003711 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3712 CaptureExpr->getExprLoc());
3713 }
3714 ExprResult Res = Ref;
3715 if (!S.getLangOpts().CPlusPlus &&
3716 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003717 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003718 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003719 if (!Res.isUsable())
3720 return ExprError();
3721 }
3722 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003723}
3724
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003725namespace {
3726// OpenMP directives parsed in this section are represented as a
3727// CapturedStatement with an associated statement. If a syntax error
3728// is detected during the parsing of the associated statement, the
3729// compiler must abort processing and close the CapturedStatement.
3730//
3731// Combined directives such as 'target parallel' have more than one
3732// nested CapturedStatements. This RAII ensures that we unwind out
3733// of all the nested CapturedStatements when an error is found.
3734class CaptureRegionUnwinderRAII {
3735private:
3736 Sema &S;
3737 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003738 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003739
3740public:
3741 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3742 OpenMPDirectiveKind DKind)
3743 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3744 ~CaptureRegionUnwinderRAII() {
3745 if (ErrorFound) {
3746 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3747 while (--ThisCaptureLevel >= 0)
3748 S.ActOnCapturedRegionError();
3749 }
3750 }
3751};
3752} // namespace
3753
Alexey Bataevb600ae32019-07-01 17:46:52 +00003754void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3755 // Capture variables captured by reference in lambdas for target-based
3756 // directives.
3757 if (!CurContext->isDependentContext() &&
3758 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3759 isOpenMPTargetDataManagementDirective(
3760 DSAStack->getCurrentDirective()))) {
3761 QualType Type = V->getType();
3762 if (const auto *RD = Type.getCanonicalType()
3763 .getNonReferenceType()
3764 ->getAsCXXRecordDecl()) {
3765 bool SavedForceCaptureByReferenceInTargetExecutable =
3766 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3767 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3768 /*V=*/true);
3769 if (RD->isLambda()) {
3770 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3771 FieldDecl *ThisCapture;
3772 RD->getCaptureFields(Captures, ThisCapture);
3773 for (const LambdaCapture &LC : RD->captures()) {
3774 if (LC.getCaptureKind() == LCK_ByRef) {
3775 VarDecl *VD = LC.getCapturedVar();
3776 DeclContext *VDC = VD->getDeclContext();
3777 if (!VDC->Encloses(CurContext))
3778 continue;
3779 MarkVariableReferenced(LC.getLocation(), VD);
3780 } else if (LC.getCaptureKind() == LCK_This) {
3781 QualType ThisTy = getCurrentThisType();
3782 if (!ThisTy.isNull() &&
3783 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3784 CheckCXXThisCapture(LC.getLocation());
3785 }
3786 }
3787 }
3788 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3789 SavedForceCaptureByReferenceInTargetExecutable);
3790 }
3791 }
3792}
3793
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003794StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3795 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003796 bool ErrorFound = false;
3797 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3798 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003799 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003800 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003801 return StmtError();
3802 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003803
Alexey Bataev2ba67042017-11-28 21:11:44 +00003804 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3805 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003806 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003807 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003808 SmallVector<const OMPLinearClause *, 4> LCs;
3809 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003810 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003811 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003812 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3813 Clause->getClauseKind() == OMPC_in_reduction) {
3814 // Capture taskgroup task_reduction descriptors inside the tasking regions
3815 // with the corresponding in_reduction items.
3816 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003817 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003818 if (E)
3819 MarkDeclarationsReferencedInExpr(E);
3820 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003821 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003822 Clause->getClauseKind() == OMPC_copyprivate ||
3823 (getLangOpts().OpenMPUseTLS &&
3824 getASTContext().getTargetInfo().isTLSSupported() &&
3825 Clause->getClauseKind() == OMPC_copyin)) {
3826 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003827 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003828 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003829 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003830 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003831 }
3832 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003833 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003834 } else if (CaptureRegions.size() > 1 ||
3835 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003836 if (auto *C = OMPClauseWithPreInit::get(Clause))
3837 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003838 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003839 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003840 MarkDeclarationsReferencedInExpr(E);
3841 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003842 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003843 if (Clause->getClauseKind() == OMPC_schedule)
3844 SC = cast<OMPScheduleClause>(Clause);
3845 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003846 OC = cast<OMPOrderedClause>(Clause);
3847 else if (Clause->getClauseKind() == OMPC_linear)
3848 LCs.push_back(cast<OMPLinearClause>(Clause));
3849 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003850 // OpenMP, 2.7.1 Loop Construct, Restrictions
3851 // The nonmonotonic modifier cannot be specified if an ordered clause is
3852 // specified.
3853 if (SC &&
3854 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3855 SC->getSecondScheduleModifier() ==
3856 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3857 OC) {
3858 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3859 ? SC->getFirstScheduleModifierLoc()
3860 : SC->getSecondScheduleModifierLoc(),
3861 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003862 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003863 ErrorFound = true;
3864 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003865 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003866 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003867 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003868 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003869 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003870 ErrorFound = true;
3871 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003872 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3873 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3874 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003875 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003876 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3877 ErrorFound = true;
3878 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003879 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003880 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003881 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003882 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003883 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003884 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003885 // Mark all variables in private list clauses as used in inner region.
3886 // Required for proper codegen of combined directives.
3887 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003888 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003889 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003890 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3891 // Find the particular capture region for the clause if the
3892 // directive is a combined one with multiple capture regions.
3893 // If the directive is not a combined one, the capture region
3894 // associated with the clause is OMPD_unknown and is generated
3895 // only once.
3896 if (CaptureRegion == ThisCaptureRegion ||
3897 CaptureRegion == OMPD_unknown) {
3898 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003899 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003900 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3901 }
3902 }
3903 }
3904 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003905 if (++CompletedRegions == CaptureRegions.size())
3906 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003907 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003908 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003909 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003910}
3911
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003912static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3913 OpenMPDirectiveKind CancelRegion,
3914 SourceLocation StartLoc) {
3915 // CancelRegion is only needed for cancel and cancellation_point.
3916 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3917 return false;
3918
3919 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3920 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3921 return false;
3922
3923 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3924 << getOpenMPDirectiveName(CancelRegion);
3925 return true;
3926}
3927
Alexey Bataeve3727102018-04-18 15:57:46 +00003928static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003929 OpenMPDirectiveKind CurrentRegion,
3930 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003931 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003932 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003933 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003934 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3935 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003936 bool NestingProhibited = false;
3937 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003938 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003939 enum {
3940 NoRecommend,
3941 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003942 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003943 ShouldBeInTargetRegion,
3944 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003945 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003946 if (isOpenMPSimdDirective(ParentRegion) &&
3947 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
3948 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
3949 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003950 // OpenMP [2.16, Nesting of Regions]
3951 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003952 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003953 // An ordered construct with the simd clause is the only OpenMP
3954 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003955 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003956 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3957 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003958 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
3959 // The only OpenMP constructs that can be encountered during execution of
3960 // a simd region are the atomic construct, the loop construct, the simd
3961 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00003962 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3963 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003964 : diag::warn_omp_nesting_simd)
3965 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00003966 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003967 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003968 if (ParentRegion == OMPD_atomic) {
3969 // OpenMP [2.16, Nesting of Regions]
3970 // OpenMP constructs may not be nested inside an atomic region.
3971 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3972 return true;
3973 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003974 if (CurrentRegion == OMPD_section) {
3975 // OpenMP [2.7.2, sections Construct, Restrictions]
3976 // Orphaned section directives are prohibited. That is, the section
3977 // directives must appear within the sections construct and must not be
3978 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003979 if (ParentRegion != OMPD_sections &&
3980 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003981 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3982 << (ParentRegion != OMPD_unknown)
3983 << getOpenMPDirectiveName(ParentRegion);
3984 return true;
3985 }
3986 return false;
3987 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003988 // Allow some constructs (except teams and cancellation constructs) to be
3989 // orphaned (they could be used in functions, called from OpenMP regions
3990 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003991 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003992 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3993 CurrentRegion != OMPD_cancellation_point &&
3994 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003995 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003996 if (CurrentRegion == OMPD_cancellation_point ||
3997 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003998 // OpenMP [2.16, Nesting of Regions]
3999 // A cancellation point construct for which construct-type-clause is
4000 // taskgroup must be nested inside a task construct. A cancellation
4001 // point construct for which construct-type-clause is not taskgroup must
4002 // be closely nested inside an OpenMP construct that matches the type
4003 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00004004 // A cancel construct for which construct-type-clause is taskgroup must be
4005 // nested inside a task construct. A cancel construct for which
4006 // construct-type-clause is not taskgroup must be closely nested inside an
4007 // OpenMP construct that matches the type specified in
4008 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004009 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004010 !((CancelRegion == OMPD_parallel &&
4011 (ParentRegion == OMPD_parallel ||
4012 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004013 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004014 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004015 ParentRegion == OMPD_target_parallel_for ||
4016 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004017 ParentRegion == OMPD_teams_distribute_parallel_for ||
4018 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004019 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4020 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004021 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4022 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004023 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004024 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004025 // OpenMP [2.16, Nesting of Regions]
4026 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004027 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004028 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004029 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004030 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4031 // OpenMP [2.16, Nesting of Regions]
4032 // A critical region may not be nested (closely or otherwise) inside a
4033 // critical region with the same name. Note that this restriction is not
4034 // sufficient to prevent deadlock.
4035 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004036 bool DeadLock = Stack->hasDirective(
4037 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4038 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004039 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004040 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4041 PreviousCriticalLoc = Loc;
4042 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004043 }
4044 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004045 },
4046 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004047 if (DeadLock) {
4048 SemaRef.Diag(StartLoc,
4049 diag::err_omp_prohibited_region_critical_same_name)
4050 << CurrentName.getName();
4051 if (PreviousCriticalLoc.isValid())
4052 SemaRef.Diag(PreviousCriticalLoc,
4053 diag::note_omp_previous_critical_region);
4054 return true;
4055 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004056 } else if (CurrentRegion == OMPD_barrier) {
4057 // OpenMP [2.16, Nesting of Regions]
4058 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004059 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004060 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4061 isOpenMPTaskingDirective(ParentRegion) ||
4062 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004063 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004064 ParentRegion == OMPD_critical ||
4065 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004066 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004067 !isOpenMPParallelDirective(CurrentRegion) &&
4068 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004069 // OpenMP [2.16, Nesting of Regions]
4070 // A worksharing region may not be closely nested inside a worksharing,
4071 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004072 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4073 isOpenMPTaskingDirective(ParentRegion) ||
4074 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004075 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004076 ParentRegion == OMPD_critical ||
4077 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004078 Recommend = ShouldBeInParallelRegion;
4079 } else if (CurrentRegion == OMPD_ordered) {
4080 // OpenMP [2.16, Nesting of Regions]
4081 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004082 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004083 // An ordered region must be closely nested inside a loop region (or
4084 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004085 // OpenMP [2.8.1,simd Construct, Restrictions]
4086 // An ordered construct with the simd clause is the only OpenMP construct
4087 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004088 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004089 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004090 !(isOpenMPSimdDirective(ParentRegion) ||
4091 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004092 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004093 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004094 // OpenMP [2.16, Nesting of Regions]
4095 // If specified, a teams construct must be contained within a target
4096 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004097 NestingProhibited =
4098 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4099 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4100 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004101 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004102 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004103 }
Kelvin Libf594a52016-12-17 05:48:59 +00004104 if (!NestingProhibited &&
4105 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4106 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4107 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004108 // OpenMP [2.16, Nesting of Regions]
4109 // distribute, parallel, parallel sections, parallel workshare, and the
4110 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4111 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004112 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4113 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004114 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004115 }
David Majnemer9d168222016-08-05 17:44:54 +00004116 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004117 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004118 // OpenMP 4.5 [2.17 Nesting of Regions]
4119 // The region associated with the distribute construct must be strictly
4120 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004121 NestingProhibited =
4122 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004123 Recommend = ShouldBeInTeamsRegion;
4124 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004125 if (!NestingProhibited &&
4126 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4127 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4128 // OpenMP 4.5 [2.17 Nesting of Regions]
4129 // If a target, target update, target data, target enter data, or
4130 // target exit data construct is encountered during execution of a
4131 // target region, the behavior is unspecified.
4132 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004133 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004134 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004135 if (isOpenMPTargetExecutionDirective(K)) {
4136 OffendingRegion = K;
4137 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004138 }
4139 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004140 },
4141 false /* don't skip top directive */);
4142 CloseNesting = false;
4143 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004144 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004145 if (OrphanSeen) {
4146 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4147 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4148 } else {
4149 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4150 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4151 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4152 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004153 return true;
4154 }
4155 }
4156 return false;
4157}
4158
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004159struct Kind2Unsigned {
4160 using argument_type = OpenMPDirectiveKind;
4161 unsigned operator()(argument_type DK) { return unsigned(DK); }
4162};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004163static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4164 ArrayRef<OMPClause *> Clauses,
4165 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4166 bool ErrorFound = false;
4167 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004168 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4169 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004170 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004171 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004172 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4173 // At most one if clause without a directive-name-modifier can appear on
4174 // the directive.
4175 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4176 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004177 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004178 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4179 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4180 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004181 } else if (CurNM != OMPD_unknown) {
4182 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004183 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004184 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004185 FoundNameModifiers[CurNM] = IC;
4186 if (CurNM == OMPD_unknown)
4187 continue;
4188 // Check if the specified name modifier is allowed for the current
4189 // directive.
4190 // At most one if clause with the particular directive-name-modifier can
4191 // appear on the directive.
4192 bool MatchFound = false;
4193 for (auto NM : AllowedNameModifiers) {
4194 if (CurNM == NM) {
4195 MatchFound = true;
4196 break;
4197 }
4198 }
4199 if (!MatchFound) {
4200 S.Diag(IC->getNameModifierLoc(),
4201 diag::err_omp_wrong_if_directive_name_modifier)
4202 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4203 ErrorFound = true;
4204 }
4205 }
4206 }
4207 // If any if clause on the directive includes a directive-name-modifier then
4208 // all if clauses on the directive must include a directive-name-modifier.
4209 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4210 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004211 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004212 diag::err_omp_no_more_if_clause);
4213 } else {
4214 std::string Values;
4215 std::string Sep(", ");
4216 unsigned AllowedCnt = 0;
4217 unsigned TotalAllowedNum =
4218 AllowedNameModifiers.size() - NamedModifiersNumber;
4219 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4220 ++Cnt) {
4221 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4222 if (!FoundNameModifiers[NM]) {
4223 Values += "'";
4224 Values += getOpenMPDirectiveName(NM);
4225 Values += "'";
4226 if (AllowedCnt + 2 == TotalAllowedNum)
4227 Values += " or ";
4228 else if (AllowedCnt + 1 != TotalAllowedNum)
4229 Values += Sep;
4230 ++AllowedCnt;
4231 }
4232 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004233 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004234 diag::err_omp_unnamed_if_clause)
4235 << (TotalAllowedNum > 1) << Values;
4236 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004237 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004238 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4239 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004240 ErrorFound = true;
4241 }
4242 return ErrorFound;
4243}
4244
Alexey Bataeve106f252019-04-01 14:25:31 +00004245static std::pair<ValueDecl *, bool>
4246getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4247 SourceRange &ERange, bool AllowArraySection = false) {
4248 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4249 RefExpr->containsUnexpandedParameterPack())
4250 return std::make_pair(nullptr, true);
4251
4252 // OpenMP [3.1, C/C++]
4253 // A list item is a variable name.
4254 // OpenMP [2.9.3.3, Restrictions, p.1]
4255 // A variable that is part of another variable (as an array or
4256 // structure element) cannot appear in a private clause.
4257 RefExpr = RefExpr->IgnoreParens();
4258 enum {
4259 NoArrayExpr = -1,
4260 ArraySubscript = 0,
4261 OMPArraySection = 1
4262 } IsArrayExpr = NoArrayExpr;
4263 if (AllowArraySection) {
4264 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4265 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4266 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4267 Base = TempASE->getBase()->IgnoreParenImpCasts();
4268 RefExpr = Base;
4269 IsArrayExpr = ArraySubscript;
4270 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4271 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4272 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4273 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4274 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4275 Base = TempASE->getBase()->IgnoreParenImpCasts();
4276 RefExpr = Base;
4277 IsArrayExpr = OMPArraySection;
4278 }
4279 }
4280 ELoc = RefExpr->getExprLoc();
4281 ERange = RefExpr->getSourceRange();
4282 RefExpr = RefExpr->IgnoreParenImpCasts();
4283 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4284 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4285 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4286 (S.getCurrentThisType().isNull() || !ME ||
4287 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4288 !isa<FieldDecl>(ME->getMemberDecl()))) {
4289 if (IsArrayExpr != NoArrayExpr) {
4290 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4291 << ERange;
4292 } else {
4293 S.Diag(ELoc,
4294 AllowArraySection
4295 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4296 : diag::err_omp_expected_var_name_member_expr)
4297 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4298 }
4299 return std::make_pair(nullptr, false);
4300 }
4301 return std::make_pair(
4302 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4303}
4304
4305static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004306 ArrayRef<OMPClause *> Clauses) {
4307 assert(!S.CurContext->isDependentContext() &&
4308 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004309 auto AllocateRange =
4310 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004311 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4312 DeclToCopy;
4313 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4314 return isOpenMPPrivate(C->getClauseKind());
4315 });
4316 for (OMPClause *Cl : PrivateRange) {
4317 MutableArrayRef<Expr *>::iterator I, It, Et;
4318 if (Cl->getClauseKind() == OMPC_private) {
4319 auto *PC = cast<OMPPrivateClause>(Cl);
4320 I = PC->private_copies().begin();
4321 It = PC->varlist_begin();
4322 Et = PC->varlist_end();
4323 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4324 auto *PC = cast<OMPFirstprivateClause>(Cl);
4325 I = PC->private_copies().begin();
4326 It = PC->varlist_begin();
4327 Et = PC->varlist_end();
4328 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4329 auto *PC = cast<OMPLastprivateClause>(Cl);
4330 I = PC->private_copies().begin();
4331 It = PC->varlist_begin();
4332 Et = PC->varlist_end();
4333 } else if (Cl->getClauseKind() == OMPC_linear) {
4334 auto *PC = cast<OMPLinearClause>(Cl);
4335 I = PC->privates().begin();
4336 It = PC->varlist_begin();
4337 Et = PC->varlist_end();
4338 } else if (Cl->getClauseKind() == OMPC_reduction) {
4339 auto *PC = cast<OMPReductionClause>(Cl);
4340 I = PC->privates().begin();
4341 It = PC->varlist_begin();
4342 Et = PC->varlist_end();
4343 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4344 auto *PC = cast<OMPTaskReductionClause>(Cl);
4345 I = PC->privates().begin();
4346 It = PC->varlist_begin();
4347 Et = PC->varlist_end();
4348 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4349 auto *PC = cast<OMPInReductionClause>(Cl);
4350 I = PC->privates().begin();
4351 It = PC->varlist_begin();
4352 Et = PC->varlist_end();
4353 } else {
4354 llvm_unreachable("Expected private clause.");
4355 }
4356 for (Expr *E : llvm::make_range(It, Et)) {
4357 if (!*I) {
4358 ++I;
4359 continue;
4360 }
4361 SourceLocation ELoc;
4362 SourceRange ERange;
4363 Expr *SimpleRefExpr = E;
4364 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4365 /*AllowArraySection=*/true);
4366 DeclToCopy.try_emplace(Res.first,
4367 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4368 ++I;
4369 }
4370 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004371 for (OMPClause *C : AllocateRange) {
4372 auto *AC = cast<OMPAllocateClause>(C);
4373 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4374 getAllocatorKind(S, Stack, AC->getAllocator());
4375 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4376 // For task, taskloop or target directives, allocation requests to memory
4377 // allocators with the trait access set to thread result in unspecified
4378 // behavior.
4379 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4380 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4381 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4382 S.Diag(AC->getAllocator()->getExprLoc(),
4383 diag::warn_omp_allocate_thread_on_task_target_directive)
4384 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004385 }
4386 for (Expr *E : AC->varlists()) {
4387 SourceLocation ELoc;
4388 SourceRange ERange;
4389 Expr *SimpleRefExpr = E;
4390 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4391 ValueDecl *VD = Res.first;
4392 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4393 if (!isOpenMPPrivate(Data.CKind)) {
4394 S.Diag(E->getExprLoc(),
4395 diag::err_omp_expected_private_copy_for_allocate);
4396 continue;
4397 }
4398 VarDecl *PrivateVD = DeclToCopy[VD];
4399 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4400 AllocatorKind, AC->getAllocator()))
4401 continue;
4402 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4403 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004404 }
4405 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004406}
4407
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004408StmtResult Sema::ActOnOpenMPExecutableDirective(
4409 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4410 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4411 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004412 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004413 // First check CancelRegion which is then used in checkNestingOfRegions.
4414 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4415 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004416 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004417 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004418
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004419 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004420 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004421 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004422 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004423 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004424 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4425
4426 // Check default data sharing attributes for referenced variables.
4427 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004428 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4429 Stmt *S = AStmt;
4430 while (--ThisCaptureLevel >= 0)
4431 S = cast<CapturedStmt>(S)->getCapturedStmt();
4432 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004433 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4434 !isOpenMPTaskingDirective(Kind)) {
4435 // Visit subcaptures to generate implicit clauses for captured vars.
4436 auto *CS = cast<CapturedStmt>(AStmt);
4437 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4438 getOpenMPCaptureRegions(CaptureRegions, Kind);
4439 // Ignore outer tasking regions for target directives.
4440 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4441 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4442 DSAChecker.visitSubCaptures(CS);
4443 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004444 if (DSAChecker.isErrorFound())
4445 return StmtError();
4446 // Generate list of implicitly defined firstprivate variables.
4447 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004448
Alexey Bataev88202be2017-07-27 13:20:36 +00004449 SmallVector<Expr *, 4> ImplicitFirstprivates(
4450 DSAChecker.getImplicitFirstprivate().begin(),
4451 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004452 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4453 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4454 ArrayRef<Expr *> ImplicitMap =
4455 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4456 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4457 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004458 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004459 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004460 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004461 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004462 if (E)
4463 ImplicitFirstprivates.emplace_back(E);
4464 }
4465 }
4466 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004467 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004468 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4469 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004470 ClausesWithImplicit.push_back(Implicit);
4471 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004472 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004473 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004474 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004475 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004476 }
cchene06f3e02019-11-15 13:02:06 -05004477 int ClauseKindCnt = -1;
4478 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4479 ++ClauseKindCnt;
4480 if (ImplicitMap.empty())
4481 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004482 CXXScopeSpec MapperIdScopeSpec;
4483 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004484 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004485 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004486 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4487 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4488 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004489 ClausesWithImplicit.emplace_back(Implicit);
4490 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004491 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004492 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004493 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004494 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004495 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004496 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004497
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004498 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004499 switch (Kind) {
4500 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004501 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4502 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004503 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004504 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004505 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004506 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4507 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004508 if (LangOpts.OpenMP >= 50)
4509 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004510 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004511 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004512 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4513 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004514 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004515 case OMPD_for_simd:
4516 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4517 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004518 if (LangOpts.OpenMP >= 50)
4519 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004520 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004521 case OMPD_sections:
4522 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4523 EndLoc);
4524 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004525 case OMPD_section:
4526 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004527 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004528 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4529 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004530 case OMPD_single:
4531 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4532 EndLoc);
4533 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004534 case OMPD_master:
4535 assert(ClausesWithImplicit.empty() &&
4536 "No clauses are allowed for 'omp master' directive");
4537 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4538 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004539 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004540 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4541 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004542 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004543 case OMPD_parallel_for:
4544 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4545 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004546 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004547 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004548 case OMPD_parallel_for_simd:
4549 Res = ActOnOpenMPParallelForSimdDirective(
4550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004551 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004552 if (LangOpts.OpenMP >= 50)
4553 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004554 break;
cchen47d60942019-12-05 13:43:48 -05004555 case OMPD_parallel_master:
4556 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4557 StartLoc, EndLoc);
4558 AllowedNameModifiers.push_back(OMPD_parallel);
4559 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004560 case OMPD_parallel_sections:
4561 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4562 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004563 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004564 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004565 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004566 Res =
4567 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004568 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004569 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004570 case OMPD_taskyield:
4571 assert(ClausesWithImplicit.empty() &&
4572 "No clauses are allowed for 'omp taskyield' directive");
4573 assert(AStmt == nullptr &&
4574 "No associated statement allowed for 'omp taskyield' directive");
4575 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4576 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004577 case OMPD_barrier:
4578 assert(ClausesWithImplicit.empty() &&
4579 "No clauses are allowed for 'omp barrier' directive");
4580 assert(AStmt == nullptr &&
4581 "No associated statement allowed for 'omp barrier' directive");
4582 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4583 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004584 case OMPD_taskwait:
4585 assert(ClausesWithImplicit.empty() &&
4586 "No clauses are allowed for 'omp taskwait' directive");
4587 assert(AStmt == nullptr &&
4588 "No associated statement allowed for 'omp taskwait' directive");
4589 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4590 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004591 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004592 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4593 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004594 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004595 case OMPD_flush:
4596 assert(AStmt == nullptr &&
4597 "No associated statement allowed for 'omp flush' directive");
4598 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4599 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004600 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004601 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4602 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004603 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004604 case OMPD_atomic:
4605 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4606 EndLoc);
4607 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004608 case OMPD_teams:
4609 Res =
4610 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4611 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004612 case OMPD_target:
4613 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4614 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004615 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004616 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004617 case OMPD_target_parallel:
4618 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4619 StartLoc, EndLoc);
4620 AllowedNameModifiers.push_back(OMPD_target);
4621 AllowedNameModifiers.push_back(OMPD_parallel);
4622 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004623 case OMPD_target_parallel_for:
4624 Res = ActOnOpenMPTargetParallelForDirective(
4625 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4626 AllowedNameModifiers.push_back(OMPD_target);
4627 AllowedNameModifiers.push_back(OMPD_parallel);
4628 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004629 case OMPD_cancellation_point:
4630 assert(ClausesWithImplicit.empty() &&
4631 "No clauses are allowed for 'omp cancellation point' directive");
4632 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4633 "cancellation point' directive");
4634 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4635 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004636 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004637 assert(AStmt == nullptr &&
4638 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004639 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4640 CancelRegion);
4641 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004642 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004643 case OMPD_target_data:
4644 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4645 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004646 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004647 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004648 case OMPD_target_enter_data:
4649 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004650 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004651 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4652 break;
Samuel Antao72590762016-01-19 20:04:50 +00004653 case OMPD_target_exit_data:
4654 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004655 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004656 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4657 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004658 case OMPD_taskloop:
4659 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4660 EndLoc, VarsWithInheritedDSA);
4661 AllowedNameModifiers.push_back(OMPD_taskloop);
4662 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004663 case OMPD_taskloop_simd:
4664 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4665 EndLoc, VarsWithInheritedDSA);
4666 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004667 if (LangOpts.OpenMP >= 50)
4668 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004669 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004670 case OMPD_master_taskloop:
4671 Res = ActOnOpenMPMasterTaskLoopDirective(
4672 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4673 AllowedNameModifiers.push_back(OMPD_taskloop);
4674 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004675 case OMPD_master_taskloop_simd:
4676 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4677 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4678 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004679 if (LangOpts.OpenMP >= 50)
4680 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004681 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004682 case OMPD_parallel_master_taskloop:
4683 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4684 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4685 AllowedNameModifiers.push_back(OMPD_taskloop);
4686 AllowedNameModifiers.push_back(OMPD_parallel);
4687 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004688 case OMPD_parallel_master_taskloop_simd:
4689 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4690 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4691 AllowedNameModifiers.push_back(OMPD_taskloop);
4692 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004693 if (LangOpts.OpenMP >= 50)
4694 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004695 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004696 case OMPD_distribute:
4697 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4698 EndLoc, VarsWithInheritedDSA);
4699 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004700 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004701 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4702 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004703 AllowedNameModifiers.push_back(OMPD_target_update);
4704 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004705 case OMPD_distribute_parallel_for:
4706 Res = ActOnOpenMPDistributeParallelForDirective(
4707 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4708 AllowedNameModifiers.push_back(OMPD_parallel);
4709 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004710 case OMPD_distribute_parallel_for_simd:
4711 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4712 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4713 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004714 if (LangOpts.OpenMP >= 50)
4715 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004716 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004717 case OMPD_distribute_simd:
4718 Res = ActOnOpenMPDistributeSimdDirective(
4719 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004720 if (LangOpts.OpenMP >= 50)
4721 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004722 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004723 case OMPD_target_parallel_for_simd:
4724 Res = ActOnOpenMPTargetParallelForSimdDirective(
4725 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4726 AllowedNameModifiers.push_back(OMPD_target);
4727 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004728 if (LangOpts.OpenMP >= 50)
4729 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004730 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004731 case OMPD_target_simd:
4732 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4733 EndLoc, VarsWithInheritedDSA);
4734 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004735 if (LangOpts.OpenMP >= 50)
4736 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004737 break;
Kelvin Li02532872016-08-05 14:37:37 +00004738 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004739 Res = ActOnOpenMPTeamsDistributeDirective(
4740 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004741 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004742 case OMPD_teams_distribute_simd:
4743 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4744 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004745 if (LangOpts.OpenMP >= 50)
4746 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004747 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004748 case OMPD_teams_distribute_parallel_for_simd:
4749 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4750 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4751 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004752 if (LangOpts.OpenMP >= 50)
4753 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004754 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004755 case OMPD_teams_distribute_parallel_for:
4756 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4757 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4758 AllowedNameModifiers.push_back(OMPD_parallel);
4759 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004760 case OMPD_target_teams:
4761 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4762 EndLoc);
4763 AllowedNameModifiers.push_back(OMPD_target);
4764 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004765 case OMPD_target_teams_distribute:
4766 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4767 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4768 AllowedNameModifiers.push_back(OMPD_target);
4769 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004770 case OMPD_target_teams_distribute_parallel_for:
4771 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4772 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4773 AllowedNameModifiers.push_back(OMPD_target);
4774 AllowedNameModifiers.push_back(OMPD_parallel);
4775 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004776 case OMPD_target_teams_distribute_parallel_for_simd:
4777 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4778 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4779 AllowedNameModifiers.push_back(OMPD_target);
4780 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004781 if (LangOpts.OpenMP >= 50)
4782 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004783 break;
Kelvin Lida681182017-01-10 18:08:18 +00004784 case OMPD_target_teams_distribute_simd:
4785 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4786 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4787 AllowedNameModifiers.push_back(OMPD_target);
4788 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004789 case OMPD_declare_target:
4790 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004791 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004792 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004793 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004794 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004795 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004796 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004797 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004798 llvm_unreachable("OpenMP Directive is not allowed");
4799 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004800 llvm_unreachable("Unknown OpenMP directive");
4801 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004802
Roman Lebedevb5700602019-03-20 16:32:36 +00004803 ErrorFound = Res.isInvalid() || ErrorFound;
4804
Alexey Bataev412254a2019-05-09 18:44:53 +00004805 // Check variables in the clauses if default(none) was specified.
4806 if (DSAStack->getDefaultDSA() == DSA_none) {
4807 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4808 for (OMPClause *C : Clauses) {
4809 switch (C->getClauseKind()) {
4810 case OMPC_num_threads:
4811 case OMPC_dist_schedule:
4812 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004813 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004814 break;
4815 continue;
4816 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004817 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004818 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4819 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004820 if (isOpenMPParallelDirective(Kind) &&
4821 isOpenMPTaskLoopDirective(Kind) &&
4822 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4823 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004824 continue;
4825 case OMPC_schedule:
4826 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004827 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004828 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004829 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004830 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004831 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004832 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004833 break;
4834 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004835 case OMPC_ordered:
4836 case OMPC_device:
4837 case OMPC_num_teams:
4838 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004839 case OMPC_hint:
4840 case OMPC_collapse:
4841 case OMPC_safelen:
4842 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004843 case OMPC_default:
4844 case OMPC_proc_bind:
4845 case OMPC_private:
4846 case OMPC_firstprivate:
4847 case OMPC_lastprivate:
4848 case OMPC_shared:
4849 case OMPC_reduction:
4850 case OMPC_task_reduction:
4851 case OMPC_in_reduction:
4852 case OMPC_linear:
4853 case OMPC_aligned:
4854 case OMPC_copyin:
4855 case OMPC_copyprivate:
4856 case OMPC_nowait:
4857 case OMPC_untied:
4858 case OMPC_mergeable:
4859 case OMPC_allocate:
4860 case OMPC_read:
4861 case OMPC_write:
4862 case OMPC_update:
4863 case OMPC_capture:
4864 case OMPC_seq_cst:
4865 case OMPC_depend:
4866 case OMPC_threads:
4867 case OMPC_simd:
4868 case OMPC_map:
4869 case OMPC_nogroup:
4870 case OMPC_defaultmap:
4871 case OMPC_to:
4872 case OMPC_from:
4873 case OMPC_use_device_ptr:
4874 case OMPC_is_device_ptr:
4875 continue;
4876 case OMPC_allocator:
4877 case OMPC_flush:
4878 case OMPC_threadprivate:
4879 case OMPC_uniform:
4880 case OMPC_unknown:
4881 case OMPC_unified_address:
4882 case OMPC_unified_shared_memory:
4883 case OMPC_reverse_offload:
4884 case OMPC_dynamic_allocators:
4885 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004886 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004887 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004888 llvm_unreachable("Unexpected clause");
4889 }
4890 for (Stmt *CC : C->children()) {
4891 if (CC)
4892 DSAChecker.Visit(CC);
4893 }
4894 }
4895 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4896 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4897 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004898 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004899 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4900 continue;
4901 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004902 if (DSAStack->getDefaultDSA() == DSA_none) {
4903 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4904 << P.first << P.second->getSourceRange();
4905 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4906 } else if (getLangOpts().OpenMP >= 50) {
4907 Diag(P.second->getExprLoc(),
4908 diag::err_omp_defaultmap_no_attr_for_variable)
4909 << P.first << P.second->getSourceRange();
4910 Diag(DSAStack->getDefaultDSALocation(),
4911 diag::note_omp_defaultmap_attr_none);
4912 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00004913 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004914
4915 if (!AllowedNameModifiers.empty())
4916 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4917 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004918
Alexey Bataeved09d242014-05-28 05:53:51 +00004919 if (ErrorFound)
4920 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004921
4922 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4923 Res.getAs<OMPExecutableDirective>()
4924 ->getStructuredBlock()
4925 ->setIsOMPStructuredBlock(true);
4926 }
4927
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004928 if (!CurContext->isDependentContext() &&
4929 isOpenMPTargetExecutionDirective(Kind) &&
4930 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4931 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4932 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4933 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4934 // Register target to DSA Stack.
4935 DSAStack->addTargetDirLocation(StartLoc);
4936 }
4937
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004938 return Res;
4939}
4940
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004941Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4942 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004943 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004944 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4945 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004946 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004947 assert(Linears.size() == LinModifiers.size());
4948 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004949 if (!DG || DG.get().isNull())
4950 return DeclGroupPtrTy();
4951
Alexey Bataevd158cf62019-09-13 20:18:17 +00004952 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004953 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004954 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4955 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004956 return DG;
4957 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004958 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004959 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4960 ADecl = FTD->getTemplatedDecl();
4961
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004962 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4963 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004964 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004965 return DeclGroupPtrTy();
4966 }
4967
Alexey Bataev2af33e32016-04-07 12:45:37 +00004968 // OpenMP [2.8.2, declare simd construct, Description]
4969 // The parameter of the simdlen clause must be a constant positive integer
4970 // expression.
4971 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004972 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004973 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004974 // OpenMP [2.8.2, declare simd construct, Description]
4975 // The special this pointer can be used as if was one of the arguments to the
4976 // function in any of the linear, aligned, or uniform clauses.
4977 // The uniform clause declares one or more arguments to have an invariant
4978 // value for all concurrent invocations of the function in the execution of a
4979 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004980 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4981 const Expr *UniformedLinearThis = nullptr;
4982 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004983 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004984 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4985 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004986 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4987 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004988 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004989 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004990 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004991 }
4992 if (isa<CXXThisExpr>(E)) {
4993 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004994 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004995 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004996 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4997 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004998 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004999 // OpenMP [2.8.2, declare simd construct, Description]
5000 // The aligned clause declares that the object to which each list item points
5001 // is aligned to the number of bytes expressed in the optional parameter of
5002 // the aligned clause.
5003 // The special this pointer can be used as if was one of the arguments to the
5004 // function in any of the linear, aligned, or uniform clauses.
5005 // The type of list items appearing in the aligned clause must be array,
5006 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005007 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5008 const Expr *AlignedThis = nullptr;
5009 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005010 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005011 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5012 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5013 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005014 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5015 FD->getParamDecl(PVD->getFunctionScopeIndex())
5016 ->getCanonicalDecl() == CanonPVD) {
5017 // OpenMP [2.8.1, simd construct, Restrictions]
5018 // A list-item cannot appear in more than one aligned clause.
5019 if (AlignedArgs.count(CanonPVD) > 0) {
5020 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
5021 << 1 << E->getSourceRange();
5022 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5023 diag::note_omp_explicit_dsa)
5024 << getOpenMPClauseName(OMPC_aligned);
5025 continue;
5026 }
5027 AlignedArgs[CanonPVD] = E;
5028 QualType QTy = PVD->getType()
5029 .getNonReferenceType()
5030 .getUnqualifiedType()
5031 .getCanonicalType();
5032 const Type *Ty = QTy.getTypePtrOrNull();
5033 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5034 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5035 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5036 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5037 }
5038 continue;
5039 }
5040 }
5041 if (isa<CXXThisExpr>(E)) {
5042 if (AlignedThis) {
5043 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
5044 << 2 << E->getSourceRange();
5045 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5046 << getOpenMPClauseName(OMPC_aligned);
5047 }
5048 AlignedThis = E;
5049 continue;
5050 }
5051 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5052 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5053 }
5054 // The optional parameter of the aligned clause, alignment, must be a constant
5055 // positive integer expression. If no optional parameter is specified,
5056 // implementation-defined default alignments for SIMD instructions on the
5057 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005058 SmallVector<const Expr *, 4> NewAligns;
5059 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005060 ExprResult Align;
5061 if (E)
5062 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5063 NewAligns.push_back(Align.get());
5064 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005065 // OpenMP [2.8.2, declare simd construct, Description]
5066 // The linear clause declares one or more list items to be private to a SIMD
5067 // lane and to have a linear relationship with respect to the iteration space
5068 // of a loop.
5069 // The special this pointer can be used as if was one of the arguments to the
5070 // function in any of the linear, aligned, or uniform clauses.
5071 // When a linear-step expression is specified in a linear clause it must be
5072 // either a constant integer expression or an integer-typed parameter that is
5073 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005074 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005075 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5076 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005077 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005078 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5079 ++MI;
5080 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005081 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5082 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5083 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005084 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5085 FD->getParamDecl(PVD->getFunctionScopeIndex())
5086 ->getCanonicalDecl() == CanonPVD) {
5087 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5088 // A list-item cannot appear in more than one linear clause.
5089 if (LinearArgs.count(CanonPVD) > 0) {
5090 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5091 << getOpenMPClauseName(OMPC_linear)
5092 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5093 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5094 diag::note_omp_explicit_dsa)
5095 << getOpenMPClauseName(OMPC_linear);
5096 continue;
5097 }
5098 // Each argument can appear in at most one uniform or linear clause.
5099 if (UniformedArgs.count(CanonPVD) > 0) {
5100 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5101 << getOpenMPClauseName(OMPC_linear)
5102 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5103 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5104 diag::note_omp_explicit_dsa)
5105 << getOpenMPClauseName(OMPC_uniform);
5106 continue;
5107 }
5108 LinearArgs[CanonPVD] = E;
5109 if (E->isValueDependent() || E->isTypeDependent() ||
5110 E->isInstantiationDependent() ||
5111 E->containsUnexpandedParameterPack())
5112 continue;
5113 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5114 PVD->getOriginalType());
5115 continue;
5116 }
5117 }
5118 if (isa<CXXThisExpr>(E)) {
5119 if (UniformedLinearThis) {
5120 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5121 << getOpenMPClauseName(OMPC_linear)
5122 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5123 << E->getSourceRange();
5124 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5125 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5126 : OMPC_linear);
5127 continue;
5128 }
5129 UniformedLinearThis = E;
5130 if (E->isValueDependent() || E->isTypeDependent() ||
5131 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5132 continue;
5133 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5134 E->getType());
5135 continue;
5136 }
5137 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5138 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5139 }
5140 Expr *Step = nullptr;
5141 Expr *NewStep = nullptr;
5142 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005143 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005144 // Skip the same step expression, it was checked already.
5145 if (Step == E || !E) {
5146 NewSteps.push_back(E ? NewStep : nullptr);
5147 continue;
5148 }
5149 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005150 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5151 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5152 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005153 if (UniformedArgs.count(CanonPVD) == 0) {
5154 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5155 << Step->getSourceRange();
5156 } else if (E->isValueDependent() || E->isTypeDependent() ||
5157 E->isInstantiationDependent() ||
5158 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005159 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005160 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005161 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005162 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5163 << Step->getSourceRange();
5164 }
5165 continue;
5166 }
5167 NewStep = Step;
5168 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5169 !Step->isInstantiationDependent() &&
5170 !Step->containsUnexpandedParameterPack()) {
5171 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5172 .get();
5173 if (NewStep)
5174 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5175 }
5176 NewSteps.push_back(NewStep);
5177 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005178 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5179 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005180 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005181 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5182 const_cast<Expr **>(Linears.data()), Linears.size(),
5183 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5184 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005185 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005186 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005187}
5188
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005189static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5190 QualType NewType) {
5191 assert(NewType->isFunctionProtoType() &&
5192 "Expected function type with prototype.");
5193 assert(FD->getType()->isFunctionNoProtoType() &&
5194 "Expected function with type with no prototype.");
5195 assert(FDWithProto->getType()->isFunctionProtoType() &&
5196 "Expected function with prototype.");
5197 // Synthesize parameters with the same types.
5198 FD->setType(NewType);
5199 SmallVector<ParmVarDecl *, 16> Params;
5200 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5201 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5202 SourceLocation(), nullptr, P->getType(),
5203 /*TInfo=*/nullptr, SC_None, nullptr);
5204 Param->setScopeInfo(0, Params.size());
5205 Param->setImplicit();
5206 Params.push_back(Param);
5207 }
5208
5209 FD->setParams(Params);
5210}
5211
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005212Optional<std::pair<FunctionDecl *, Expr *>>
5213Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5214 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005215 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005216 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005217
5218 const int VariantId = 1;
5219 // Must be applied only to single decl.
5220 if (!DG.get().isSingleDecl()) {
5221 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5222 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005223 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005224 }
5225 Decl *ADecl = DG.get().getSingleDecl();
5226 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5227 ADecl = FTD->getTemplatedDecl();
5228
5229 // Decl must be a function.
5230 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5231 if (!FD) {
5232 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5233 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005234 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005235 }
5236
5237 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5238 return FD->hasAttrs() &&
5239 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5240 FD->hasAttr<TargetAttr>());
5241 };
5242 // OpenMP is not compatible with CPU-specific attributes.
5243 if (HasMultiVersionAttributes(FD)) {
5244 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5245 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005246 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005247 }
5248
5249 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005250 if (FD->isUsed(false))
5251 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005252 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005253
5254 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005255 const FunctionDecl *Definition;
5256 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5257 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005258 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5259 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005260
5261 // The VariantRef must point to function.
5262 if (!VariantRef) {
5263 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005264 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005265 }
5266
5267 // Do not check templates, wait until instantiation.
5268 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5269 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005270 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5271 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005272
5273 // Convert VariantRef expression to the type of the original function to
5274 // resolve possible conflicts.
5275 ExprResult VariantRefCast;
5276 if (LangOpts.CPlusPlus) {
5277 QualType FnPtrType;
5278 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5279 if (Method && !Method->isStatic()) {
5280 const Type *ClassType =
5281 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5282 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5283 ExprResult ER;
5284 {
5285 // Build adrr_of unary op to correctly handle type checks for member
5286 // functions.
5287 Sema::TentativeAnalysisScope Trap(*this);
5288 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5289 VariantRef);
5290 }
5291 if (!ER.isUsable()) {
5292 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5293 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005294 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005295 }
5296 VariantRef = ER.get();
5297 } else {
5298 FnPtrType = Context.getPointerType(FD->getType());
5299 }
5300 ImplicitConversionSequence ICS =
5301 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5302 /*SuppressUserConversions=*/false,
5303 /*AllowExplicit=*/false,
5304 /*InOverloadResolution=*/false,
5305 /*CStyle=*/false,
5306 /*AllowObjCWritebackConversion=*/false);
5307 if (ICS.isFailure()) {
5308 Diag(VariantRef->getExprLoc(),
5309 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005310 << VariantRef->getType()
5311 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5312 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005313 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005314 }
5315 VariantRefCast = PerformImplicitConversion(
5316 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5317 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005318 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005319 // Drop previously built artificial addr_of unary op for member functions.
5320 if (Method && !Method->isStatic()) {
5321 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5322 if (auto *UO = dyn_cast<UnaryOperator>(
5323 PossibleAddrOfVariantRef->IgnoreImplicit()))
5324 VariantRefCast = UO->getSubExpr();
5325 }
5326 } else {
5327 VariantRefCast = VariantRef;
5328 }
5329
5330 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5331 if (!ER.isUsable() ||
5332 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5333 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5334 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005335 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005336 }
5337
5338 // The VariantRef must point to function.
5339 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5340 if (!DRE) {
5341 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5342 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005343 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005344 }
5345 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5346 if (!NewFD) {
5347 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5348 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005349 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005350 }
5351
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005352 // Check if function types are compatible in C.
5353 if (!LangOpts.CPlusPlus) {
5354 QualType NewType =
5355 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5356 if (NewType.isNull()) {
5357 Diag(VariantRef->getExprLoc(),
5358 diag::err_omp_declare_variant_incompat_types)
5359 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5360 return None;
5361 }
5362 if (NewType->isFunctionProtoType()) {
5363 if (FD->getType()->isFunctionNoProtoType())
5364 setPrototype(*this, FD, NewFD, NewType);
5365 else if (NewFD->getType()->isFunctionNoProtoType())
5366 setPrototype(*this, NewFD, FD, NewType);
5367 }
5368 }
5369
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005370 // Check if variant function is not marked with declare variant directive.
5371 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5372 Diag(VariantRef->getExprLoc(),
5373 diag::warn_omp_declare_variant_marked_as_declare_variant)
5374 << VariantRef->getSourceRange();
5375 SourceRange SR =
5376 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5377 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005378 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005379 }
5380
Alexey Bataevd158cf62019-09-13 20:18:17 +00005381 enum DoesntSupport {
5382 VirtFuncs = 1,
5383 Constructors = 3,
5384 Destructors = 4,
5385 DeletedFuncs = 5,
5386 DefaultedFuncs = 6,
5387 ConstexprFuncs = 7,
5388 ConstevalFuncs = 8,
5389 };
5390 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5391 if (CXXFD->isVirtual()) {
5392 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5393 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005394 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005395 }
5396
5397 if (isa<CXXConstructorDecl>(FD)) {
5398 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5399 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005400 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005401 }
5402
5403 if (isa<CXXDestructorDecl>(FD)) {
5404 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5405 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005406 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005407 }
5408 }
5409
5410 if (FD->isDeleted()) {
5411 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5412 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005413 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005414 }
5415
5416 if (FD->isDefaulted()) {
5417 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5418 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005419 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005420 }
5421
5422 if (FD->isConstexpr()) {
5423 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5424 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005425 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005426 }
5427
5428 // Check general compatibility.
5429 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005430 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5431 PartialDiagnosticAt(SourceLocation(),
5432 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005433 PartialDiagnosticAt(
5434 VariantRef->getExprLoc(),
5435 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5436 PartialDiagnosticAt(VariantRef->getExprLoc(),
5437 PDiag(diag::err_omp_declare_variant_diff)
5438 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005439 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5440 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005441 return None;
5442 return std::make_pair(FD, cast<Expr>(DRE));
5443}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005444
Alexey Bataev9ff34742019-09-25 19:43:37 +00005445void Sema::ActOnOpenMPDeclareVariantDirective(
5446 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005447 ArrayRef<OMPCtxSelectorData> Data) {
5448 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005449 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005450 SmallVector<Expr *, 4> CtxScores;
5451 SmallVector<unsigned, 4> CtxSets;
5452 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005453 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005454 bool IsError = false;
5455 for (const OMPCtxSelectorData &D : Data) {
5456 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5457 OpenMPContextSelectorKind Ctx = D.Ctx;
5458 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5459 return;
5460 Expr *Score = nullptr;
5461 if (D.Score.isUsable()) {
5462 Score = D.Score.get();
5463 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5464 !Score->isInstantiationDependent() &&
5465 !Score->containsUnexpandedParameterPack()) {
5466 Score =
5467 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5468 .get();
5469 if (Score)
5470 Score = VerifyIntegerConstantExpression(Score).get();
5471 }
5472 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005473 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5474 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5475 // 2^(l+2), respectively, where l is the number of traits in the construct
5476 // set.
5477 // TODO: implement correct logic for isa and arch traits.
5478 // TODO: take the construct context set into account when it is
5479 // implemented.
5480 int L = 0; // Currently set the number of traits in construct set to 0,
5481 // since the construct trait set in not supported yet.
5482 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5483 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5484 else
5485 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005486 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005487 switch (Ctx) {
5488 case OMP_CTX_vendor:
5489 assert(CtxSet == OMP_CTX_SET_implementation &&
5490 "Expected implementation context selector set.");
5491 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005492 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005493 case OMP_CTX_kind:
5494 assert(CtxSet == OMP_CTX_SET_device &&
5495 "Expected device context selector set.");
5496 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005497 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005498 case OMP_CTX_unknown:
5499 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005500 }
5501 IsError = IsError || !Score;
5502 CtxSets.push_back(CtxSet);
5503 Ctxs.push_back(Ctx);
5504 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005505 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005506 if (!IsError) {
5507 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5508 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5509 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005510 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5511 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005512 FD->addAttr(NewAttr);
5513 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005514}
5515
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005516void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5517 FunctionDecl *Func,
5518 bool MightBeOdrUse) {
5519 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5520
5521 if (!Func->isDependentContext() && Func->hasAttrs()) {
5522 for (OMPDeclareVariantAttr *A :
5523 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5524 // TODO: add checks for active OpenMP context where possible.
5525 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005526 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005527 auto *F = cast<FunctionDecl>(DRE->getDecl());
5528 if (!F->isDefined() && F->isTemplateInstantiation())
5529 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5530 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5531 }
5532 }
5533}
5534
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005535StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5536 Stmt *AStmt,
5537 SourceLocation StartLoc,
5538 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005539 if (!AStmt)
5540 return StmtError();
5541
Alexey Bataeve3727102018-04-18 15:57:46 +00005542 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005543 // 1.2.2 OpenMP Language Terminology
5544 // Structured block - An executable statement with a single entry at the
5545 // top and a single exit at the bottom.
5546 // The point of exit cannot be a branch out of the structured block.
5547 // longjmp() and throw() must not violate the entry/exit criteria.
5548 CS->getCapturedDecl()->setNothrow();
5549
Reid Kleckner87a31802018-03-12 21:43:02 +00005550 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005551
Alexey Bataev25e5b442015-09-15 12:52:43 +00005552 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5553 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005554}
5555
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005556namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005557/// Iteration space of a single for loop.
5558struct LoopIterationSpace final {
5559 /// True if the condition operator is the strict compare operator (<, > or
5560 /// !=).
5561 bool IsStrictCompare = false;
5562 /// Condition of the loop.
5563 Expr *PreCond = nullptr;
5564 /// This expression calculates the number of iterations in the loop.
5565 /// It is always possible to calculate it before starting the loop.
5566 Expr *NumIterations = nullptr;
5567 /// The loop counter variable.
5568 Expr *CounterVar = nullptr;
5569 /// Private loop counter variable.
5570 Expr *PrivateCounterVar = nullptr;
5571 /// This is initializer for the initial value of #CounterVar.
5572 Expr *CounterInit = nullptr;
5573 /// This is step for the #CounterVar used to generate its update:
5574 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5575 Expr *CounterStep = nullptr;
5576 /// Should step be subtracted?
5577 bool Subtract = false;
5578 /// Source range of the loop init.
5579 SourceRange InitSrcRange;
5580 /// Source range of the loop condition.
5581 SourceRange CondSrcRange;
5582 /// Source range of the loop increment.
5583 SourceRange IncSrcRange;
5584 /// Minimum value that can have the loop control variable. Used to support
5585 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5586 /// since only such variables can be used in non-loop invariant expressions.
5587 Expr *MinValue = nullptr;
5588 /// Maximum value that can have the loop control variable. Used to support
5589 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5590 /// since only such variables can be used in non-loop invariant expressions.
5591 Expr *MaxValue = nullptr;
5592 /// true, if the lower bound depends on the outer loop control var.
5593 bool IsNonRectangularLB = false;
5594 /// true, if the upper bound depends on the outer loop control var.
5595 bool IsNonRectangularUB = false;
5596 /// Index of the loop this loop depends on and forms non-rectangular loop
5597 /// nest.
5598 unsigned LoopDependentIdx = 0;
5599 /// Final condition for the non-rectangular loop nest support. It is used to
5600 /// check that the number of iterations for this particular counter must be
5601 /// finished.
5602 Expr *FinalCondition = nullptr;
5603};
5604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005605/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005606/// extracting iteration space of each loop in the loop nest, that will be used
5607/// for IR generation.
5608class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005609 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005610 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005611 /// Data-sharing stack.
5612 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005613 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005614 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005615 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005616 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005617 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005618 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005619 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005620 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005621 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005622 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005623 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005624 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005625 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005626 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005627 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005628 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005629 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005630 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005631 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005632 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005633 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005634 /// Var < UB
5635 /// Var <= UB
5636 /// UB > Var
5637 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005638 /// This will have no value when the condition is !=
5639 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005640 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005641 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005642 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005643 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005644 /// The outer loop counter this loop depends on (if any).
5645 const ValueDecl *DepDecl = nullptr;
5646 /// Contains number of loop (starts from 1) on which loop counter init
5647 /// expression of this loop depends on.
5648 Optional<unsigned> InitDependOnLC;
5649 /// Contains number of loop (starts from 1) on which loop counter condition
5650 /// expression of this loop depends on.
5651 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005652 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005653 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005654 /// Original condition required for checking of the exit condition for
5655 /// non-rectangular loop.
5656 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005657
5658public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005659 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5660 SourceLocation DefaultLoc)
5661 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5662 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005663 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005664 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005665 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005666 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005667 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005668 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005669 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005670 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005671 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005672 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005673 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005674 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005675 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005676 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005677 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005678 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005679 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005680 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005681 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005682 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005683 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005684 /// True, if the compare operator is strict (<, > or !=).
5685 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005686 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005687 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005688 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005689 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005690 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005691 Expr *
5692 buildPreCond(Scope *S, Expr *Cond,
5693 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005694 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005695 DeclRefExpr *
5696 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5697 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005698 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005699 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005700 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005701 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005702 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005703 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005704 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005705 /// Build loop data with counter value for depend clauses in ordered
5706 /// directives.
5707 Expr *
5708 buildOrderedLoopData(Scope *S, Expr *Counter,
5709 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5710 SourceLocation Loc, Expr *Inc = nullptr,
5711 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005712 /// Builds the minimum value for the loop counter.
5713 std::pair<Expr *, Expr *> buildMinMaxValues(
5714 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5715 /// Builds final condition for the non-rectangular loops.
5716 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005717 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005718 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005719 /// Returns true if the initializer forms non-rectangular loop.
5720 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5721 /// Returns true if the condition forms non-rectangular loop.
5722 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5723 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5724 unsigned getLoopDependentIdx() const {
5725 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5726 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005727
5728private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005729 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005730 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005731 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005732 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005733 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5734 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005735 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005736 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5737 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005738 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005739 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005740};
5741
Alexey Bataeve3727102018-04-18 15:57:46 +00005742bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005743 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005744 assert(!LB && !UB && !Step);
5745 return false;
5746 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005747 return LCDecl->getType()->isDependentType() ||
5748 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5749 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005750}
5751
Alexey Bataeve3727102018-04-18 15:57:46 +00005752bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005753 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005754 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005755 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005756 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005757 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005758 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005759 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005760 LCDecl = getCanonicalDecl(NewLCDecl);
5761 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005762 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5763 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005764 if ((Ctor->isCopyOrMoveConstructor() ||
5765 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5766 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005767 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005768 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005769 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005770 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005771 return false;
5772}
5773
Alexey Bataev316ccf62019-01-29 18:51:58 +00005774bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5775 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005776 bool StrictOp, SourceRange SR,
5777 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005778 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005779 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5780 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005781 if (!NewUB)
5782 return true;
5783 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005784 if (LessOp)
5785 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005786 TestIsStrictOp = StrictOp;
5787 ConditionSrcRange = SR;
5788 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005789 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005790 return false;
5791}
5792
Alexey Bataeve3727102018-04-18 15:57:46 +00005793bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005794 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005795 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005796 if (!NewStep)
5797 return true;
5798 if (!NewStep->isValueDependent()) {
5799 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005800 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005801 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5802 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005803 if (Val.isInvalid())
5804 return true;
5805 NewStep = Val.get();
5806
5807 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5808 // If test-expr is of form var relational-op b and relational-op is < or
5809 // <= then incr-expr must cause var to increase on each iteration of the
5810 // loop. If test-expr is of form var relational-op b and relational-op is
5811 // > or >= then incr-expr must cause var to decrease on each iteration of
5812 // the loop.
5813 // If test-expr is of form b relational-op var and relational-op is < or
5814 // <= then incr-expr must cause var to decrease on each iteration of the
5815 // loop. If test-expr is of form b relational-op var and relational-op is
5816 // > or >= then incr-expr must cause var to increase on each iteration of
5817 // the loop.
5818 llvm::APSInt Result;
5819 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5820 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5821 bool IsConstNeg =
5822 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005823 bool IsConstPos =
5824 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005825 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005826
5827 // != with increment is treated as <; != with decrement is treated as >
5828 if (!TestIsLessOp.hasValue())
5829 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005830 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005831 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005832 (IsConstNeg || (IsUnsigned && Subtract)) :
5833 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005834 SemaRef.Diag(NewStep->getExprLoc(),
5835 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005836 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005837 SemaRef.Diag(ConditionLoc,
5838 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005839 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005840 return true;
5841 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005842 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005843 NewStep =
5844 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5845 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005846 Subtract = !Subtract;
5847 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005848 }
5849
5850 Step = NewStep;
5851 SubtractStep = Subtract;
5852 return false;
5853}
5854
Alexey Bataev622af1d2019-04-24 19:58:30 +00005855namespace {
5856/// Checker for the non-rectangular loops. Checks if the initializer or
5857/// condition expression references loop counter variable.
5858class LoopCounterRefChecker final
5859 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5860 Sema &SemaRef;
5861 DSAStackTy &Stack;
5862 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005863 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005864 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005865 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005866 unsigned BaseLoopId = 0;
5867 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5868 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5869 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5870 << (IsInitializer ? 0 : 1);
5871 return false;
5872 }
5873 const auto &&Data = Stack.isLoopControlVariable(VD);
5874 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5875 // The type of the loop iterator on which we depend may not have a random
5876 // access iterator type.
5877 if (Data.first && VD->getType()->isRecordType()) {
5878 SmallString<128> Name;
5879 llvm::raw_svector_ostream OS(Name);
5880 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5881 /*Qualified=*/true);
5882 SemaRef.Diag(E->getExprLoc(),
5883 diag::err_omp_wrong_dependency_iterator_type)
5884 << OS.str();
5885 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5886 return false;
5887 }
5888 if (Data.first &&
5889 (DepDecl || (PrevDepDecl &&
5890 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5891 if (!DepDecl && PrevDepDecl)
5892 DepDecl = PrevDepDecl;
5893 SmallString<128> Name;
5894 llvm::raw_svector_ostream OS(Name);
5895 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5896 /*Qualified=*/true);
5897 SemaRef.Diag(E->getExprLoc(),
5898 diag::err_omp_invariant_or_linear_dependency)
5899 << OS.str();
5900 return false;
5901 }
5902 if (Data.first) {
5903 DepDecl = VD;
5904 BaseLoopId = Data.first;
5905 }
5906 return Data.first;
5907 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005908
5909public:
5910 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5911 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005912 if (isa<VarDecl>(VD))
5913 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005914 return false;
5915 }
5916 bool VisitMemberExpr(const MemberExpr *E) {
5917 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5918 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005919 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5920 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005921 }
5922 return false;
5923 }
5924 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005925 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005926 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005927 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005928 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005929 }
5930 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005931 const ValueDecl *CurLCDecl, bool IsInitializer,
5932 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005933 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005934 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5935 unsigned getBaseLoopId() const {
5936 assert(CurLCDecl && "Expected loop dependency.");
5937 return BaseLoopId;
5938 }
5939 const ValueDecl *getDepDecl() const {
5940 assert(CurLCDecl && "Expected loop dependency.");
5941 return DepDecl;
5942 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005943};
5944} // namespace
5945
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005946Optional<unsigned>
5947OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5948 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005949 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005950 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5951 DepDecl);
5952 if (LoopStmtChecker.Visit(S)) {
5953 DepDecl = LoopStmtChecker.getDepDecl();
5954 return LoopStmtChecker.getBaseLoopId();
5955 }
5956 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005957}
5958
Alexey Bataeve3727102018-04-18 15:57:46 +00005959bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005960 // Check init-expr for canonical loop form and save loop counter
5961 // variable - #Var and its initialization value - #LB.
5962 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5963 // var = lb
5964 // integer-type var = lb
5965 // random-access-iterator-type var = lb
5966 // pointer-type var = lb
5967 //
5968 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005969 if (EmitDiags) {
5970 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5971 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005972 return true;
5973 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005974 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5975 if (!ExprTemp->cleanupsHaveSideEffects())
5976 S = ExprTemp->getSubExpr();
5977
Alexander Musmana5f070a2014-10-01 06:03:56 +00005978 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005979 if (Expr *E = dyn_cast<Expr>(S))
5980 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005981 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005982 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005983 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005984 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5985 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5986 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005987 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5988 EmitDiags);
5989 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005990 }
5991 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5992 if (ME->isArrow() &&
5993 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005994 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5995 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005996 }
5997 }
David Majnemer9d168222016-08-05 17:44:54 +00005998 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005999 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006000 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006001 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006002 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006003 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006004 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006005 diag::ext_omp_loop_not_canonical_init)
6006 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006007 return setLCDeclAndLB(
6008 Var,
6009 buildDeclRefExpr(SemaRef, Var,
6010 Var->getType().getNonReferenceType(),
6011 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006012 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006013 }
6014 }
6015 }
David Majnemer9d168222016-08-05 17:44:54 +00006016 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006017 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006018 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006019 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006020 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6021 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006022 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6023 EmitDiags);
6024 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006025 }
6026 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6027 if (ME->isArrow() &&
6028 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006029 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6030 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006031 }
6032 }
6033 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006034
Alexey Bataeve3727102018-04-18 15:57:46 +00006035 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006036 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006037 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006038 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006039 << S->getSourceRange();
6040 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006041 return true;
6042}
6043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006044/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006045/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006046static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006047 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006048 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006049 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006050 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006051 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006052 if ((Ctor->isCopyOrMoveConstructor() ||
6053 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6054 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006055 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006056 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6057 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006058 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006059 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006060 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006061 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6062 return getCanonicalDecl(ME->getMemberDecl());
6063 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006064}
6065
Alexey Bataeve3727102018-04-18 15:57:46 +00006066bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006067 // Check test-expr for canonical form, save upper-bound UB, flags for
6068 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006069 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006070 // var relational-op b
6071 // b relational-op var
6072 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006073 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006074 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006075 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6076 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006077 return true;
6078 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006079 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006080 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006081 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006082 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006083 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006084 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6085 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006086 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6087 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6088 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006089 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6090 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006091 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6092 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6093 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006094 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6095 return setUB(
6096 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6097 /*LessOp=*/llvm::None,
6098 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006099 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006100 if (CE->getNumArgs() == 2) {
6101 auto Op = CE->getOperator();
6102 switch (Op) {
6103 case OO_Greater:
6104 case OO_GreaterEqual:
6105 case OO_Less:
6106 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006107 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6108 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006109 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6110 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006111 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6112 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006113 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6114 CE->getOperatorLoc());
6115 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006116 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006117 if (IneqCondIsCanonical)
6118 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6119 : CE->getArg(0),
6120 /*LessOp=*/llvm::None,
6121 /*StrictOp=*/true, CE->getSourceRange(),
6122 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006123 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006124 default:
6125 break;
6126 }
6127 }
6128 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006129 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006130 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006131 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006132 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006133 return true;
6134}
6135
Alexey Bataeve3727102018-04-18 15:57:46 +00006136bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006137 // RHS of canonical loop form increment can be:
6138 // var + incr
6139 // incr + var
6140 // var - incr
6141 //
6142 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006143 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006144 if (BO->isAdditiveOp()) {
6145 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006146 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6147 return setStep(BO->getRHS(), !IsAdd);
6148 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6149 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006150 }
David Majnemer9d168222016-08-05 17:44:54 +00006151 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006152 bool IsAdd = CE->getOperator() == OO_Plus;
6153 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006154 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6155 return setStep(CE->getArg(1), !IsAdd);
6156 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6157 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006158 }
6159 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006160 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006161 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006162 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006163 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006164 return true;
6165}
6166
Alexey Bataeve3727102018-04-18 15:57:46 +00006167bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006168 // Check incr-expr for canonical loop form and return true if it
6169 // does not conform.
6170 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6171 // ++var
6172 // var++
6173 // --var
6174 // var--
6175 // var += incr
6176 // var -= incr
6177 // var = var + incr
6178 // var = incr + var
6179 // var = var - incr
6180 //
6181 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006182 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006183 return true;
6184 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006185 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6186 if (!ExprTemp->cleanupsHaveSideEffects())
6187 S = ExprTemp->getSubExpr();
6188
Alexander Musmana5f070a2014-10-01 06:03:56 +00006189 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006190 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006191 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006192 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006193 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6194 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006195 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006196 (UO->isDecrementOp() ? -1 : 1))
6197 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006198 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006199 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006200 switch (BO->getOpcode()) {
6201 case BO_AddAssign:
6202 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006203 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6204 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006205 break;
6206 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006207 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6208 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006209 break;
6210 default:
6211 break;
6212 }
David Majnemer9d168222016-08-05 17:44:54 +00006213 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006214 switch (CE->getOperator()) {
6215 case OO_PlusPlus:
6216 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006217 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6218 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006219 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006220 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006221 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6222 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006223 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006224 break;
6225 case OO_PlusEqual:
6226 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006227 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6228 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006229 break;
6230 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006231 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6232 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006233 break;
6234 default:
6235 break;
6236 }
6237 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006238 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006239 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006240 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006241 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006242 return true;
6243}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006244
Alexey Bataev5a3af132016-03-29 08:58:54 +00006245static ExprResult
6246tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006247 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006248 if (SemaRef.CurContext->isDependentContext())
6249 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006250 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6251 return SemaRef.PerformImplicitConversion(
6252 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6253 /*AllowExplicit=*/true);
6254 auto I = Captures.find(Capture);
6255 if (I != Captures.end())
6256 return buildCapture(SemaRef, Capture, I->second);
6257 DeclRefExpr *Ref = nullptr;
6258 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6259 Captures[Capture] = Ref;
6260 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006261}
6262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006263/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006264Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006265 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006266 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006267 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006268 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006269 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006270 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006271 Expr *LBVal = LB;
6272 Expr *UBVal = UB;
6273 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6274 // max(LB(MinVal), LB(MaxVal))
6275 if (InitDependOnLC) {
6276 const LoopIterationSpace &IS =
6277 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6278 InitDependOnLC.getValueOr(
6279 CondDependOnLC.getValueOr(0))];
6280 if (!IS.MinValue || !IS.MaxValue)
6281 return nullptr;
6282 // OuterVar = Min
6283 ExprResult MinValue =
6284 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6285 if (!MinValue.isUsable())
6286 return nullptr;
6287
6288 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6289 IS.CounterVar, MinValue.get());
6290 if (!LBMinVal.isUsable())
6291 return nullptr;
6292 // OuterVar = Min, LBVal
6293 LBMinVal =
6294 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6295 if (!LBMinVal.isUsable())
6296 return nullptr;
6297 // (OuterVar = Min, LBVal)
6298 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6299 if (!LBMinVal.isUsable())
6300 return nullptr;
6301
6302 // OuterVar = Max
6303 ExprResult MaxValue =
6304 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6305 if (!MaxValue.isUsable())
6306 return nullptr;
6307
6308 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6309 IS.CounterVar, MaxValue.get());
6310 if (!LBMaxVal.isUsable())
6311 return nullptr;
6312 // OuterVar = Max, LBVal
6313 LBMaxVal =
6314 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6315 if (!LBMaxVal.isUsable())
6316 return nullptr;
6317 // (OuterVar = Max, LBVal)
6318 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6319 if (!LBMaxVal.isUsable())
6320 return nullptr;
6321
6322 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6323 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6324 if (!LBMin || !LBMax)
6325 return nullptr;
6326 // LB(MinVal) < LB(MaxVal)
6327 ExprResult MinLessMaxRes =
6328 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6329 if (!MinLessMaxRes.isUsable())
6330 return nullptr;
6331 Expr *MinLessMax =
6332 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6333 if (!MinLessMax)
6334 return nullptr;
6335 if (TestIsLessOp.getValue()) {
6336 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6337 // LB(MaxVal))
6338 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6339 MinLessMax, LBMin, LBMax);
6340 if (!MinLB.isUsable())
6341 return nullptr;
6342 LBVal = MinLB.get();
6343 } else {
6344 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6345 // LB(MaxVal))
6346 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6347 MinLessMax, LBMax, LBMin);
6348 if (!MaxLB.isUsable())
6349 return nullptr;
6350 LBVal = MaxLB.get();
6351 }
6352 }
6353 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6354 // min(UB(MinVal), UB(MaxVal))
6355 if (CondDependOnLC) {
6356 const LoopIterationSpace &IS =
6357 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6358 InitDependOnLC.getValueOr(
6359 CondDependOnLC.getValueOr(0))];
6360 if (!IS.MinValue || !IS.MaxValue)
6361 return nullptr;
6362 // OuterVar = Min
6363 ExprResult MinValue =
6364 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6365 if (!MinValue.isUsable())
6366 return nullptr;
6367
6368 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6369 IS.CounterVar, MinValue.get());
6370 if (!UBMinVal.isUsable())
6371 return nullptr;
6372 // OuterVar = Min, UBVal
6373 UBMinVal =
6374 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6375 if (!UBMinVal.isUsable())
6376 return nullptr;
6377 // (OuterVar = Min, UBVal)
6378 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6379 if (!UBMinVal.isUsable())
6380 return nullptr;
6381
6382 // OuterVar = Max
6383 ExprResult MaxValue =
6384 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6385 if (!MaxValue.isUsable())
6386 return nullptr;
6387
6388 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6389 IS.CounterVar, MaxValue.get());
6390 if (!UBMaxVal.isUsable())
6391 return nullptr;
6392 // OuterVar = Max, UBVal
6393 UBMaxVal =
6394 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6395 if (!UBMaxVal.isUsable())
6396 return nullptr;
6397 // (OuterVar = Max, UBVal)
6398 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6399 if (!UBMaxVal.isUsable())
6400 return nullptr;
6401
6402 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6403 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6404 if (!UBMin || !UBMax)
6405 return nullptr;
6406 // UB(MinVal) > UB(MaxVal)
6407 ExprResult MinGreaterMaxRes =
6408 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6409 if (!MinGreaterMaxRes.isUsable())
6410 return nullptr;
6411 Expr *MinGreaterMax =
6412 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6413 if (!MinGreaterMax)
6414 return nullptr;
6415 if (TestIsLessOp.getValue()) {
6416 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6417 // UB(MaxVal))
6418 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6419 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6420 if (!MaxUB.isUsable())
6421 return nullptr;
6422 UBVal = MaxUB.get();
6423 } else {
6424 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6425 // UB(MaxVal))
6426 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6427 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6428 if (!MinUB.isUsable())
6429 return nullptr;
6430 UBVal = MinUB.get();
6431 }
6432 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006433 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006434 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6435 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006436 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6437 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006438 if (!Upper || !Lower)
6439 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006440
6441 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6442
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006443 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006444 // BuildBinOp already emitted error, this one is to point user to upper
6445 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006446 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006447 << Upper->getSourceRange() << Lower->getSourceRange();
6448 return nullptr;
6449 }
6450 }
6451
6452 if (!Diff.isUsable())
6453 return nullptr;
6454
6455 // Upper - Lower [- 1]
6456 if (TestIsStrictOp)
6457 Diff = SemaRef.BuildBinOp(
6458 S, DefaultLoc, BO_Sub, Diff.get(),
6459 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6460 if (!Diff.isUsable())
6461 return nullptr;
6462
6463 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006464 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006465 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006466 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006467 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006468 if (!Diff.isUsable())
6469 return nullptr;
6470
6471 // Parentheses (for dumping/debugging purposes only).
6472 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6473 if (!Diff.isUsable())
6474 return nullptr;
6475
6476 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006477 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006478 if (!Diff.isUsable())
6479 return nullptr;
6480
Alexander Musman174b3ca2014-10-06 11:16:29 +00006481 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006482 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006483 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006484 bool UseVarType = VarType->hasIntegerRepresentation() &&
6485 C.getTypeSize(Type) > C.getTypeSize(VarType);
6486 if (!Type->isIntegerType() || UseVarType) {
6487 unsigned NewSize =
6488 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6489 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6490 : Type->hasSignedIntegerRepresentation();
6491 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006492 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6493 Diff = SemaRef.PerformImplicitConversion(
6494 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6495 if (!Diff.isUsable())
6496 return nullptr;
6497 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006498 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006499 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006500 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6501 if (NewSize != C.getTypeSize(Type)) {
6502 if (NewSize < C.getTypeSize(Type)) {
6503 assert(NewSize == 64 && "incorrect loop var size");
6504 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6505 << InitSrcRange << ConditionSrcRange;
6506 }
6507 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006508 NewSize, Type->hasSignedIntegerRepresentation() ||
6509 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006510 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6511 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6512 Sema::AA_Converting, true);
6513 if (!Diff.isUsable())
6514 return nullptr;
6515 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006516 }
6517 }
6518
Alexander Musmana5f070a2014-10-01 06:03:56 +00006519 return Diff.get();
6520}
6521
Alexey Bataevf8be4762019-08-14 19:30:06 +00006522std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6523 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6524 // Do not build for iterators, they cannot be used in non-rectangular loop
6525 // nests.
6526 if (LCDecl->getType()->isRecordType())
6527 return std::make_pair(nullptr, nullptr);
6528 // If we subtract, the min is in the condition, otherwise the min is in the
6529 // init value.
6530 Expr *MinExpr = nullptr;
6531 Expr *MaxExpr = nullptr;
6532 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6533 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6534 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6535 : CondDependOnLC.hasValue();
6536 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6537 : InitDependOnLC.hasValue();
6538 Expr *Lower =
6539 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6540 Expr *Upper =
6541 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6542 if (!Upper || !Lower)
6543 return std::make_pair(nullptr, nullptr);
6544
6545 if (TestIsLessOp.getValue())
6546 MinExpr = Lower;
6547 else
6548 MaxExpr = Upper;
6549
6550 // Build minimum/maximum value based on number of iterations.
6551 ExprResult Diff;
6552 QualType VarType = LCDecl->getType().getNonReferenceType();
6553
6554 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6555 if (!Diff.isUsable())
6556 return std::make_pair(nullptr, nullptr);
6557
6558 // Upper - Lower [- 1]
6559 if (TestIsStrictOp)
6560 Diff = SemaRef.BuildBinOp(
6561 S, DefaultLoc, BO_Sub, Diff.get(),
6562 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6563 if (!Diff.isUsable())
6564 return std::make_pair(nullptr, nullptr);
6565
6566 // Upper - Lower [- 1] + Step
6567 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6568 if (!NewStep.isUsable())
6569 return std::make_pair(nullptr, nullptr);
6570
6571 // Parentheses (for dumping/debugging purposes only).
6572 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6573 if (!Diff.isUsable())
6574 return std::make_pair(nullptr, nullptr);
6575
6576 // (Upper - Lower [- 1]) / Step
6577 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6578 if (!Diff.isUsable())
6579 return std::make_pair(nullptr, nullptr);
6580
6581 // ((Upper - Lower [- 1]) / Step) * Step
6582 // Parentheses (for dumping/debugging purposes only).
6583 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6584 if (!Diff.isUsable())
6585 return std::make_pair(nullptr, nullptr);
6586
6587 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6588 if (!Diff.isUsable())
6589 return std::make_pair(nullptr, nullptr);
6590
6591 // Convert to the original type or ptrdiff_t, if original type is pointer.
6592 if (!VarType->isAnyPointerType() &&
6593 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6594 Diff = SemaRef.PerformImplicitConversion(
6595 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6596 } else if (VarType->isAnyPointerType() &&
6597 !SemaRef.Context.hasSameType(
6598 Diff.get()->getType(),
6599 SemaRef.Context.getUnsignedPointerDiffType())) {
6600 Diff = SemaRef.PerformImplicitConversion(
6601 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6602 Sema::AA_Converting, /*AllowExplicit=*/true);
6603 }
6604 if (!Diff.isUsable())
6605 return std::make_pair(nullptr, nullptr);
6606
6607 // Parentheses (for dumping/debugging purposes only).
6608 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6609 if (!Diff.isUsable())
6610 return std::make_pair(nullptr, nullptr);
6611
6612 if (TestIsLessOp.getValue()) {
6613 // MinExpr = Lower;
6614 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6615 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6616 if (!Diff.isUsable())
6617 return std::make_pair(nullptr, nullptr);
6618 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6619 if (!Diff.isUsable())
6620 return std::make_pair(nullptr, nullptr);
6621 MaxExpr = Diff.get();
6622 } else {
6623 // MaxExpr = Upper;
6624 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6625 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6626 if (!Diff.isUsable())
6627 return std::make_pair(nullptr, nullptr);
6628 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6629 if (!Diff.isUsable())
6630 return std::make_pair(nullptr, nullptr);
6631 MinExpr = Diff.get();
6632 }
6633
6634 return std::make_pair(MinExpr, MaxExpr);
6635}
6636
6637Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6638 if (InitDependOnLC || CondDependOnLC)
6639 return Condition;
6640 return nullptr;
6641}
6642
Alexey Bataeve3727102018-04-18 15:57:46 +00006643Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006644 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006645 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006646 // Do not build a precondition when the condition/initialization is dependent
6647 // to prevent pessimistic early loop exit.
6648 // TODO: this can be improved by calculating min/max values but not sure that
6649 // it will be very effective.
6650 if (CondDependOnLC || InitDependOnLC)
6651 return SemaRef.PerformImplicitConversion(
6652 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6653 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6654 /*AllowExplicit=*/true).get();
6655
Alexey Bataev62dbb972015-04-22 11:59:37 +00006656 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006657 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006658
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006659 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6660 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006661 if (!NewLB.isUsable() || !NewUB.isUsable())
6662 return nullptr;
6663
Alexey Bataeve3727102018-04-18 15:57:46 +00006664 ExprResult CondExpr =
6665 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006666 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006667 (TestIsStrictOp ? BO_LT : BO_LE) :
6668 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006669 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006670 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006671 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6672 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006673 CondExpr = SemaRef.PerformImplicitConversion(
6674 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6675 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006676 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006677
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006678 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006679 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6680}
6681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006682/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006683DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006684 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6685 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006686 auto *VD = dyn_cast<VarDecl>(LCDecl);
6687 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006688 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6689 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006690 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006691 const DSAStackTy::DSAVarData Data =
6692 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006693 // If the loop control decl is explicitly marked as private, do not mark it
6694 // as captured again.
6695 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6696 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006697 return Ref;
6698 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006699 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006700}
6701
Alexey Bataeve3727102018-04-18 15:57:46 +00006702Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006703 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006704 QualType Type = LCDecl->getType().getNonReferenceType();
6705 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006706 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6707 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6708 isa<VarDecl>(LCDecl)
6709 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6710 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006711 if (PrivateVar->isInvalidDecl())
6712 return nullptr;
6713 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6714 }
6715 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006716}
6717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006719Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006721/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006722Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006723
Alexey Bataevf138fda2018-08-13 19:04:24 +00006724Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6725 Scope *S, Expr *Counter,
6726 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6727 Expr *Inc, OverloadedOperatorKind OOK) {
6728 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6729 if (!Cnt)
6730 return nullptr;
6731 if (Inc) {
6732 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6733 "Expected only + or - operations for depend clauses.");
6734 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6735 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6736 if (!Cnt)
6737 return nullptr;
6738 }
6739 ExprResult Diff;
6740 QualType VarType = LCDecl->getType().getNonReferenceType();
6741 if (VarType->isIntegerType() || VarType->isPointerType() ||
6742 SemaRef.getLangOpts().CPlusPlus) {
6743 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006744 Expr *Upper = TestIsLessOp.getValue()
6745 ? Cnt
6746 : tryBuildCapture(SemaRef, UB, Captures).get();
6747 Expr *Lower = TestIsLessOp.getValue()
6748 ? tryBuildCapture(SemaRef, LB, Captures).get()
6749 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006750 if (!Upper || !Lower)
6751 return nullptr;
6752
6753 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6754
6755 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6756 // BuildBinOp already emitted error, this one is to point user to upper
6757 // and lower bound, and to tell what is passed to 'operator-'.
6758 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6759 << Upper->getSourceRange() << Lower->getSourceRange();
6760 return nullptr;
6761 }
6762 }
6763
6764 if (!Diff.isUsable())
6765 return nullptr;
6766
6767 // Parentheses (for dumping/debugging purposes only).
6768 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6769 if (!Diff.isUsable())
6770 return nullptr;
6771
6772 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6773 if (!NewStep.isUsable())
6774 return nullptr;
6775 // (Upper - Lower) / Step
6776 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6777 if (!Diff.isUsable())
6778 return nullptr;
6779
6780 return Diff.get();
6781}
Alexey Bataev23b69422014-06-18 07:08:49 +00006782} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006783
Alexey Bataev9c821032015-04-30 04:23:23 +00006784void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6785 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6786 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006787 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6788 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006789 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006790 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006791 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006792 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6793 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006794 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006795 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006796 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006797 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006798 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006799 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006800 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6801 /*WithInit=*/false);
6802 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006803 }
6804 }
6805 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006806 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6807 if (LD != D->getCanonicalDecl()) {
6808 DSAStack->resetPossibleLoopCounter();
6809 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6810 MarkDeclarationsReferencedInExpr(
6811 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6812 Var->getType().getNonLValueExprType(Context),
6813 ForLoc, /*RefersToCapture=*/true));
6814 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006815 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6816 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6817 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6818 // associated for-loop of a simd construct with just one associated
6819 // for-loop may be listed in a linear clause with a constant-linear-step
6820 // that is the increment of the associated for-loop. The loop iteration
6821 // variable(s) in the associated for-loop(s) of a for or parallel for
6822 // construct may be listed in a private or lastprivate clause.
6823 DSAStackTy::DSAVarData DVar =
6824 DSAStack->getTopDSA(D, /*FromParent=*/false);
6825 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6826 // is declared in the loop and it is predetermined as a private.
6827 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6828 OpenMPClauseKind PredeterminedCKind =
6829 isOpenMPSimdDirective(DKind)
6830 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6831 : OMPC_private;
6832 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6833 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6834 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6835 DVar.CKind != OMPC_private))) ||
6836 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006837 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006838 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006839 isOpenMPDistributeDirective(DKind)) &&
6840 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6841 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6842 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6843 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6844 << getOpenMPClauseName(DVar.CKind)
6845 << getOpenMPDirectiveName(DKind)
6846 << getOpenMPClauseName(PredeterminedCKind);
6847 if (DVar.RefExpr == nullptr)
6848 DVar.CKind = PredeterminedCKind;
6849 reportOriginalDsa(*this, DSAStack, D, DVar,
6850 /*IsLoopIterVar=*/true);
6851 } else if (LoopDeclRefExpr) {
6852 // Make the loop iteration variable private (for worksharing
6853 // constructs), linear (for simd directives with the only one
6854 // associated loop) or lastprivate (for simd directives with several
6855 // collapsed or ordered loops).
6856 if (DVar.CKind == OMPC_unknown)
6857 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6858 PrivateRef);
6859 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006860 }
6861 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006862 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006863 }
6864}
6865
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006866/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006867/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006868static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006869 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6870 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006871 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6872 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006873 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006874 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006875 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006876 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006877 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006878 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006879 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006880 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6881 // Ranged for is supported only in OpenMP 5.0.
6882 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006883 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006884 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006885 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006886 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006887 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006888 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6889 SemaRef.Diag(DSA.getConstructLoc(),
6890 diag::note_omp_collapse_ordered_expr)
6891 << 2 << CollapseLoopCountExpr->getSourceRange()
6892 << OrderedLoopCountExpr->getSourceRange();
6893 else if (CollapseLoopCountExpr)
6894 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6895 diag::note_omp_collapse_ordered_expr)
6896 << 0 << CollapseLoopCountExpr->getSourceRange();
6897 else
6898 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6899 diag::note_omp_collapse_ordered_expr)
6900 << 1 << OrderedLoopCountExpr->getSourceRange();
6901 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006902 return true;
6903 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006904 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6905 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006906
Alexey Bataevbef93a92019-10-07 18:54:57 +00006907 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6908 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006909
6910 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006911 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006912 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006913 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006914
6915 bool HasErrors = false;
6916
6917 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006918 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006919 // OpenMP [2.6, Canonical Loop Form]
6920 // Var is one of the following:
6921 // A variable of signed or unsigned integer type.
6922 // For C++, a variable of a random access iterator type.
6923 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006924 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006925 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6926 !VarType->isPointerType() &&
6927 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006928 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006929 << SemaRef.getLangOpts().CPlusPlus;
6930 HasErrors = true;
6931 }
6932
6933 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6934 // a Construct
6935 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6936 // parallel for construct is (are) private.
6937 // The loop iteration variable in the associated for-loop of a simd
6938 // construct with just one associated for-loop is linear with a
6939 // constant-linear-step that is the increment of the associated for-loop.
6940 // Exclude loop var from the list of variables with implicitly defined data
6941 // sharing attributes.
6942 VarsWithImplicitDSA.erase(LCDecl);
6943
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006944 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6945
6946 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006947 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006948
6949 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006950 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006951 }
6952
Alexey Bataeve3727102018-04-18 15:57:46 +00006953 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006954 return HasErrors;
6955
Alexander Musmana5f070a2014-10-01 06:03:56 +00006956 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006957 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6958 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006959 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6960 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6961 (isOpenMPWorksharingDirective(DKind) ||
6962 isOpenMPTaskLoopDirective(DKind) ||
6963 isOpenMPDistributeDirective(DKind)),
6964 Captures);
6965 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6966 ISC.buildCounterVar(Captures, DSA);
6967 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6968 ISC.buildPrivateCounterVar();
6969 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6970 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6971 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6972 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6973 ISC.getConditionSrcRange();
6974 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6975 ISC.getIncrementSrcRange();
6976 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6977 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6978 ISC.isStrictTestOp();
6979 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6980 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6981 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6982 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6983 ISC.buildFinalCondition(DSA.getCurScope());
6984 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6985 ISC.doesInitDependOnLC();
6986 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6987 ISC.doesCondDependOnLC();
6988 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6989 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006990
Alexey Bataevf8be4762019-08-14 19:30:06 +00006991 HasErrors |=
6992 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6993 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6994 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6995 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6996 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6997 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006998 if (!HasErrors && DSA.isOrderedRegion()) {
6999 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7000 if (CurrentNestedLoopCount <
7001 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7002 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007003 CurrentNestedLoopCount,
7004 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007005 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007006 CurrentNestedLoopCount,
7007 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007008 }
7009 }
7010 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7011 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7012 // Erroneous case - clause has some problems.
7013 continue;
7014 }
7015 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7016 Pair.second.size() <= CurrentNestedLoopCount) {
7017 // Erroneous case - clause has some problems.
7018 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7019 continue;
7020 }
7021 Expr *CntValue;
7022 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7023 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007024 DSA.getCurScope(),
7025 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007026 Pair.first->getDependencyLoc());
7027 else
7028 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007029 DSA.getCurScope(),
7030 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007031 Pair.first->getDependencyLoc(),
7032 Pair.second[CurrentNestedLoopCount].first,
7033 Pair.second[CurrentNestedLoopCount].second);
7034 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7035 }
7036 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007037
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007038 return HasErrors;
7039}
7040
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007041/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007042static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007043buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007044 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007045 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007046 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007047 ExprResult NewStart = IsNonRectangularLB
7048 ? Start.get()
7049 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007050 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007051 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007052 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007053 VarRef.get()->getType())) {
7054 NewStart = SemaRef.PerformImplicitConversion(
7055 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7056 /*AllowExplicit=*/true);
7057 if (!NewStart.isUsable())
7058 return ExprError();
7059 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007060
Alexey Bataeve3727102018-04-18 15:57:46 +00007061 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007062 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7063 return Init;
7064}
7065
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007066/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007067static ExprResult buildCounterUpdate(
7068 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7069 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007070 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007071 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007072 // Add parentheses (for debugging purposes only).
7073 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7074 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7075 !Step.isUsable())
7076 return ExprError();
7077
Alexey Bataev5a3af132016-03-29 08:58:54 +00007078 ExprResult NewStep = Step;
7079 if (Captures)
7080 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007081 if (NewStep.isInvalid())
7082 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007083 ExprResult Update =
7084 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007085 if (!Update.isUsable())
7086 return ExprError();
7087
Alexey Bataevc0214e02016-02-16 12:13:49 +00007088 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7089 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007090 if (!Start.isUsable())
7091 return ExprError();
7092 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7093 if (!NewStart.isUsable())
7094 return ExprError();
7095 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007096 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007097 if (NewStart.isInvalid())
7098 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007099
Alexey Bataevc0214e02016-02-16 12:13:49 +00007100 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7101 ExprResult SavedUpdate = Update;
7102 ExprResult UpdateVal;
7103 if (VarRef.get()->getType()->isOverloadableType() ||
7104 NewStart.get()->getType()->isOverloadableType() ||
7105 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007106 Sema::TentativeAnalysisScope Trap(SemaRef);
7107
Alexey Bataevc0214e02016-02-16 12:13:49 +00007108 Update =
7109 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7110 if (Update.isUsable()) {
7111 UpdateVal =
7112 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7113 VarRef.get(), SavedUpdate.get());
7114 if (UpdateVal.isUsable()) {
7115 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7116 UpdateVal.get());
7117 }
7118 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007119 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007120
Alexey Bataevc0214e02016-02-16 12:13:49 +00007121 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7122 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7123 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7124 NewStart.get(), SavedUpdate.get());
7125 if (!Update.isUsable())
7126 return ExprError();
7127
Alexey Bataev11481f52016-02-17 10:29:05 +00007128 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7129 VarRef.get()->getType())) {
7130 Update = SemaRef.PerformImplicitConversion(
7131 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7132 if (!Update.isUsable())
7133 return ExprError();
7134 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007135
7136 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7137 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007138 return Update;
7139}
7140
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007141/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007142/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007143static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007144 if (E == nullptr)
7145 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007146 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007147 QualType OldType = E->getType();
7148 unsigned HasBits = C.getTypeSize(OldType);
7149 if (HasBits >= Bits)
7150 return ExprResult(E);
7151 // OK to convert to signed, because new type has more bits than old.
7152 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7153 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7154 true);
7155}
7156
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007157/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007158/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007159static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007160 if (E == nullptr)
7161 return false;
7162 llvm::APSInt Result;
7163 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7164 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7165 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007166}
7167
Alexey Bataev5a3af132016-03-29 08:58:54 +00007168/// Build preinits statement for the given declarations.
7169static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007170 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007171 if (!PreInits.empty()) {
7172 return new (Context) DeclStmt(
7173 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7174 SourceLocation(), SourceLocation());
7175 }
7176 return nullptr;
7177}
7178
7179/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007180static Stmt *
7181buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007182 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007183 if (!Captures.empty()) {
7184 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007185 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007186 PreInits.push_back(Pair.second->getDecl());
7187 return buildPreInits(Context, PreInits);
7188 }
7189 return nullptr;
7190}
7191
7192/// Build postupdate expression for the given list of postupdates expressions.
7193static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7194 Expr *PostUpdate = nullptr;
7195 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007196 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007197 Expr *ConvE = S.BuildCStyleCastExpr(
7198 E->getExprLoc(),
7199 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7200 E->getExprLoc(), E)
7201 .get();
7202 PostUpdate = PostUpdate
7203 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7204 PostUpdate, ConvE)
7205 .get()
7206 : ConvE;
7207 }
7208 }
7209 return PostUpdate;
7210}
7211
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007212/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007213/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7214/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007215static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007216checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007217 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7218 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007219 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007220 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007221 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007222 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007223 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007224 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007225 if (!CollapseLoopCountExpr->isValueDependent() &&
7226 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007227 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007228 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007229 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007230 return 1;
7231 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007232 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007233 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007234 if (OrderedLoopCountExpr) {
7235 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007236 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007237 if (!OrderedLoopCountExpr->isValueDependent() &&
7238 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7239 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007240 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007241 if (Result.getLimitedValue() < NestedLoopCount) {
7242 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7243 diag::err_omp_wrong_ordered_loop_count)
7244 << OrderedLoopCountExpr->getSourceRange();
7245 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7246 diag::note_collapse_loop_count)
7247 << CollapseLoopCountExpr->getSourceRange();
7248 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007249 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007250 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007251 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007252 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007253 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007254 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007255 // This is helper routine for loop directives (e.g., 'for', 'simd',
7256 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007257 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007258 SmallVector<LoopIterationSpace, 4> IterSpaces(
7259 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007260 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007261 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007262 if (checkOpenMPIterationSpace(
7263 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7264 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007265 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007266 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007267 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007268 // OpenMP [2.8.1, simd construct, Restrictions]
7269 // All loops associated with the construct must be perfectly nested; that
7270 // is, there must be no intervening code nor any OpenMP directive between
7271 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007272 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7273 CurStmt = For->getBody();
7274 } else {
7275 assert(isa<CXXForRangeStmt>(CurStmt) &&
7276 "Expected canonical for or range-based for loops.");
7277 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7278 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007279 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7280 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007281 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007282 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7283 if (checkOpenMPIterationSpace(
7284 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7285 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007286 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007287 return 0;
7288 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7289 // Handle initialization of captured loop iterator variables.
7290 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7291 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7292 Captures[DRE] = DRE;
7293 }
7294 }
7295 // Move on to the next nested for loop, or to the loop body.
7296 // OpenMP [2.8.1, simd construct, Restrictions]
7297 // All loops associated with the construct must be perfectly nested; that
7298 // is, there must be no intervening code nor any OpenMP directive between
7299 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007300 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7301 CurStmt = For->getBody();
7302 } else {
7303 assert(isa<CXXForRangeStmt>(CurStmt) &&
7304 "Expected canonical for or range-based for loops.");
7305 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7306 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007307 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7308 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007309 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007310
Alexander Musmana5f070a2014-10-01 06:03:56 +00007311 Built.clear(/* size */ NestedLoopCount);
7312
7313 if (SemaRef.CurContext->isDependentContext())
7314 return NestedLoopCount;
7315
7316 // An example of what is generated for the following code:
7317 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007318 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007319 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007320 // for (k = 0; k < NK; ++k)
7321 // for (j = J0; j < NJ; j+=2) {
7322 // <loop body>
7323 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007324 //
7325 // We generate the code below.
7326 // Note: the loop body may be outlined in CodeGen.
7327 // Note: some counters may be C++ classes, operator- is used to find number of
7328 // iterations and operator+= to calculate counter value.
7329 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7330 // or i64 is currently supported).
7331 //
7332 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7333 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7334 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7335 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7336 // // similar updates for vars in clauses (e.g. 'linear')
7337 // <loop body (using local i and j)>
7338 // }
7339 // i = NI; // assign final values of counters
7340 // j = NJ;
7341 //
7342
7343 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7344 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007345 // Precondition tests if there is at least one iteration (all conditions are
7346 // true).
7347 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007348 Expr *N0 = IterSpaces[0].NumIterations;
7349 ExprResult LastIteration32 =
7350 widenIterationCount(/*Bits=*/32,
7351 SemaRef
7352 .PerformImplicitConversion(
7353 N0->IgnoreImpCasts(), N0->getType(),
7354 Sema::AA_Converting, /*AllowExplicit=*/true)
7355 .get(),
7356 SemaRef);
7357 ExprResult LastIteration64 = widenIterationCount(
7358 /*Bits=*/64,
7359 SemaRef
7360 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7361 Sema::AA_Converting,
7362 /*AllowExplicit=*/true)
7363 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007364 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007365
7366 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7367 return NestedLoopCount;
7368
Alexey Bataeve3727102018-04-18 15:57:46 +00007369 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007370 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7371
7372 Scope *CurScope = DSA.getCurScope();
7373 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007374 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007375 PreCond =
7376 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7377 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007378 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007379 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007380 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007381 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7382 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007383 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007384 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007385 SemaRef
7386 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7387 Sema::AA_Converting,
7388 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007389 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007390 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007391 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007392 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007393 SemaRef
7394 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7395 Sema::AA_Converting,
7396 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007397 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007398 }
7399
7400 // Choose either the 32-bit or 64-bit version.
7401 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007402 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7403 (LastIteration32.isUsable() &&
7404 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7405 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7406 fitsInto(
7407 /*Bits=*/32,
7408 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7409 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007410 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007411 QualType VType = LastIteration.get()->getType();
7412 QualType RealVType = VType;
7413 QualType StrideVType = VType;
7414 if (isOpenMPTaskLoopDirective(DKind)) {
7415 VType =
7416 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7417 StrideVType =
7418 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7419 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007420
7421 if (!LastIteration.isUsable())
7422 return 0;
7423
7424 // Save the number of iterations.
7425 ExprResult NumIterations = LastIteration;
7426 {
7427 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007428 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7429 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007430 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7431 if (!LastIteration.isUsable())
7432 return 0;
7433 }
7434
7435 // Calculate the last iteration number beforehand instead of doing this on
7436 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7437 llvm::APSInt Result;
7438 bool IsConstant =
7439 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7440 ExprResult CalcLastIteration;
7441 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007442 ExprResult SaveRef =
7443 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007444 LastIteration = SaveRef;
7445
7446 // Prepare SaveRef + 1.
7447 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007448 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007449 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7450 if (!NumIterations.isUsable())
7451 return 0;
7452 }
7453
7454 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7455
David Majnemer9d168222016-08-05 17:44:54 +00007456 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007457 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007458 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7459 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007460 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007461 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7462 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007463 SemaRef.AddInitializerToDecl(LBDecl,
7464 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7465 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007466
7467 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007468 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7469 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007470 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007471 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007472
7473 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7474 // This will be used to implement clause 'lastprivate'.
7475 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007476 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7477 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007478 SemaRef.AddInitializerToDecl(ILDecl,
7479 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7480 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007481
7482 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007483 VarDecl *STDecl =
7484 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7485 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007486 SemaRef.AddInitializerToDecl(STDecl,
7487 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7488 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007489
7490 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007491 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007492 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7493 UB.get(), LastIteration.get());
7494 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007495 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7496 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007497 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7498 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007499 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007500
7501 // If we have a combined directive that combines 'distribute', 'for' or
7502 // 'simd' we need to be able to access the bounds of the schedule of the
7503 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7504 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7505 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007506 // Lower bound variable, initialized with zero.
7507 VarDecl *CombLBDecl =
7508 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7509 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7510 SemaRef.AddInitializerToDecl(
7511 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7512 /*DirectInit*/ false);
7513
7514 // Upper bound variable, initialized with last iteration number.
7515 VarDecl *CombUBDecl =
7516 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7517 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7518 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7519 /*DirectInit*/ false);
7520
7521 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7522 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7523 ExprResult CombCondOp =
7524 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7525 LastIteration.get(), CombUB.get());
7526 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7527 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007528 CombEUB =
7529 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007530
Alexey Bataeve3727102018-04-18 15:57:46 +00007531 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007532 // We expect to have at least 2 more parameters than the 'parallel'
7533 // directive does - the lower and upper bounds of the previous schedule.
7534 assert(CD->getNumParams() >= 4 &&
7535 "Unexpected number of parameters in loop combined directive");
7536
7537 // Set the proper type for the bounds given what we learned from the
7538 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007539 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7540 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007541
7542 // Previous lower and upper bounds are obtained from the region
7543 // parameters.
7544 PrevLB =
7545 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7546 PrevUB =
7547 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7548 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007549 }
7550
7551 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007552 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007553 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007554 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007555 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7556 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007557 Expr *RHS =
7558 (isOpenMPWorksharingDirective(DKind) ||
7559 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7560 ? LB.get()
7561 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007562 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007563 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007564
7565 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7566 Expr *CombRHS =
7567 (isOpenMPWorksharingDirective(DKind) ||
7568 isOpenMPTaskLoopDirective(DKind) ||
7569 isOpenMPDistributeDirective(DKind))
7570 ? CombLB.get()
7571 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7572 CombInit =
7573 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007574 CombInit =
7575 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007576 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007577 }
7578
Alexey Bataev316ccf62019-01-29 18:51:58 +00007579 bool UseStrictCompare =
7580 RealVType->hasUnsignedIntegerRepresentation() &&
7581 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7582 return LIS.IsStrictCompare;
7583 });
7584 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7585 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007586 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007587 Expr *BoundUB = UB.get();
7588 if (UseStrictCompare) {
7589 BoundUB =
7590 SemaRef
7591 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7592 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7593 .get();
7594 BoundUB =
7595 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7596 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007597 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007598 (isOpenMPWorksharingDirective(DKind) ||
7599 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007600 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7601 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7602 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007603 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7604 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007605 ExprResult CombDistCond;
7606 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007607 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7608 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007609 }
7610
Carlo Bertolliffafe102017-04-20 00:39:39 +00007611 ExprResult CombCond;
7612 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007613 Expr *BoundCombUB = CombUB.get();
7614 if (UseStrictCompare) {
7615 BoundCombUB =
7616 SemaRef
7617 .BuildBinOp(
7618 CurScope, CondLoc, BO_Add, BoundCombUB,
7619 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7620 .get();
7621 BoundCombUB =
7622 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7623 .get();
7624 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007625 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007626 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7627 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007628 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007629 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007630 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007631 ExprResult Inc =
7632 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7633 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7634 if (!Inc.isUsable())
7635 return 0;
7636 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007637 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007638 if (!Inc.isUsable())
7639 return 0;
7640
7641 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7642 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007643 // In combined construct, add combined version that use CombLB and CombUB
7644 // base variables for the update
7645 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007646 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7647 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007648 // LB + ST
7649 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7650 if (!NextLB.isUsable())
7651 return 0;
7652 // LB = LB + ST
7653 NextLB =
7654 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007655 NextLB =
7656 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007657 if (!NextLB.isUsable())
7658 return 0;
7659 // UB + ST
7660 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7661 if (!NextUB.isUsable())
7662 return 0;
7663 // UB = UB + ST
7664 NextUB =
7665 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007666 NextUB =
7667 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007668 if (!NextUB.isUsable())
7669 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007670 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7671 CombNextLB =
7672 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7673 if (!NextLB.isUsable())
7674 return 0;
7675 // LB = LB + ST
7676 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7677 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007678 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7679 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007680 if (!CombNextLB.isUsable())
7681 return 0;
7682 // UB + ST
7683 CombNextUB =
7684 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7685 if (!CombNextUB.isUsable())
7686 return 0;
7687 // UB = UB + ST
7688 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7689 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007690 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7691 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007692 if (!CombNextUB.isUsable())
7693 return 0;
7694 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007695 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007696
Carlo Bertolliffafe102017-04-20 00:39:39 +00007697 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007698 // directive with for as IV = IV + ST; ensure upper bound expression based
7699 // on PrevUB instead of NumIterations - used to implement 'for' when found
7700 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007701 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007702 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007703 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007704 DistCond = SemaRef.BuildBinOp(
7705 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007706 assert(DistCond.isUsable() && "distribute cond expr was not built");
7707
7708 DistInc =
7709 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7710 assert(DistInc.isUsable() && "distribute inc expr was not built");
7711 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7712 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007713 DistInc =
7714 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007715 assert(DistInc.isUsable() && "distribute inc expr was not built");
7716
7717 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7718 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007719 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007720 ExprResult IsUBGreater =
7721 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7722 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7723 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7724 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7725 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007726 PrevEUB =
7727 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007728
Alexey Bataev316ccf62019-01-29 18:51:58 +00007729 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7730 // parallel for is in combination with a distribute directive with
7731 // schedule(static, 1)
7732 Expr *BoundPrevUB = PrevUB.get();
7733 if (UseStrictCompare) {
7734 BoundPrevUB =
7735 SemaRef
7736 .BuildBinOp(
7737 CurScope, CondLoc, BO_Add, BoundPrevUB,
7738 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7739 .get();
7740 BoundPrevUB =
7741 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7742 .get();
7743 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007744 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007745 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7746 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007747 }
7748
Alexander Musmana5f070a2014-10-01 06:03:56 +00007749 // Build updates and final values of the loop counters.
7750 bool HasErrors = false;
7751 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007752 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007753 Built.Updates.resize(NestedLoopCount);
7754 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007755 Built.DependentCounters.resize(NestedLoopCount);
7756 Built.DependentInits.resize(NestedLoopCount);
7757 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007758 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007759 // We implement the following algorithm for obtaining the
7760 // original loop iteration variable values based on the
7761 // value of the collapsed loop iteration variable IV.
7762 //
7763 // Let n+1 be the number of collapsed loops in the nest.
7764 // Iteration variables (I0, I1, .... In)
7765 // Iteration counts (N0, N1, ... Nn)
7766 //
7767 // Acc = IV;
7768 //
7769 // To compute Ik for loop k, 0 <= k <= n, generate:
7770 // Prod = N(k+1) * N(k+2) * ... * Nn;
7771 // Ik = Acc / Prod;
7772 // Acc -= Ik * Prod;
7773 //
7774 ExprResult Acc = IV;
7775 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007776 LoopIterationSpace &IS = IterSpaces[Cnt];
7777 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007778 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007779
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007780 // Compute prod
7781 ExprResult Prod =
7782 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7783 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7784 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7785 IterSpaces[K].NumIterations);
7786
7787 // Iter = Acc / Prod
7788 // If there is at least one more inner loop to avoid
7789 // multiplication by 1.
7790 if (Cnt + 1 < NestedLoopCount)
7791 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7792 Acc.get(), Prod.get());
7793 else
7794 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007795 if (!Iter.isUsable()) {
7796 HasErrors = true;
7797 break;
7798 }
7799
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007800 // Update Acc:
7801 // Acc -= Iter * Prod
7802 // Check if there is at least one more inner loop to avoid
7803 // multiplication by 1.
7804 if (Cnt + 1 < NestedLoopCount)
7805 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7806 Iter.get(), Prod.get());
7807 else
7808 Prod = Iter;
7809 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7810 Acc.get(), Prod.get());
7811
Alexey Bataev39f915b82015-05-08 10:41:21 +00007812 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007813 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007814 DeclRefExpr *CounterVar = buildDeclRefExpr(
7815 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7816 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007817 ExprResult Init =
7818 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7819 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007820 if (!Init.isUsable()) {
7821 HasErrors = true;
7822 break;
7823 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007824 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007825 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007826 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007827 if (!Update.isUsable()) {
7828 HasErrors = true;
7829 break;
7830 }
7831
7832 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007833 ExprResult Final =
7834 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7835 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7836 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007837 if (!Final.isUsable()) {
7838 HasErrors = true;
7839 break;
7840 }
7841
Alexander Musmana5f070a2014-10-01 06:03:56 +00007842 if (!Update.isUsable() || !Final.isUsable()) {
7843 HasErrors = true;
7844 break;
7845 }
7846 // Save results
7847 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007848 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007849 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007850 Built.Updates[Cnt] = Update.get();
7851 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007852 Built.DependentCounters[Cnt] = nullptr;
7853 Built.DependentInits[Cnt] = nullptr;
7854 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007855 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007856 Built.DependentCounters[Cnt] =
7857 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7858 Built.DependentInits[Cnt] =
7859 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7860 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7861 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007862 }
7863 }
7864
7865 if (HasErrors)
7866 return 0;
7867
7868 // Save results
7869 Built.IterationVarRef = IV.get();
7870 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007871 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007872 Built.CalcLastIteration = SemaRef
7873 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007874 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007875 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007876 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007877 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007878 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007879 Built.Init = Init.get();
7880 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007881 Built.LB = LB.get();
7882 Built.UB = UB.get();
7883 Built.IL = IL.get();
7884 Built.ST = ST.get();
7885 Built.EUB = EUB.get();
7886 Built.NLB = NextLB.get();
7887 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007888 Built.PrevLB = PrevLB.get();
7889 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007890 Built.DistInc = DistInc.get();
7891 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007892 Built.DistCombinedFields.LB = CombLB.get();
7893 Built.DistCombinedFields.UB = CombUB.get();
7894 Built.DistCombinedFields.EUB = CombEUB.get();
7895 Built.DistCombinedFields.Init = CombInit.get();
7896 Built.DistCombinedFields.Cond = CombCond.get();
7897 Built.DistCombinedFields.NLB = CombNextLB.get();
7898 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007899 Built.DistCombinedFields.DistCond = CombDistCond.get();
7900 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007901
Alexey Bataevabfc0692014-06-25 06:52:00 +00007902 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007903}
7904
Alexey Bataev10e775f2015-07-30 11:36:16 +00007905static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007906 auto CollapseClauses =
7907 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7908 if (CollapseClauses.begin() != CollapseClauses.end())
7909 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007910 return nullptr;
7911}
7912
Alexey Bataev10e775f2015-07-30 11:36:16 +00007913static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007914 auto OrderedClauses =
7915 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7916 if (OrderedClauses.begin() != OrderedClauses.end())
7917 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007918 return nullptr;
7919}
7920
Kelvin Lic5609492016-07-15 04:39:07 +00007921static bool checkSimdlenSafelenSpecified(Sema &S,
7922 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007923 const OMPSafelenClause *Safelen = nullptr;
7924 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007925
Alexey Bataeve3727102018-04-18 15:57:46 +00007926 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007927 if (Clause->getClauseKind() == OMPC_safelen)
7928 Safelen = cast<OMPSafelenClause>(Clause);
7929 else if (Clause->getClauseKind() == OMPC_simdlen)
7930 Simdlen = cast<OMPSimdlenClause>(Clause);
7931 if (Safelen && Simdlen)
7932 break;
7933 }
7934
7935 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007936 const Expr *SimdlenLength = Simdlen->getSimdlen();
7937 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007938 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7939 SimdlenLength->isInstantiationDependent() ||
7940 SimdlenLength->containsUnexpandedParameterPack())
7941 return false;
7942 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7943 SafelenLength->isInstantiationDependent() ||
7944 SafelenLength->containsUnexpandedParameterPack())
7945 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007946 Expr::EvalResult SimdlenResult, SafelenResult;
7947 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7948 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7949 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7950 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007951 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7952 // If both simdlen and safelen clauses are specified, the value of the
7953 // simdlen parameter must be less than or equal to the value of the safelen
7954 // parameter.
7955 if (SimdlenRes > SafelenRes) {
7956 S.Diag(SimdlenLength->getExprLoc(),
7957 diag::err_omp_wrong_simdlen_safelen_values)
7958 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7959 return true;
7960 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007961 }
7962 return false;
7963}
7964
Alexey Bataeve3727102018-04-18 15:57:46 +00007965StmtResult
7966Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7967 SourceLocation StartLoc, SourceLocation EndLoc,
7968 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007969 if (!AStmt)
7970 return StmtError();
7971
7972 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007973 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007974 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7975 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007976 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007977 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7978 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007979 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007980 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007981
Alexander Musmana5f070a2014-10-01 06:03:56 +00007982 assert((CurContext->isDependentContext() || B.builtAll()) &&
7983 "omp simd loop exprs were not built");
7984
Alexander Musman3276a272015-03-21 10:12:56 +00007985 if (!CurContext->isDependentContext()) {
7986 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007987 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007988 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007989 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007990 B.NumIterations, *this, CurScope,
7991 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007992 return StmtError();
7993 }
7994 }
7995
Kelvin Lic5609492016-07-15 04:39:07 +00007996 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007997 return StmtError();
7998
Reid Kleckner87a31802018-03-12 21:43:02 +00007999 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008000 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8001 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008002}
8003
Alexey Bataeve3727102018-04-18 15:57:46 +00008004StmtResult
8005Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8006 SourceLocation StartLoc, SourceLocation EndLoc,
8007 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008008 if (!AStmt)
8009 return StmtError();
8010
8011 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008012 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008013 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8014 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008015 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008016 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8017 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008018 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008019 return StmtError();
8020
Alexander Musmana5f070a2014-10-01 06:03:56 +00008021 assert((CurContext->isDependentContext() || B.builtAll()) &&
8022 "omp for loop exprs were not built");
8023
Alexey Bataev54acd402015-08-04 11:18:19 +00008024 if (!CurContext->isDependentContext()) {
8025 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008026 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008027 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008028 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008029 B.NumIterations, *this, CurScope,
8030 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008031 return StmtError();
8032 }
8033 }
8034
Reid Kleckner87a31802018-03-12 21:43:02 +00008035 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008036 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008037 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008038}
8039
Alexander Musmanf82886e2014-09-18 05:12:34 +00008040StmtResult Sema::ActOnOpenMPForSimdDirective(
8041 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008042 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008043 if (!AStmt)
8044 return StmtError();
8045
8046 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008047 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008048 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8049 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008050 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008051 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008052 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8053 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008054 if (NestedLoopCount == 0)
8055 return StmtError();
8056
Alexander Musmanc6388682014-12-15 07:07:06 +00008057 assert((CurContext->isDependentContext() || B.builtAll()) &&
8058 "omp for simd loop exprs were not built");
8059
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008060 if (!CurContext->isDependentContext()) {
8061 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008062 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008063 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008064 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008065 B.NumIterations, *this, CurScope,
8066 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008067 return StmtError();
8068 }
8069 }
8070
Kelvin Lic5609492016-07-15 04:39:07 +00008071 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008072 return StmtError();
8073
Reid Kleckner87a31802018-03-12 21:43:02 +00008074 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008075 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8076 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008077}
8078
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008079StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8080 Stmt *AStmt,
8081 SourceLocation StartLoc,
8082 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008083 if (!AStmt)
8084 return StmtError();
8085
8086 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008087 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008088 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008089 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008090 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008091 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008092 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008093 return StmtError();
8094 // All associated statements must be '#pragma omp section' except for
8095 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008096 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008097 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8098 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008099 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008100 diag::err_omp_sections_substmt_not_section);
8101 return StmtError();
8102 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008103 cast<OMPSectionDirective>(SectionStmt)
8104 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008105 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008106 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008107 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008108 return StmtError();
8109 }
8110
Reid Kleckner87a31802018-03-12 21:43:02 +00008111 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008112
Alexey Bataev25e5b442015-09-15 12:52:43 +00008113 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8114 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008115}
8116
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008117StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8118 SourceLocation StartLoc,
8119 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008120 if (!AStmt)
8121 return StmtError();
8122
8123 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008124
Reid Kleckner87a31802018-03-12 21:43:02 +00008125 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008126 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008127
Alexey Bataev25e5b442015-09-15 12:52:43 +00008128 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8129 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008130}
8131
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008132StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8133 Stmt *AStmt,
8134 SourceLocation StartLoc,
8135 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008136 if (!AStmt)
8137 return StmtError();
8138
8139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008140
Reid Kleckner87a31802018-03-12 21:43:02 +00008141 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008142
Alexey Bataev3255bf32015-01-19 05:20:46 +00008143 // OpenMP [2.7.3, single Construct, Restrictions]
8144 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008145 const OMPClause *Nowait = nullptr;
8146 const OMPClause *Copyprivate = nullptr;
8147 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008148 if (Clause->getClauseKind() == OMPC_nowait)
8149 Nowait = Clause;
8150 else if (Clause->getClauseKind() == OMPC_copyprivate)
8151 Copyprivate = Clause;
8152 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008153 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008154 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008155 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008156 return StmtError();
8157 }
8158 }
8159
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008160 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8161}
8162
Alexander Musman80c22892014-07-17 08:54:58 +00008163StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8164 SourceLocation StartLoc,
8165 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008166 if (!AStmt)
8167 return StmtError();
8168
8169 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008170
Reid Kleckner87a31802018-03-12 21:43:02 +00008171 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008172
8173 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8174}
8175
Alexey Bataev28c75412015-12-15 08:19:24 +00008176StmtResult Sema::ActOnOpenMPCriticalDirective(
8177 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8178 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008179 if (!AStmt)
8180 return StmtError();
8181
8182 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008183
Alexey Bataev28c75412015-12-15 08:19:24 +00008184 bool ErrorFound = false;
8185 llvm::APSInt Hint;
8186 SourceLocation HintLoc;
8187 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008188 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008189 if (C->getClauseKind() == OMPC_hint) {
8190 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008191 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008192 ErrorFound = true;
8193 }
8194 Expr *E = cast<OMPHintClause>(C)->getHint();
8195 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008196 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008197 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008198 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008199 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008200 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008201 }
8202 }
8203 }
8204 if (ErrorFound)
8205 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008206 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008207 if (Pair.first && DirName.getName() && !DependentHint) {
8208 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8209 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008210 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008211 Diag(HintLoc, diag::note_omp_critical_hint_here)
8212 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008213 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008214 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008215 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008216 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008217 << 1
8218 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8219 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008220 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008221 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008222 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008223 }
8224 }
8225
Reid Kleckner87a31802018-03-12 21:43:02 +00008226 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008227
Alexey Bataev28c75412015-12-15 08:19:24 +00008228 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8229 Clauses, AStmt);
8230 if (!Pair.first && DirName.getName() && !DependentHint)
8231 DSAStack->addCriticalWithHint(Dir, Hint);
8232 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008233}
8234
Alexey Bataev4acb8592014-07-07 13:01:15 +00008235StmtResult Sema::ActOnOpenMPParallelForDirective(
8236 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008237 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008238 if (!AStmt)
8239 return StmtError();
8240
Alexey Bataeve3727102018-04-18 15:57:46 +00008241 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008242 // 1.2.2 OpenMP Language Terminology
8243 // Structured block - An executable statement with a single entry at the
8244 // top and a single exit at the bottom.
8245 // The point of exit cannot be a branch out of the structured block.
8246 // longjmp() and throw() must not violate the entry/exit criteria.
8247 CS->getCapturedDecl()->setNothrow();
8248
Alexander Musmanc6388682014-12-15 07:07:06 +00008249 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008250 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8251 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008252 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008253 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008254 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8255 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008256 if (NestedLoopCount == 0)
8257 return StmtError();
8258
Alexander Musmana5f070a2014-10-01 06:03:56 +00008259 assert((CurContext->isDependentContext() || B.builtAll()) &&
8260 "omp parallel for loop exprs were not built");
8261
Alexey Bataev54acd402015-08-04 11:18:19 +00008262 if (!CurContext->isDependentContext()) {
8263 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008264 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008265 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008266 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008267 B.NumIterations, *this, CurScope,
8268 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008269 return StmtError();
8270 }
8271 }
8272
Reid Kleckner87a31802018-03-12 21:43:02 +00008273 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008274 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008275 NestedLoopCount, Clauses, AStmt, B,
8276 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008277}
8278
Alexander Musmane4e893b2014-09-23 09:33:00 +00008279StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8280 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008281 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008282 if (!AStmt)
8283 return StmtError();
8284
Alexey Bataeve3727102018-04-18 15:57:46 +00008285 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008286 // 1.2.2 OpenMP Language Terminology
8287 // Structured block - An executable statement with a single entry at the
8288 // top and a single exit at the bottom.
8289 // The point of exit cannot be a branch out of the structured block.
8290 // longjmp() and throw() must not violate the entry/exit criteria.
8291 CS->getCapturedDecl()->setNothrow();
8292
Alexander Musmanc6388682014-12-15 07:07:06 +00008293 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008294 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8295 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008296 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008297 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008298 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8299 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008300 if (NestedLoopCount == 0)
8301 return StmtError();
8302
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008303 if (!CurContext->isDependentContext()) {
8304 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008305 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008306 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008307 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008308 B.NumIterations, *this, CurScope,
8309 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008310 return StmtError();
8311 }
8312 }
8313
Kelvin Lic5609492016-07-15 04:39:07 +00008314 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008315 return StmtError();
8316
Reid Kleckner87a31802018-03-12 21:43:02 +00008317 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008318 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008319 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008320}
8321
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008322StmtResult
cchen47d60942019-12-05 13:43:48 -05008323Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8324 Stmt *AStmt, SourceLocation StartLoc,
8325 SourceLocation EndLoc) {
8326 if (!AStmt)
8327 return StmtError();
8328
8329 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8330 auto *CS = cast<CapturedStmt>(AStmt);
8331 // 1.2.2 OpenMP Language Terminology
8332 // Structured block - An executable statement with a single entry at the
8333 // top and a single exit at the bottom.
8334 // The point of exit cannot be a branch out of the structured block.
8335 // longjmp() and throw() must not violate the entry/exit criteria.
8336 CS->getCapturedDecl()->setNothrow();
8337
8338 setFunctionHasBranchProtectedScope();
8339
8340 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8341 AStmt);
8342}
8343
8344StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008345Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8346 Stmt *AStmt, SourceLocation StartLoc,
8347 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008348 if (!AStmt)
8349 return StmtError();
8350
8351 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008352 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008353 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008354 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008355 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008356 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008357 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008358 return StmtError();
8359 // All associated statements must be '#pragma omp section' except for
8360 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008361 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008362 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8363 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008364 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008365 diag::err_omp_parallel_sections_substmt_not_section);
8366 return StmtError();
8367 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008368 cast<OMPSectionDirective>(SectionStmt)
8369 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008370 }
8371 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008372 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008373 diag::err_omp_parallel_sections_not_compound_stmt);
8374 return StmtError();
8375 }
8376
Reid Kleckner87a31802018-03-12 21:43:02 +00008377 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008378
Alexey Bataev25e5b442015-09-15 12:52:43 +00008379 return OMPParallelSectionsDirective::Create(
8380 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008381}
8382
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008383StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8384 Stmt *AStmt, SourceLocation StartLoc,
8385 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008386 if (!AStmt)
8387 return StmtError();
8388
David Majnemer9d168222016-08-05 17:44:54 +00008389 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008390 // 1.2.2 OpenMP Language Terminology
8391 // Structured block - An executable statement with a single entry at the
8392 // top and a single exit at the bottom.
8393 // The point of exit cannot be a branch out of the structured block.
8394 // longjmp() and throw() must not violate the entry/exit criteria.
8395 CS->getCapturedDecl()->setNothrow();
8396
Reid Kleckner87a31802018-03-12 21:43:02 +00008397 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008398
Alexey Bataev25e5b442015-09-15 12:52:43 +00008399 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8400 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008401}
8402
Alexey Bataev68446b72014-07-18 07:47:19 +00008403StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8404 SourceLocation EndLoc) {
8405 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8406}
8407
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008408StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8409 SourceLocation EndLoc) {
8410 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8411}
8412
Alexey Bataev2df347a2014-07-18 10:17:07 +00008413StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8414 SourceLocation EndLoc) {
8415 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8416}
8417
Alexey Bataev169d96a2017-07-18 20:17:46 +00008418StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8419 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008420 SourceLocation StartLoc,
8421 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008422 if (!AStmt)
8423 return StmtError();
8424
8425 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008426
Reid Kleckner87a31802018-03-12 21:43:02 +00008427 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008428
Alexey Bataev169d96a2017-07-18 20:17:46 +00008429 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008430 AStmt,
8431 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008432}
8433
Alexey Bataev6125da92014-07-21 11:26:11 +00008434StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8435 SourceLocation StartLoc,
8436 SourceLocation EndLoc) {
8437 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8438 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8439}
8440
Alexey Bataev346265e2015-09-25 10:37:12 +00008441StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8442 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008443 SourceLocation StartLoc,
8444 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008445 const OMPClause *DependFound = nullptr;
8446 const OMPClause *DependSourceClause = nullptr;
8447 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008448 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008449 const OMPThreadsClause *TC = nullptr;
8450 const OMPSIMDClause *SC = nullptr;
8451 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008452 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8453 DependFound = C;
8454 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8455 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008456 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008457 << getOpenMPDirectiveName(OMPD_ordered)
8458 << getOpenMPClauseName(OMPC_depend) << 2;
8459 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008460 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008461 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008462 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008463 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008464 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008465 << 0;
8466 ErrorFound = true;
8467 }
8468 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8469 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008470 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008471 << 1;
8472 ErrorFound = true;
8473 }
8474 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008475 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008476 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008477 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008478 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008479 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008480 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008481 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008482 if (!ErrorFound && !SC &&
8483 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008484 // OpenMP [2.8.1,simd Construct, Restrictions]
8485 // An ordered construct with the simd clause is the only OpenMP construct
8486 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008487 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8488 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008489 ErrorFound = true;
8490 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008491 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008492 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8493 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008494 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008495 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008496 diag::err_omp_ordered_directive_without_param);
8497 ErrorFound = true;
8498 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008499 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008500 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008501 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8502 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008503 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008504 ErrorFound = true;
8505 }
8506 }
8507 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008508 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008509
8510 if (AStmt) {
8511 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8512
Reid Kleckner87a31802018-03-12 21:43:02 +00008513 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008514 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008515
8516 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008517}
8518
Alexey Bataev1d160b12015-03-13 12:27:31 +00008519namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008520/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008521/// construct.
8522class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008523 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008524 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008525 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008526 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008527 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008528 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008529 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008530 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008531 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008532 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008533 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008534 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008535 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008536 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008537 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008538 /// expression.
8539 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008540 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008541 /// part.
8542 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008543 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008544 NoError
8545 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008546 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008547 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008548 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008549 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008550 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008551 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008552 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008553 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008554 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008555 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8556 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8557 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008558 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008559 /// important for non-associative operations.
8560 bool IsXLHSInRHSPart;
8561 BinaryOperatorKind Op;
8562 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008563 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008564 /// if it is a prefix unary operation.
8565 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008566
8567public:
8568 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008569 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008570 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008571 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008572 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008573 /// expression. If DiagId and NoteId == 0, then only check is performed
8574 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008575 /// \param DiagId Diagnostic which should be emitted if error is found.
8576 /// \param NoteId Diagnostic note for the main error message.
8577 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008578 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008579 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008580 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008581 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008582 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008583 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008584 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8585 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8586 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008587 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008588 /// false otherwise.
8589 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8590
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008591 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008592 /// if it is a prefix unary operation.
8593 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8594
Alexey Bataev1d160b12015-03-13 12:27:31 +00008595private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008596 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8597 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008598};
8599} // namespace
8600
8601bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8602 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8603 ExprAnalysisErrorCode ErrorFound = NoError;
8604 SourceLocation ErrorLoc, NoteLoc;
8605 SourceRange ErrorRange, NoteRange;
8606 // Allowed constructs are:
8607 // x = x binop expr;
8608 // x = expr binop x;
8609 if (AtomicBinOp->getOpcode() == BO_Assign) {
8610 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008611 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008612 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8613 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8614 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8615 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008616 Op = AtomicInnerBinOp->getOpcode();
8617 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008618 Expr *LHS = AtomicInnerBinOp->getLHS();
8619 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008620 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8621 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8622 /*Canonical=*/true);
8623 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8624 /*Canonical=*/true);
8625 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8626 /*Canonical=*/true);
8627 if (XId == LHSId) {
8628 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008629 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008630 } else if (XId == RHSId) {
8631 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008632 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008633 } else {
8634 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8635 ErrorRange = AtomicInnerBinOp->getSourceRange();
8636 NoteLoc = X->getExprLoc();
8637 NoteRange = X->getSourceRange();
8638 ErrorFound = NotAnUpdateExpression;
8639 }
8640 } else {
8641 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8642 ErrorRange = AtomicInnerBinOp->getSourceRange();
8643 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8644 NoteRange = SourceRange(NoteLoc, NoteLoc);
8645 ErrorFound = NotABinaryOperator;
8646 }
8647 } else {
8648 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8649 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8650 ErrorFound = NotABinaryExpression;
8651 }
8652 } else {
8653 ErrorLoc = AtomicBinOp->getExprLoc();
8654 ErrorRange = AtomicBinOp->getSourceRange();
8655 NoteLoc = AtomicBinOp->getOperatorLoc();
8656 NoteRange = SourceRange(NoteLoc, NoteLoc);
8657 ErrorFound = NotAnAssignmentOp;
8658 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008659 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008660 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8661 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8662 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008663 }
8664 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008665 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008666 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008667}
8668
8669bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8670 unsigned NoteId) {
8671 ExprAnalysisErrorCode ErrorFound = NoError;
8672 SourceLocation ErrorLoc, NoteLoc;
8673 SourceRange ErrorRange, NoteRange;
8674 // Allowed constructs are:
8675 // x++;
8676 // x--;
8677 // ++x;
8678 // --x;
8679 // x binop= expr;
8680 // x = x binop expr;
8681 // x = expr binop x;
8682 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8683 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8684 if (AtomicBody->getType()->isScalarType() ||
8685 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008686 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008687 AtomicBody->IgnoreParenImpCasts())) {
8688 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008689 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008690 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008691 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008692 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008693 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008694 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008695 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8696 AtomicBody->IgnoreParenImpCasts())) {
8697 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008698 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008699 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008700 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008701 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008702 // Check for Unary Operation
8703 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008704 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008705 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8706 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008707 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008708 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8709 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008710 } else {
8711 ErrorFound = NotAnUnaryIncDecExpression;
8712 ErrorLoc = AtomicUnaryOp->getExprLoc();
8713 ErrorRange = AtomicUnaryOp->getSourceRange();
8714 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8715 NoteRange = SourceRange(NoteLoc, NoteLoc);
8716 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008717 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008718 ErrorFound = NotABinaryOrUnaryExpression;
8719 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8720 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8721 }
8722 } else {
8723 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008724 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008725 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8726 }
8727 } else {
8728 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008729 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008730 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8731 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008732 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008733 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8734 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8735 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008736 }
8737 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008738 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008739 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008740 // Build an update expression of form 'OpaqueValueExpr(x) binop
8741 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8742 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8743 auto *OVEX = new (SemaRef.getASTContext())
8744 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8745 auto *OVEExpr = new (SemaRef.getASTContext())
8746 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008747 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008748 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8749 IsXLHSInRHSPart ? OVEExpr : OVEX);
8750 if (Update.isInvalid())
8751 return true;
8752 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8753 Sema::AA_Casting);
8754 if (Update.isInvalid())
8755 return true;
8756 UpdateExpr = Update.get();
8757 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008758 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008759}
8760
Alexey Bataev0162e452014-07-22 10:10:35 +00008761StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8762 Stmt *AStmt,
8763 SourceLocation StartLoc,
8764 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008765 if (!AStmt)
8766 return StmtError();
8767
David Majnemer9d168222016-08-05 17:44:54 +00008768 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008769 // 1.2.2 OpenMP Language Terminology
8770 // Structured block - An executable statement with a single entry at the
8771 // top and a single exit at the bottom.
8772 // The point of exit cannot be a branch out of the structured block.
8773 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008774 OpenMPClauseKind AtomicKind = OMPC_unknown;
8775 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008776 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008777 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008778 C->getClauseKind() == OMPC_update ||
8779 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008780 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008781 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008782 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008783 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8784 << getOpenMPClauseName(AtomicKind);
8785 } else {
8786 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008787 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008788 }
8789 }
8790 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008791
Alexey Bataeve3727102018-04-18 15:57:46 +00008792 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008793 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8794 Body = EWC->getSubExpr();
8795
Alexey Bataev62cec442014-11-18 10:14:22 +00008796 Expr *X = nullptr;
8797 Expr *V = nullptr;
8798 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008799 Expr *UE = nullptr;
8800 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008801 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008802 // OpenMP [2.12.6, atomic Construct]
8803 // In the next expressions:
8804 // * x and v (as applicable) are both l-value expressions with scalar type.
8805 // * During the execution of an atomic region, multiple syntactic
8806 // occurrences of x must designate the same storage location.
8807 // * Neither of v and expr (as applicable) may access the storage location
8808 // designated by x.
8809 // * Neither of x and expr (as applicable) may access the storage location
8810 // designated by v.
8811 // * expr is an expression with scalar type.
8812 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8813 // * binop, binop=, ++, and -- are not overloaded operators.
8814 // * The expression x binop expr must be numerically equivalent to x binop
8815 // (expr). This requirement is satisfied if the operators in expr have
8816 // precedence greater than binop, or by using parentheses around expr or
8817 // subexpressions of expr.
8818 // * The expression expr binop x must be numerically equivalent to (expr)
8819 // binop x. This requirement is satisfied if the operators in expr have
8820 // precedence equal to or greater than binop, or by using parentheses around
8821 // expr or subexpressions of expr.
8822 // * For forms that allow multiple occurrences of x, the number of times
8823 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008824 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008825 enum {
8826 NotAnExpression,
8827 NotAnAssignmentOp,
8828 NotAScalarType,
8829 NotAnLValue,
8830 NoError
8831 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008832 SourceLocation ErrorLoc, NoteLoc;
8833 SourceRange ErrorRange, NoteRange;
8834 // If clause is read:
8835 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008836 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8837 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008838 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8839 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8840 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8841 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8842 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8843 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8844 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008845 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008846 ErrorFound = NotAnLValue;
8847 ErrorLoc = AtomicBinOp->getExprLoc();
8848 ErrorRange = AtomicBinOp->getSourceRange();
8849 NoteLoc = NotLValueExpr->getExprLoc();
8850 NoteRange = NotLValueExpr->getSourceRange();
8851 }
8852 } else if (!X->isInstantiationDependent() ||
8853 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008854 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008855 (X->isInstantiationDependent() || X->getType()->isScalarType())
8856 ? V
8857 : X;
8858 ErrorFound = NotAScalarType;
8859 ErrorLoc = AtomicBinOp->getExprLoc();
8860 ErrorRange = AtomicBinOp->getSourceRange();
8861 NoteLoc = NotScalarExpr->getExprLoc();
8862 NoteRange = NotScalarExpr->getSourceRange();
8863 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008864 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008865 ErrorFound = NotAnAssignmentOp;
8866 ErrorLoc = AtomicBody->getExprLoc();
8867 ErrorRange = AtomicBody->getSourceRange();
8868 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8869 : AtomicBody->getExprLoc();
8870 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8871 : AtomicBody->getSourceRange();
8872 }
8873 } else {
8874 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008875 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008876 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008877 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008878 if (ErrorFound != NoError) {
8879 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8880 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008881 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8882 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008883 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008884 }
8885 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008886 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008887 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008888 enum {
8889 NotAnExpression,
8890 NotAnAssignmentOp,
8891 NotAScalarType,
8892 NotAnLValue,
8893 NoError
8894 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008895 SourceLocation ErrorLoc, NoteLoc;
8896 SourceRange ErrorRange, NoteRange;
8897 // If clause is write:
8898 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008899 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8900 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008901 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8902 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008903 X = AtomicBinOp->getLHS();
8904 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008905 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8906 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8907 if (!X->isLValue()) {
8908 ErrorFound = NotAnLValue;
8909 ErrorLoc = AtomicBinOp->getExprLoc();
8910 ErrorRange = AtomicBinOp->getSourceRange();
8911 NoteLoc = X->getExprLoc();
8912 NoteRange = X->getSourceRange();
8913 }
8914 } else if (!X->isInstantiationDependent() ||
8915 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008916 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008917 (X->isInstantiationDependent() || X->getType()->isScalarType())
8918 ? E
8919 : X;
8920 ErrorFound = NotAScalarType;
8921 ErrorLoc = AtomicBinOp->getExprLoc();
8922 ErrorRange = AtomicBinOp->getSourceRange();
8923 NoteLoc = NotScalarExpr->getExprLoc();
8924 NoteRange = NotScalarExpr->getSourceRange();
8925 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008926 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008927 ErrorFound = NotAnAssignmentOp;
8928 ErrorLoc = AtomicBody->getExprLoc();
8929 ErrorRange = AtomicBody->getSourceRange();
8930 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8931 : AtomicBody->getExprLoc();
8932 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8933 : AtomicBody->getSourceRange();
8934 }
8935 } else {
8936 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008937 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008938 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008939 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008940 if (ErrorFound != NoError) {
8941 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8942 << ErrorRange;
8943 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8944 << NoteRange;
8945 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008946 }
8947 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008948 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008949 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008950 // If clause is update:
8951 // x++;
8952 // x--;
8953 // ++x;
8954 // --x;
8955 // x binop= expr;
8956 // x = x binop expr;
8957 // x = expr binop x;
8958 OpenMPAtomicUpdateChecker Checker(*this);
8959 if (Checker.checkStatement(
8960 Body, (AtomicKind == OMPC_update)
8961 ? diag::err_omp_atomic_update_not_expression_statement
8962 : diag::err_omp_atomic_not_expression_statement,
8963 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008964 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008965 if (!CurContext->isDependentContext()) {
8966 E = Checker.getExpr();
8967 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008968 UE = Checker.getUpdateExpr();
8969 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008970 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008971 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008972 enum {
8973 NotAnAssignmentOp,
8974 NotACompoundStatement,
8975 NotTwoSubstatements,
8976 NotASpecificExpression,
8977 NoError
8978 } ErrorFound = NoError;
8979 SourceLocation ErrorLoc, NoteLoc;
8980 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008981 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008982 // If clause is a capture:
8983 // v = x++;
8984 // v = x--;
8985 // v = ++x;
8986 // v = --x;
8987 // v = x binop= expr;
8988 // v = x = x binop expr;
8989 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008990 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008991 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8992 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8993 V = AtomicBinOp->getLHS();
8994 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8995 OpenMPAtomicUpdateChecker Checker(*this);
8996 if (Checker.checkStatement(
8997 Body, diag::err_omp_atomic_capture_not_expression_statement,
8998 diag::note_omp_atomic_update))
8999 return StmtError();
9000 E = Checker.getExpr();
9001 X = Checker.getX();
9002 UE = Checker.getUpdateExpr();
9003 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9004 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009005 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009006 ErrorLoc = AtomicBody->getExprLoc();
9007 ErrorRange = AtomicBody->getSourceRange();
9008 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9009 : AtomicBody->getExprLoc();
9010 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9011 : AtomicBody->getSourceRange();
9012 ErrorFound = NotAnAssignmentOp;
9013 }
9014 if (ErrorFound != NoError) {
9015 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9016 << ErrorRange;
9017 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9018 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009019 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009020 if (CurContext->isDependentContext())
9021 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009022 } else {
9023 // If clause is a capture:
9024 // { v = x; x = expr; }
9025 // { v = x; x++; }
9026 // { v = x; x--; }
9027 // { v = x; ++x; }
9028 // { v = x; --x; }
9029 // { v = x; x binop= expr; }
9030 // { v = x; x = x binop expr; }
9031 // { v = x; x = expr binop x; }
9032 // { x++; v = x; }
9033 // { x--; v = x; }
9034 // { ++x; v = x; }
9035 // { --x; v = x; }
9036 // { x binop= expr; v = x; }
9037 // { x = x binop expr; v = x; }
9038 // { x = expr binop x; v = x; }
9039 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9040 // Check that this is { expr1; expr2; }
9041 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009042 Stmt *First = CS->body_front();
9043 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009044 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9045 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9046 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9047 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9048 // Need to find what subexpression is 'v' and what is 'x'.
9049 OpenMPAtomicUpdateChecker Checker(*this);
9050 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9051 BinaryOperator *BinOp = nullptr;
9052 if (IsUpdateExprFound) {
9053 BinOp = dyn_cast<BinaryOperator>(First);
9054 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9055 }
9056 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9057 // { v = x; x++; }
9058 // { v = x; x--; }
9059 // { v = x; ++x; }
9060 // { v = x; --x; }
9061 // { v = x; x binop= expr; }
9062 // { v = x; x = x binop expr; }
9063 // { v = x; x = expr binop x; }
9064 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009065 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009066 llvm::FoldingSetNodeID XId, PossibleXId;
9067 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9068 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9069 IsUpdateExprFound = XId == PossibleXId;
9070 if (IsUpdateExprFound) {
9071 V = BinOp->getLHS();
9072 X = Checker.getX();
9073 E = Checker.getExpr();
9074 UE = Checker.getUpdateExpr();
9075 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009076 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009077 }
9078 }
9079 if (!IsUpdateExprFound) {
9080 IsUpdateExprFound = !Checker.checkStatement(First);
9081 BinOp = nullptr;
9082 if (IsUpdateExprFound) {
9083 BinOp = dyn_cast<BinaryOperator>(Second);
9084 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9085 }
9086 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9087 // { x++; v = x; }
9088 // { x--; v = x; }
9089 // { ++x; v = x; }
9090 // { --x; v = x; }
9091 // { x binop= expr; v = x; }
9092 // { x = x binop expr; v = x; }
9093 // { x = expr binop x; v = x; }
9094 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009095 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009096 llvm::FoldingSetNodeID XId, PossibleXId;
9097 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9098 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9099 IsUpdateExprFound = XId == PossibleXId;
9100 if (IsUpdateExprFound) {
9101 V = BinOp->getLHS();
9102 X = Checker.getX();
9103 E = Checker.getExpr();
9104 UE = Checker.getUpdateExpr();
9105 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009106 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009107 }
9108 }
9109 }
9110 if (!IsUpdateExprFound) {
9111 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009112 auto *FirstExpr = dyn_cast<Expr>(First);
9113 auto *SecondExpr = dyn_cast<Expr>(Second);
9114 if (!FirstExpr || !SecondExpr ||
9115 !(FirstExpr->isInstantiationDependent() ||
9116 SecondExpr->isInstantiationDependent())) {
9117 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9118 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009119 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009120 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009121 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009122 NoteRange = ErrorRange = FirstBinOp
9123 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009124 : SourceRange(ErrorLoc, ErrorLoc);
9125 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009126 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9127 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9128 ErrorFound = NotAnAssignmentOp;
9129 NoteLoc = ErrorLoc = SecondBinOp
9130 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009131 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009132 NoteRange = ErrorRange =
9133 SecondBinOp ? SecondBinOp->getSourceRange()
9134 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009135 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009136 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009137 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009138 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009139 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9140 llvm::FoldingSetNodeID X1Id, X2Id;
9141 PossibleXRHSInFirst->Profile(X1Id, Context,
9142 /*Canonical=*/true);
9143 PossibleXLHSInSecond->Profile(X2Id, Context,
9144 /*Canonical=*/true);
9145 IsUpdateExprFound = X1Id == X2Id;
9146 if (IsUpdateExprFound) {
9147 V = FirstBinOp->getLHS();
9148 X = SecondBinOp->getLHS();
9149 E = SecondBinOp->getRHS();
9150 UE = nullptr;
9151 IsXLHSInRHSPart = false;
9152 IsPostfixUpdate = true;
9153 } else {
9154 ErrorFound = NotASpecificExpression;
9155 ErrorLoc = FirstBinOp->getExprLoc();
9156 ErrorRange = FirstBinOp->getSourceRange();
9157 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9158 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9159 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009160 }
9161 }
9162 }
9163 }
9164 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009165 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009166 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009167 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009168 ErrorFound = NotTwoSubstatements;
9169 }
9170 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009171 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009172 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009173 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009174 ErrorFound = NotACompoundStatement;
9175 }
9176 if (ErrorFound != NoError) {
9177 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9178 << ErrorRange;
9179 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9180 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009181 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009182 if (CurContext->isDependentContext())
9183 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009184 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009185 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009186
Reid Kleckner87a31802018-03-12 21:43:02 +00009187 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009188
Alexey Bataev62cec442014-11-18 10:14:22 +00009189 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009190 X, V, E, UE, IsXLHSInRHSPart,
9191 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009192}
9193
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009194StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9195 Stmt *AStmt,
9196 SourceLocation StartLoc,
9197 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009198 if (!AStmt)
9199 return StmtError();
9200
Alexey Bataeve3727102018-04-18 15:57:46 +00009201 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009202 // 1.2.2 OpenMP Language Terminology
9203 // Structured block - An executable statement with a single entry at the
9204 // top and a single exit at the bottom.
9205 // The point of exit cannot be a branch out of the structured block.
9206 // longjmp() and throw() must not violate the entry/exit criteria.
9207 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009208 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9209 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9210 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9211 // 1.2.2 OpenMP Language Terminology
9212 // Structured block - An executable statement with a single entry at the
9213 // top and a single exit at the bottom.
9214 // The point of exit cannot be a branch out of the structured block.
9215 // longjmp() and throw() must not violate the entry/exit criteria.
9216 CS->getCapturedDecl()->setNothrow();
9217 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009218
Alexey Bataev13314bf2014-10-09 04:18:56 +00009219 // OpenMP [2.16, Nesting of Regions]
9220 // If specified, a teams construct must be contained within a target
9221 // construct. That target construct must contain no statements or directives
9222 // outside of the teams construct.
9223 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009224 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009225 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009226 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009227 auto I = CS->body_begin();
9228 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009229 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009230 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9231 OMPTeamsFound) {
9232
Alexey Bataev13314bf2014-10-09 04:18:56 +00009233 OMPTeamsFound = false;
9234 break;
9235 }
9236 ++I;
9237 }
9238 assert(I != CS->body_end() && "Not found statement");
9239 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009240 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009241 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009242 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009243 }
9244 if (!OMPTeamsFound) {
9245 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9246 Diag(DSAStack->getInnerTeamsRegionLoc(),
9247 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009248 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009249 << isa<OMPExecutableDirective>(S);
9250 return StmtError();
9251 }
9252 }
9253
Reid Kleckner87a31802018-03-12 21:43:02 +00009254 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009255
9256 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9257}
9258
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009259StmtResult
9260Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9261 Stmt *AStmt, SourceLocation StartLoc,
9262 SourceLocation EndLoc) {
9263 if (!AStmt)
9264 return StmtError();
9265
Alexey Bataeve3727102018-04-18 15:57:46 +00009266 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009267 // 1.2.2 OpenMP Language Terminology
9268 // Structured block - An executable statement with a single entry at the
9269 // top and a single exit at the bottom.
9270 // The point of exit cannot be a branch out of the structured block.
9271 // longjmp() and throw() must not violate the entry/exit criteria.
9272 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009273 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9274 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9275 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9276 // 1.2.2 OpenMP Language Terminology
9277 // Structured block - An executable statement with a single entry at the
9278 // top and a single exit at the bottom.
9279 // The point of exit cannot be a branch out of the structured block.
9280 // longjmp() and throw() must not violate the entry/exit criteria.
9281 CS->getCapturedDecl()->setNothrow();
9282 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009283
Reid Kleckner87a31802018-03-12 21:43:02 +00009284 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009285
9286 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9287 AStmt);
9288}
9289
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009290StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9291 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009292 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009293 if (!AStmt)
9294 return StmtError();
9295
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009297 // 1.2.2 OpenMP Language Terminology
9298 // Structured block - An executable statement with a single entry at the
9299 // top and a single exit at the bottom.
9300 // The point of exit cannot be a branch out of the structured block.
9301 // longjmp() and throw() must not violate the entry/exit criteria.
9302 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009303 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9304 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9305 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9306 // 1.2.2 OpenMP Language Terminology
9307 // Structured block - An executable statement with a single entry at the
9308 // top and a single exit at the bottom.
9309 // The point of exit cannot be a branch out of the structured block.
9310 // longjmp() and throw() must not violate the entry/exit criteria.
9311 CS->getCapturedDecl()->setNothrow();
9312 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009313
9314 OMPLoopDirective::HelperExprs B;
9315 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9316 // define the nested loops number.
9317 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009318 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009319 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009320 VarsWithImplicitDSA, B);
9321 if (NestedLoopCount == 0)
9322 return StmtError();
9323
9324 assert((CurContext->isDependentContext() || B.builtAll()) &&
9325 "omp target parallel for loop exprs were not built");
9326
9327 if (!CurContext->isDependentContext()) {
9328 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009329 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009330 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009331 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009332 B.NumIterations, *this, CurScope,
9333 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009334 return StmtError();
9335 }
9336 }
9337
Reid Kleckner87a31802018-03-12 21:43:02 +00009338 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009339 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9340 NestedLoopCount, Clauses, AStmt,
9341 B, DSAStack->isCancelRegion());
9342}
9343
Alexey Bataev95b64a92017-05-30 16:00:04 +00009344/// Check for existence of a map clause in the list of clauses.
9345static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9346 const OpenMPClauseKind K) {
9347 return llvm::any_of(
9348 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9349}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009350
Alexey Bataev95b64a92017-05-30 16:00:04 +00009351template <typename... Params>
9352static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9353 const Params... ClauseTypes) {
9354 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009355}
9356
Michael Wong65f367f2015-07-21 13:44:28 +00009357StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9358 Stmt *AStmt,
9359 SourceLocation StartLoc,
9360 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009361 if (!AStmt)
9362 return StmtError();
9363
9364 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9365
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009366 // OpenMP [2.10.1, Restrictions, p. 97]
9367 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009368 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9369 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9370 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009371 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009372 return StmtError();
9373 }
9374
Reid Kleckner87a31802018-03-12 21:43:02 +00009375 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009376
9377 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9378 AStmt);
9379}
9380
Samuel Antaodf67fc42016-01-19 19:15:56 +00009381StmtResult
9382Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9383 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009384 SourceLocation EndLoc, Stmt *AStmt) {
9385 if (!AStmt)
9386 return StmtError();
9387
Alexey Bataeve3727102018-04-18 15:57:46 +00009388 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009389 // 1.2.2 OpenMP Language Terminology
9390 // Structured block - An executable statement with a single entry at the
9391 // top and a single exit at the bottom.
9392 // The point of exit cannot be a branch out of the structured block.
9393 // longjmp() and throw() must not violate the entry/exit criteria.
9394 CS->getCapturedDecl()->setNothrow();
9395 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9396 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9397 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9398 // 1.2.2 OpenMP Language Terminology
9399 // Structured block - An executable statement with a single entry at the
9400 // top and a single exit at the bottom.
9401 // The point of exit cannot be a branch out of the structured block.
9402 // longjmp() and throw() must not violate the entry/exit criteria.
9403 CS->getCapturedDecl()->setNothrow();
9404 }
9405
Samuel Antaodf67fc42016-01-19 19:15:56 +00009406 // OpenMP [2.10.2, Restrictions, p. 99]
9407 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009408 if (!hasClauses(Clauses, OMPC_map)) {
9409 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9410 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009411 return StmtError();
9412 }
9413
Alexey Bataev7828b252017-11-21 17:08:48 +00009414 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9415 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009416}
9417
Samuel Antao72590762016-01-19 20:04:50 +00009418StmtResult
9419Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9420 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009421 SourceLocation EndLoc, Stmt *AStmt) {
9422 if (!AStmt)
9423 return StmtError();
9424
Alexey Bataeve3727102018-04-18 15:57:46 +00009425 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009426 // 1.2.2 OpenMP Language Terminology
9427 // Structured block - An executable statement with a single entry at the
9428 // top and a single exit at the bottom.
9429 // The point of exit cannot be a branch out of the structured block.
9430 // longjmp() and throw() must not violate the entry/exit criteria.
9431 CS->getCapturedDecl()->setNothrow();
9432 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9433 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9434 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9435 // 1.2.2 OpenMP Language Terminology
9436 // Structured block - An executable statement with a single entry at the
9437 // top and a single exit at the bottom.
9438 // The point of exit cannot be a branch out of the structured block.
9439 // longjmp() and throw() must not violate the entry/exit criteria.
9440 CS->getCapturedDecl()->setNothrow();
9441 }
9442
Samuel Antao72590762016-01-19 20:04:50 +00009443 // OpenMP [2.10.3, Restrictions, p. 102]
9444 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009445 if (!hasClauses(Clauses, OMPC_map)) {
9446 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9447 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009448 return StmtError();
9449 }
9450
Alexey Bataev7828b252017-11-21 17:08:48 +00009451 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9452 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009453}
9454
Samuel Antao686c70c2016-05-26 17:30:50 +00009455StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9456 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009457 SourceLocation EndLoc,
9458 Stmt *AStmt) {
9459 if (!AStmt)
9460 return StmtError();
9461
Alexey Bataeve3727102018-04-18 15:57:46 +00009462 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009463 // 1.2.2 OpenMP Language Terminology
9464 // Structured block - An executable statement with a single entry at the
9465 // top and a single exit at the bottom.
9466 // The point of exit cannot be a branch out of the structured block.
9467 // longjmp() and throw() must not violate the entry/exit criteria.
9468 CS->getCapturedDecl()->setNothrow();
9469 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9470 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9471 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9472 // 1.2.2 OpenMP Language Terminology
9473 // Structured block - An executable statement with a single entry at the
9474 // top and a single exit at the bottom.
9475 // The point of exit cannot be a branch out of the structured block.
9476 // longjmp() and throw() must not violate the entry/exit criteria.
9477 CS->getCapturedDecl()->setNothrow();
9478 }
9479
Alexey Bataev95b64a92017-05-30 16:00:04 +00009480 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009481 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9482 return StmtError();
9483 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009484 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9485 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009486}
9487
Alexey Bataev13314bf2014-10-09 04:18:56 +00009488StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9489 Stmt *AStmt, SourceLocation StartLoc,
9490 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009491 if (!AStmt)
9492 return StmtError();
9493
Alexey Bataeve3727102018-04-18 15:57:46 +00009494 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009495 // 1.2.2 OpenMP Language Terminology
9496 // Structured block - An executable statement with a single entry at the
9497 // top and a single exit at the bottom.
9498 // The point of exit cannot be a branch out of the structured block.
9499 // longjmp() and throw() must not violate the entry/exit criteria.
9500 CS->getCapturedDecl()->setNothrow();
9501
Reid Kleckner87a31802018-03-12 21:43:02 +00009502 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009503
Alexey Bataevceabd412017-11-30 18:01:54 +00009504 DSAStack->setParentTeamsRegionLoc(StartLoc);
9505
Alexey Bataev13314bf2014-10-09 04:18:56 +00009506 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9507}
9508
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009509StmtResult
9510Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9511 SourceLocation EndLoc,
9512 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009513 if (DSAStack->isParentNowaitRegion()) {
9514 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9515 return StmtError();
9516 }
9517 if (DSAStack->isParentOrderedRegion()) {
9518 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9519 return StmtError();
9520 }
9521 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9522 CancelRegion);
9523}
9524
Alexey Bataev87933c72015-09-18 08:07:34 +00009525StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9526 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009527 SourceLocation EndLoc,
9528 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009529 if (DSAStack->isParentNowaitRegion()) {
9530 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9531 return StmtError();
9532 }
9533 if (DSAStack->isParentOrderedRegion()) {
9534 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9535 return StmtError();
9536 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009537 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009538 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9539 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009540}
9541
Alexey Bataev382967a2015-12-08 12:06:20 +00009542static bool checkGrainsizeNumTasksClauses(Sema &S,
9543 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009544 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009545 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009546 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009547 if (C->getClauseKind() == OMPC_grainsize ||
9548 C->getClauseKind() == OMPC_num_tasks) {
9549 if (!PrevClause)
9550 PrevClause = C;
9551 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009552 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009553 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9554 << getOpenMPClauseName(C->getClauseKind())
9555 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009556 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009557 diag::note_omp_previous_grainsize_num_tasks)
9558 << getOpenMPClauseName(PrevClause->getClauseKind());
9559 ErrorFound = true;
9560 }
9561 }
9562 }
9563 return ErrorFound;
9564}
9565
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009566static bool checkReductionClauseWithNogroup(Sema &S,
9567 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009568 const OMPClause *ReductionClause = nullptr;
9569 const OMPClause *NogroupClause = nullptr;
9570 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009571 if (C->getClauseKind() == OMPC_reduction) {
9572 ReductionClause = C;
9573 if (NogroupClause)
9574 break;
9575 continue;
9576 }
9577 if (C->getClauseKind() == OMPC_nogroup) {
9578 NogroupClause = C;
9579 if (ReductionClause)
9580 break;
9581 continue;
9582 }
9583 }
9584 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009585 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9586 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009587 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009588 return true;
9589 }
9590 return false;
9591}
9592
Alexey Bataev49f6e782015-12-01 04:18:41 +00009593StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9594 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009595 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009596 if (!AStmt)
9597 return StmtError();
9598
9599 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9600 OMPLoopDirective::HelperExprs B;
9601 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9602 // define the nested loops number.
9603 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009604 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009605 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009606 VarsWithImplicitDSA, B);
9607 if (NestedLoopCount == 0)
9608 return StmtError();
9609
9610 assert((CurContext->isDependentContext() || B.builtAll()) &&
9611 "omp for loop exprs were not built");
9612
Alexey Bataev382967a2015-12-08 12:06:20 +00009613 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9614 // The grainsize clause and num_tasks clause are mutually exclusive and may
9615 // not appear on the same taskloop directive.
9616 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9617 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009618 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9619 // If a reduction clause is present on the taskloop directive, the nogroup
9620 // clause must not be specified.
9621 if (checkReductionClauseWithNogroup(*this, Clauses))
9622 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009623
Reid Kleckner87a31802018-03-12 21:43:02 +00009624 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009625 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9626 NestedLoopCount, Clauses, AStmt, B);
9627}
9628
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009629StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9630 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009631 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009632 if (!AStmt)
9633 return StmtError();
9634
9635 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9636 OMPLoopDirective::HelperExprs B;
9637 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9638 // define the nested loops number.
9639 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009640 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009641 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9642 VarsWithImplicitDSA, B);
9643 if (NestedLoopCount == 0)
9644 return StmtError();
9645
9646 assert((CurContext->isDependentContext() || B.builtAll()) &&
9647 "omp for loop exprs were not built");
9648
Alexey Bataev5a3af132016-03-29 08:58:54 +00009649 if (!CurContext->isDependentContext()) {
9650 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009651 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009652 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009653 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009654 B.NumIterations, *this, CurScope,
9655 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009656 return StmtError();
9657 }
9658 }
9659
Alexey Bataev382967a2015-12-08 12:06:20 +00009660 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9661 // The grainsize clause and num_tasks clause are mutually exclusive and may
9662 // not appear on the same taskloop directive.
9663 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9664 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009665 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9666 // If a reduction clause is present on the taskloop directive, the nogroup
9667 // clause must not be specified.
9668 if (checkReductionClauseWithNogroup(*this, Clauses))
9669 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009670 if (checkSimdlenSafelenSpecified(*this, Clauses))
9671 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009672
Reid Kleckner87a31802018-03-12 21:43:02 +00009673 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009674 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9675 NestedLoopCount, Clauses, AStmt, B);
9676}
9677
Alexey Bataev60e51c42019-10-10 20:13:02 +00009678StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9679 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9680 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9681 if (!AStmt)
9682 return StmtError();
9683
9684 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9685 OMPLoopDirective::HelperExprs B;
9686 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9687 // define the nested loops number.
9688 unsigned NestedLoopCount =
9689 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9690 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9691 VarsWithImplicitDSA, B);
9692 if (NestedLoopCount == 0)
9693 return StmtError();
9694
9695 assert((CurContext->isDependentContext() || B.builtAll()) &&
9696 "omp for loop exprs were not built");
9697
9698 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9699 // The grainsize clause and num_tasks clause are mutually exclusive and may
9700 // not appear on the same taskloop directive.
9701 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9702 return StmtError();
9703 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9704 // If a reduction clause is present on the taskloop directive, the nogroup
9705 // clause must not be specified.
9706 if (checkReductionClauseWithNogroup(*this, Clauses))
9707 return StmtError();
9708
9709 setFunctionHasBranchProtectedScope();
9710 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9711 NestedLoopCount, Clauses, AStmt, B);
9712}
9713
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009714StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9715 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9716 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9717 if (!AStmt)
9718 return StmtError();
9719
9720 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9721 OMPLoopDirective::HelperExprs B;
9722 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9723 // define the nested loops number.
9724 unsigned NestedLoopCount =
9725 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9726 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9727 VarsWithImplicitDSA, B);
9728 if (NestedLoopCount == 0)
9729 return StmtError();
9730
9731 assert((CurContext->isDependentContext() || B.builtAll()) &&
9732 "omp for loop exprs were not built");
9733
9734 if (!CurContext->isDependentContext()) {
9735 // Finalize the clauses that need pre-built expressions for CodeGen.
9736 for (OMPClause *C : Clauses) {
9737 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9738 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9739 B.NumIterations, *this, CurScope,
9740 DSAStack))
9741 return StmtError();
9742 }
9743 }
9744
9745 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9746 // The grainsize clause and num_tasks clause are mutually exclusive and may
9747 // not appear on the same taskloop directive.
9748 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9749 return StmtError();
9750 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9751 // If a reduction clause is present on the taskloop directive, the nogroup
9752 // clause must not be specified.
9753 if (checkReductionClauseWithNogroup(*this, Clauses))
9754 return StmtError();
9755 if (checkSimdlenSafelenSpecified(*this, Clauses))
9756 return StmtError();
9757
9758 setFunctionHasBranchProtectedScope();
9759 return OMPMasterTaskLoopSimdDirective::Create(
9760 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9761}
9762
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009763StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9764 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9765 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9766 if (!AStmt)
9767 return StmtError();
9768
9769 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9770 auto *CS = cast<CapturedStmt>(AStmt);
9771 // 1.2.2 OpenMP Language Terminology
9772 // Structured block - An executable statement with a single entry at the
9773 // top and a single exit at the bottom.
9774 // The point of exit cannot be a branch out of the structured block.
9775 // longjmp() and throw() must not violate the entry/exit criteria.
9776 CS->getCapturedDecl()->setNothrow();
9777 for (int ThisCaptureLevel =
9778 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9779 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9780 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9781 // 1.2.2 OpenMP Language Terminology
9782 // Structured block - An executable statement with a single entry at the
9783 // top and a single exit at the bottom.
9784 // The point of exit cannot be a branch out of the structured block.
9785 // longjmp() and throw() must not violate the entry/exit criteria.
9786 CS->getCapturedDecl()->setNothrow();
9787 }
9788
9789 OMPLoopDirective::HelperExprs B;
9790 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9791 // define the nested loops number.
9792 unsigned NestedLoopCount = checkOpenMPLoop(
9793 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9794 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9795 VarsWithImplicitDSA, B);
9796 if (NestedLoopCount == 0)
9797 return StmtError();
9798
9799 assert((CurContext->isDependentContext() || B.builtAll()) &&
9800 "omp for loop exprs were not built");
9801
9802 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9803 // The grainsize clause and num_tasks clause are mutually exclusive and may
9804 // not appear on the same taskloop directive.
9805 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9806 return StmtError();
9807 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9808 // If a reduction clause is present on the taskloop directive, the nogroup
9809 // clause must not be specified.
9810 if (checkReductionClauseWithNogroup(*this, Clauses))
9811 return StmtError();
9812
9813 setFunctionHasBranchProtectedScope();
9814 return OMPParallelMasterTaskLoopDirective::Create(
9815 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9816}
9817
Alexey Bataev14a388f2019-10-25 10:27:13 -04009818StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9820 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9821 if (!AStmt)
9822 return StmtError();
9823
9824 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9825 auto *CS = cast<CapturedStmt>(AStmt);
9826 // 1.2.2 OpenMP Language Terminology
9827 // Structured block - An executable statement with a single entry at the
9828 // top and a single exit at the bottom.
9829 // The point of exit cannot be a branch out of the structured block.
9830 // longjmp() and throw() must not violate the entry/exit criteria.
9831 CS->getCapturedDecl()->setNothrow();
9832 for (int ThisCaptureLevel =
9833 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9834 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9835 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9836 // 1.2.2 OpenMP Language Terminology
9837 // Structured block - An executable statement with a single entry at the
9838 // top and a single exit at the bottom.
9839 // The point of exit cannot be a branch out of the structured block.
9840 // longjmp() and throw() must not violate the entry/exit criteria.
9841 CS->getCapturedDecl()->setNothrow();
9842 }
9843
9844 OMPLoopDirective::HelperExprs B;
9845 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9846 // define the nested loops number.
9847 unsigned NestedLoopCount = checkOpenMPLoop(
9848 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9849 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9850 VarsWithImplicitDSA, B);
9851 if (NestedLoopCount == 0)
9852 return StmtError();
9853
9854 assert((CurContext->isDependentContext() || B.builtAll()) &&
9855 "omp for loop exprs were not built");
9856
9857 if (!CurContext->isDependentContext()) {
9858 // Finalize the clauses that need pre-built expressions for CodeGen.
9859 for (OMPClause *C : Clauses) {
9860 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9861 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9862 B.NumIterations, *this, CurScope,
9863 DSAStack))
9864 return StmtError();
9865 }
9866 }
9867
9868 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9869 // The grainsize clause and num_tasks clause are mutually exclusive and may
9870 // not appear on the same taskloop directive.
9871 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9872 return StmtError();
9873 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9874 // If a reduction clause is present on the taskloop directive, the nogroup
9875 // clause must not be specified.
9876 if (checkReductionClauseWithNogroup(*this, Clauses))
9877 return StmtError();
9878 if (checkSimdlenSafelenSpecified(*this, Clauses))
9879 return StmtError();
9880
9881 setFunctionHasBranchProtectedScope();
9882 return OMPParallelMasterTaskLoopSimdDirective::Create(
9883 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9884}
9885
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009886StmtResult Sema::ActOnOpenMPDistributeDirective(
9887 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009888 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009889 if (!AStmt)
9890 return StmtError();
9891
9892 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9893 OMPLoopDirective::HelperExprs B;
9894 // In presence of clause 'collapse' with number of loops, it will
9895 // define the nested loops number.
9896 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009897 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009898 nullptr /*ordered not a clause on distribute*/, AStmt,
9899 *this, *DSAStack, VarsWithImplicitDSA, B);
9900 if (NestedLoopCount == 0)
9901 return StmtError();
9902
9903 assert((CurContext->isDependentContext() || B.builtAll()) &&
9904 "omp for loop exprs were not built");
9905
Reid Kleckner87a31802018-03-12 21:43:02 +00009906 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009907 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9908 NestedLoopCount, Clauses, AStmt, B);
9909}
9910
Carlo Bertolli9925f152016-06-27 14:55:37 +00009911StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9912 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009913 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009914 if (!AStmt)
9915 return StmtError();
9916
Alexey Bataeve3727102018-04-18 15:57:46 +00009917 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009918 // 1.2.2 OpenMP Language Terminology
9919 // Structured block - An executable statement with a single entry at the
9920 // top and a single exit at the bottom.
9921 // The point of exit cannot be a branch out of the structured block.
9922 // longjmp() and throw() must not violate the entry/exit criteria.
9923 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009924 for (int ThisCaptureLevel =
9925 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9926 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9927 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9928 // 1.2.2 OpenMP Language Terminology
9929 // Structured block - An executable statement with a single entry at the
9930 // top and a single exit at the bottom.
9931 // The point of exit cannot be a branch out of the structured block.
9932 // longjmp() and throw() must not violate the entry/exit criteria.
9933 CS->getCapturedDecl()->setNothrow();
9934 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009935
9936 OMPLoopDirective::HelperExprs B;
9937 // In presence of clause 'collapse' with number of loops, it will
9938 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009939 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009940 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009941 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009942 VarsWithImplicitDSA, B);
9943 if (NestedLoopCount == 0)
9944 return StmtError();
9945
9946 assert((CurContext->isDependentContext() || B.builtAll()) &&
9947 "omp for loop exprs were not built");
9948
Reid Kleckner87a31802018-03-12 21:43:02 +00009949 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009950 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009951 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9952 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009953}
9954
Kelvin Li4a39add2016-07-05 05:00:15 +00009955StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9956 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009957 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009958 if (!AStmt)
9959 return StmtError();
9960
Alexey Bataeve3727102018-04-18 15:57:46 +00009961 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009962 // 1.2.2 OpenMP Language Terminology
9963 // Structured block - An executable statement with a single entry at the
9964 // top and a single exit at the bottom.
9965 // The point of exit cannot be a branch out of the structured block.
9966 // longjmp() and throw() must not violate the entry/exit criteria.
9967 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009968 for (int ThisCaptureLevel =
9969 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9970 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9971 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9972 // 1.2.2 OpenMP Language Terminology
9973 // Structured block - An executable statement with a single entry at the
9974 // top and a single exit at the bottom.
9975 // The point of exit cannot be a branch out of the structured block.
9976 // longjmp() and throw() must not violate the entry/exit criteria.
9977 CS->getCapturedDecl()->setNothrow();
9978 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009979
9980 OMPLoopDirective::HelperExprs B;
9981 // In presence of clause 'collapse' with number of loops, it will
9982 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009983 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009984 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009985 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009986 VarsWithImplicitDSA, B);
9987 if (NestedLoopCount == 0)
9988 return StmtError();
9989
9990 assert((CurContext->isDependentContext() || B.builtAll()) &&
9991 "omp for loop exprs were not built");
9992
Alexey Bataev438388c2017-11-22 18:34:02 +00009993 if (!CurContext->isDependentContext()) {
9994 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009995 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009996 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9997 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9998 B.NumIterations, *this, CurScope,
9999 DSAStack))
10000 return StmtError();
10001 }
10002 }
10003
Kelvin Lic5609492016-07-15 04:39:07 +000010004 if (checkSimdlenSafelenSpecified(*this, Clauses))
10005 return StmtError();
10006
Reid Kleckner87a31802018-03-12 21:43:02 +000010007 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010008 return OMPDistributeParallelForSimdDirective::Create(
10009 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10010}
10011
Kelvin Li787f3fc2016-07-06 04:45:38 +000010012StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010014 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010015 if (!AStmt)
10016 return StmtError();
10017
Alexey Bataeve3727102018-04-18 15:57:46 +000010018 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010019 // 1.2.2 OpenMP Language Terminology
10020 // Structured block - An executable statement with a single entry at the
10021 // top and a single exit at the bottom.
10022 // The point of exit cannot be a branch out of the structured block.
10023 // longjmp() and throw() must not violate the entry/exit criteria.
10024 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010025 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10026 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10027 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10028 // 1.2.2 OpenMP Language Terminology
10029 // Structured block - An executable statement with a single entry at the
10030 // top and a single exit at the bottom.
10031 // The point of exit cannot be a branch out of the structured block.
10032 // longjmp() and throw() must not violate the entry/exit criteria.
10033 CS->getCapturedDecl()->setNothrow();
10034 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010035
10036 OMPLoopDirective::HelperExprs B;
10037 // In presence of clause 'collapse' with number of loops, it will
10038 // define the nested loops number.
10039 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010040 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010041 nullptr /*ordered not a clause on distribute*/, CS, *this,
10042 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010043 if (NestedLoopCount == 0)
10044 return StmtError();
10045
10046 assert((CurContext->isDependentContext() || B.builtAll()) &&
10047 "omp for loop exprs were not built");
10048
Alexey Bataev438388c2017-11-22 18:34:02 +000010049 if (!CurContext->isDependentContext()) {
10050 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010051 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010052 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10053 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10054 B.NumIterations, *this, CurScope,
10055 DSAStack))
10056 return StmtError();
10057 }
10058 }
10059
Kelvin Lic5609492016-07-15 04:39:07 +000010060 if (checkSimdlenSafelenSpecified(*this, Clauses))
10061 return StmtError();
10062
Reid Kleckner87a31802018-03-12 21:43:02 +000010063 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010064 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10065 NestedLoopCount, Clauses, AStmt, B);
10066}
10067
Kelvin Lia579b912016-07-14 02:54:56 +000010068StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10069 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010070 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010071 if (!AStmt)
10072 return StmtError();
10073
Alexey Bataeve3727102018-04-18 15:57:46 +000010074 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010075 // 1.2.2 OpenMP Language Terminology
10076 // Structured block - An executable statement with a single entry at the
10077 // top and a single exit at the bottom.
10078 // The point of exit cannot be a branch out of the structured block.
10079 // longjmp() and throw() must not violate the entry/exit criteria.
10080 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010081 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10082 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10083 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10084 // 1.2.2 OpenMP Language Terminology
10085 // Structured block - An executable statement with a single entry at the
10086 // top and a single exit at the bottom.
10087 // The point of exit cannot be a branch out of the structured block.
10088 // longjmp() and throw() must not violate the entry/exit criteria.
10089 CS->getCapturedDecl()->setNothrow();
10090 }
Kelvin Lia579b912016-07-14 02:54:56 +000010091
10092 OMPLoopDirective::HelperExprs B;
10093 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10094 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010095 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010096 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010097 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010098 VarsWithImplicitDSA, B);
10099 if (NestedLoopCount == 0)
10100 return StmtError();
10101
10102 assert((CurContext->isDependentContext() || B.builtAll()) &&
10103 "omp target parallel for simd loop exprs were not built");
10104
10105 if (!CurContext->isDependentContext()) {
10106 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010107 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010108 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010109 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10110 B.NumIterations, *this, CurScope,
10111 DSAStack))
10112 return StmtError();
10113 }
10114 }
Kelvin Lic5609492016-07-15 04:39:07 +000010115 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010116 return StmtError();
10117
Reid Kleckner87a31802018-03-12 21:43:02 +000010118 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010119 return OMPTargetParallelForSimdDirective::Create(
10120 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10121}
10122
Kelvin Li986330c2016-07-20 22:57:10 +000010123StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10124 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010125 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010126 if (!AStmt)
10127 return StmtError();
10128
Alexey Bataeve3727102018-04-18 15:57:46 +000010129 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010130 // 1.2.2 OpenMP Language Terminology
10131 // Structured block - An executable statement with a single entry at the
10132 // top and a single exit at the bottom.
10133 // The point of exit cannot be a branch out of the structured block.
10134 // longjmp() and throw() must not violate the entry/exit criteria.
10135 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010136 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10137 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10138 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10139 // 1.2.2 OpenMP Language Terminology
10140 // Structured block - An executable statement with a single entry at the
10141 // top and a single exit at the bottom.
10142 // The point of exit cannot be a branch out of the structured block.
10143 // longjmp() and throw() must not violate the entry/exit criteria.
10144 CS->getCapturedDecl()->setNothrow();
10145 }
10146
Kelvin Li986330c2016-07-20 22:57:10 +000010147 OMPLoopDirective::HelperExprs B;
10148 // In presence of clause 'collapse' with number of loops, it will define the
10149 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010150 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010151 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010152 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010153 VarsWithImplicitDSA, B);
10154 if (NestedLoopCount == 0)
10155 return StmtError();
10156
10157 assert((CurContext->isDependentContext() || B.builtAll()) &&
10158 "omp target simd loop exprs were not built");
10159
10160 if (!CurContext->isDependentContext()) {
10161 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010162 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010163 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010164 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10165 B.NumIterations, *this, CurScope,
10166 DSAStack))
10167 return StmtError();
10168 }
10169 }
10170
10171 if (checkSimdlenSafelenSpecified(*this, Clauses))
10172 return StmtError();
10173
Reid Kleckner87a31802018-03-12 21:43:02 +000010174 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010175 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10176 NestedLoopCount, Clauses, AStmt, B);
10177}
10178
Kelvin Li02532872016-08-05 14:37:37 +000010179StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010181 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010182 if (!AStmt)
10183 return StmtError();
10184
Alexey Bataeve3727102018-04-18 15:57:46 +000010185 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010186 // 1.2.2 OpenMP Language Terminology
10187 // Structured block - An executable statement with a single entry at the
10188 // top and a single exit at the bottom.
10189 // The point of exit cannot be a branch out of the structured block.
10190 // longjmp() and throw() must not violate the entry/exit criteria.
10191 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010192 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10193 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10194 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10195 // 1.2.2 OpenMP Language Terminology
10196 // Structured block - An executable statement with a single entry at the
10197 // top and a single exit at the bottom.
10198 // The point of exit cannot be a branch out of the structured block.
10199 // longjmp() and throw() must not violate the entry/exit criteria.
10200 CS->getCapturedDecl()->setNothrow();
10201 }
Kelvin Li02532872016-08-05 14:37:37 +000010202
10203 OMPLoopDirective::HelperExprs B;
10204 // In presence of clause 'collapse' with number of loops, it will
10205 // define the nested loops number.
10206 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010207 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010208 nullptr /*ordered not a clause on distribute*/, CS, *this,
10209 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010210 if (NestedLoopCount == 0)
10211 return StmtError();
10212
10213 assert((CurContext->isDependentContext() || B.builtAll()) &&
10214 "omp teams distribute loop exprs were not built");
10215
Reid Kleckner87a31802018-03-12 21:43:02 +000010216 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010217
10218 DSAStack->setParentTeamsRegionLoc(StartLoc);
10219
David Majnemer9d168222016-08-05 17:44:54 +000010220 return OMPTeamsDistributeDirective::Create(
10221 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010222}
10223
Kelvin Li4e325f72016-10-25 12:50:55 +000010224StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10225 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010226 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010227 if (!AStmt)
10228 return StmtError();
10229
Alexey Bataeve3727102018-04-18 15:57:46 +000010230 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010231 // 1.2.2 OpenMP Language Terminology
10232 // Structured block - An executable statement with a single entry at the
10233 // top and a single exit at the bottom.
10234 // The point of exit cannot be a branch out of the structured block.
10235 // longjmp() and throw() must not violate the entry/exit criteria.
10236 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010237 for (int ThisCaptureLevel =
10238 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10239 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10240 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10241 // 1.2.2 OpenMP Language Terminology
10242 // Structured block - An executable statement with a single entry at the
10243 // top and a single exit at the bottom.
10244 // The point of exit cannot be a branch out of the structured block.
10245 // longjmp() and throw() must not violate the entry/exit criteria.
10246 CS->getCapturedDecl()->setNothrow();
10247 }
10248
Kelvin Li4e325f72016-10-25 12:50:55 +000010249
10250 OMPLoopDirective::HelperExprs B;
10251 // In presence of clause 'collapse' with number of loops, it will
10252 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010253 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010254 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010255 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010256 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010257
10258 if (NestedLoopCount == 0)
10259 return StmtError();
10260
10261 assert((CurContext->isDependentContext() || B.builtAll()) &&
10262 "omp teams distribute simd loop exprs were not built");
10263
10264 if (!CurContext->isDependentContext()) {
10265 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010266 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010267 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10268 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10269 B.NumIterations, *this, CurScope,
10270 DSAStack))
10271 return StmtError();
10272 }
10273 }
10274
10275 if (checkSimdlenSafelenSpecified(*this, Clauses))
10276 return StmtError();
10277
Reid Kleckner87a31802018-03-12 21:43:02 +000010278 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010279
10280 DSAStack->setParentTeamsRegionLoc(StartLoc);
10281
Kelvin Li4e325f72016-10-25 12:50:55 +000010282 return OMPTeamsDistributeSimdDirective::Create(
10283 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10284}
10285
Kelvin Li579e41c2016-11-30 23:51:03 +000010286StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10287 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010288 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010289 if (!AStmt)
10290 return StmtError();
10291
Alexey Bataeve3727102018-04-18 15:57:46 +000010292 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010293 // 1.2.2 OpenMP Language Terminology
10294 // Structured block - An executable statement with a single entry at the
10295 // top and a single exit at the bottom.
10296 // The point of exit cannot be a branch out of the structured block.
10297 // longjmp() and throw() must not violate the entry/exit criteria.
10298 CS->getCapturedDecl()->setNothrow();
10299
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010300 for (int ThisCaptureLevel =
10301 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10302 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10303 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10304 // 1.2.2 OpenMP Language Terminology
10305 // Structured block - An executable statement with a single entry at the
10306 // top and a single exit at the bottom.
10307 // The point of exit cannot be a branch out of the structured block.
10308 // longjmp() and throw() must not violate the entry/exit criteria.
10309 CS->getCapturedDecl()->setNothrow();
10310 }
10311
Kelvin Li579e41c2016-11-30 23:51:03 +000010312 OMPLoopDirective::HelperExprs B;
10313 // In presence of clause 'collapse' with number of loops, it will
10314 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010315 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010316 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010317 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010318 VarsWithImplicitDSA, B);
10319
10320 if (NestedLoopCount == 0)
10321 return StmtError();
10322
10323 assert((CurContext->isDependentContext() || B.builtAll()) &&
10324 "omp for loop exprs were not built");
10325
10326 if (!CurContext->isDependentContext()) {
10327 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010328 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010329 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10331 B.NumIterations, *this, CurScope,
10332 DSAStack))
10333 return StmtError();
10334 }
10335 }
10336
10337 if (checkSimdlenSafelenSpecified(*this, Clauses))
10338 return StmtError();
10339
Reid Kleckner87a31802018-03-12 21:43:02 +000010340 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010341
10342 DSAStack->setParentTeamsRegionLoc(StartLoc);
10343
Kelvin Li579e41c2016-11-30 23:51:03 +000010344 return OMPTeamsDistributeParallelForSimdDirective::Create(
10345 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10346}
10347
Kelvin Li7ade93f2016-12-09 03:24:30 +000010348StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10349 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010350 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010351 if (!AStmt)
10352 return StmtError();
10353
Alexey Bataeve3727102018-04-18 15:57:46 +000010354 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010355 // 1.2.2 OpenMP Language Terminology
10356 // Structured block - An executable statement with a single entry at the
10357 // top and a single exit at the bottom.
10358 // The point of exit cannot be a branch out of the structured block.
10359 // longjmp() and throw() must not violate the entry/exit criteria.
10360 CS->getCapturedDecl()->setNothrow();
10361
Carlo Bertolli62fae152017-11-20 20:46:39 +000010362 for (int ThisCaptureLevel =
10363 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10364 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10365 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10366 // 1.2.2 OpenMP Language Terminology
10367 // Structured block - An executable statement with a single entry at the
10368 // top and a single exit at the bottom.
10369 // The point of exit cannot be a branch out of the structured block.
10370 // longjmp() and throw() must not violate the entry/exit criteria.
10371 CS->getCapturedDecl()->setNothrow();
10372 }
10373
Kelvin Li7ade93f2016-12-09 03:24:30 +000010374 OMPLoopDirective::HelperExprs B;
10375 // In presence of clause 'collapse' with number of loops, it will
10376 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010377 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010378 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010379 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010380 VarsWithImplicitDSA, B);
10381
10382 if (NestedLoopCount == 0)
10383 return StmtError();
10384
10385 assert((CurContext->isDependentContext() || B.builtAll()) &&
10386 "omp for loop exprs were not built");
10387
Reid Kleckner87a31802018-03-12 21:43:02 +000010388 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010389
10390 DSAStack->setParentTeamsRegionLoc(StartLoc);
10391
Kelvin Li7ade93f2016-12-09 03:24:30 +000010392 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010393 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10394 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010395}
10396
Kelvin Libf594a52016-12-17 05:48:59 +000010397StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10398 Stmt *AStmt,
10399 SourceLocation StartLoc,
10400 SourceLocation EndLoc) {
10401 if (!AStmt)
10402 return StmtError();
10403
Alexey Bataeve3727102018-04-18 15:57:46 +000010404 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010405 // 1.2.2 OpenMP Language Terminology
10406 // Structured block - An executable statement with a single entry at the
10407 // top and a single exit at the bottom.
10408 // The point of exit cannot be a branch out of the structured block.
10409 // longjmp() and throw() must not violate the entry/exit criteria.
10410 CS->getCapturedDecl()->setNothrow();
10411
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010412 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10413 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10414 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10415 // 1.2.2 OpenMP Language Terminology
10416 // Structured block - An executable statement with a single entry at the
10417 // top and a single exit at the bottom.
10418 // The point of exit cannot be a branch out of the structured block.
10419 // longjmp() and throw() must not violate the entry/exit criteria.
10420 CS->getCapturedDecl()->setNothrow();
10421 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010422 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010423
10424 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10425 AStmt);
10426}
10427
Kelvin Li83c451e2016-12-25 04:52:54 +000010428StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10429 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010430 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010431 if (!AStmt)
10432 return StmtError();
10433
Alexey Bataeve3727102018-04-18 15:57:46 +000010434 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010435 // 1.2.2 OpenMP Language Terminology
10436 // Structured block - An executable statement with a single entry at the
10437 // top and a single exit at the bottom.
10438 // The point of exit cannot be a branch out of the structured block.
10439 // longjmp() and throw() must not violate the entry/exit criteria.
10440 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010441 for (int ThisCaptureLevel =
10442 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10443 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10444 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10445 // 1.2.2 OpenMP Language Terminology
10446 // Structured block - An executable statement with a single entry at the
10447 // top and a single exit at the bottom.
10448 // The point of exit cannot be a branch out of the structured block.
10449 // longjmp() and throw() must not violate the entry/exit criteria.
10450 CS->getCapturedDecl()->setNothrow();
10451 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010452
10453 OMPLoopDirective::HelperExprs B;
10454 // In presence of clause 'collapse' with number of loops, it will
10455 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010456 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010457 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10458 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010459 VarsWithImplicitDSA, B);
10460 if (NestedLoopCount == 0)
10461 return StmtError();
10462
10463 assert((CurContext->isDependentContext() || B.builtAll()) &&
10464 "omp target teams distribute loop exprs were not built");
10465
Reid Kleckner87a31802018-03-12 21:43:02 +000010466 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010467 return OMPTargetTeamsDistributeDirective::Create(
10468 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10469}
10470
Kelvin Li80e8f562016-12-29 22:16:30 +000010471StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10472 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010473 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010474 if (!AStmt)
10475 return StmtError();
10476
Alexey Bataeve3727102018-04-18 15:57:46 +000010477 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010478 // 1.2.2 OpenMP Language Terminology
10479 // Structured block - An executable statement with a single entry at the
10480 // top and a single exit at the bottom.
10481 // The point of exit cannot be a branch out of the structured block.
10482 // longjmp() and throw() must not violate the entry/exit criteria.
10483 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010484 for (int ThisCaptureLevel =
10485 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10486 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10487 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10488 // 1.2.2 OpenMP Language Terminology
10489 // Structured block - An executable statement with a single entry at the
10490 // top and a single exit at the bottom.
10491 // The point of exit cannot be a branch out of the structured block.
10492 // longjmp() and throw() must not violate the entry/exit criteria.
10493 CS->getCapturedDecl()->setNothrow();
10494 }
10495
Kelvin Li80e8f562016-12-29 22:16:30 +000010496 OMPLoopDirective::HelperExprs B;
10497 // In presence of clause 'collapse' with number of loops, it will
10498 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010499 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010500 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10501 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010502 VarsWithImplicitDSA, B);
10503 if (NestedLoopCount == 0)
10504 return StmtError();
10505
10506 assert((CurContext->isDependentContext() || B.builtAll()) &&
10507 "omp target teams distribute parallel for loop exprs were not built");
10508
Alexey Bataev647dd842018-01-15 20:59:40 +000010509 if (!CurContext->isDependentContext()) {
10510 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010511 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010512 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10513 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10514 B.NumIterations, *this, CurScope,
10515 DSAStack))
10516 return StmtError();
10517 }
10518 }
10519
Reid Kleckner87a31802018-03-12 21:43:02 +000010520 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010521 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010522 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10523 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010524}
10525
Kelvin Li1851df52017-01-03 05:23:48 +000010526StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10527 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010528 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010529 if (!AStmt)
10530 return StmtError();
10531
Alexey Bataeve3727102018-04-18 15:57:46 +000010532 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010533 // 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();
Alexey Bataev647dd842018-01-15 20:59:40 +000010539 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10540 OMPD_target_teams_distribute_parallel_for_simd);
10541 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10542 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10543 // 1.2.2 OpenMP Language Terminology
10544 // Structured block - An executable statement with a single entry at the
10545 // top and a single exit at the bottom.
10546 // The point of exit cannot be a branch out of the structured block.
10547 // longjmp() and throw() must not violate the entry/exit criteria.
10548 CS->getCapturedDecl()->setNothrow();
10549 }
Kelvin Li1851df52017-01-03 05:23:48 +000010550
10551 OMPLoopDirective::HelperExprs B;
10552 // In presence of clause 'collapse' with number of loops, it will
10553 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010554 unsigned NestedLoopCount =
10555 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010556 getCollapseNumberExpr(Clauses),
10557 nullptr /*ordered not a clause on distribute*/, CS, *this,
10558 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010559 if (NestedLoopCount == 0)
10560 return StmtError();
10561
10562 assert((CurContext->isDependentContext() || B.builtAll()) &&
10563 "omp target teams distribute parallel for simd loop exprs were not "
10564 "built");
10565
10566 if (!CurContext->isDependentContext()) {
10567 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010568 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010569 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10570 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10571 B.NumIterations, *this, CurScope,
10572 DSAStack))
10573 return StmtError();
10574 }
10575 }
10576
Alexey Bataev438388c2017-11-22 18:34:02 +000010577 if (checkSimdlenSafelenSpecified(*this, Clauses))
10578 return StmtError();
10579
Reid Kleckner87a31802018-03-12 21:43:02 +000010580 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010581 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10582 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10583}
10584
Kelvin Lida681182017-01-10 18:08:18 +000010585StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10586 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010587 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010588 if (!AStmt)
10589 return StmtError();
10590
10591 auto *CS = cast<CapturedStmt>(AStmt);
10592 // 1.2.2 OpenMP Language Terminology
10593 // Structured block - An executable statement with a single entry at the
10594 // top and a single exit at the bottom.
10595 // The point of exit cannot be a branch out of the structured block.
10596 // longjmp() and throw() must not violate the entry/exit criteria.
10597 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010598 for (int ThisCaptureLevel =
10599 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10600 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10601 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10602 // 1.2.2 OpenMP Language Terminology
10603 // Structured block - An executable statement with a single entry at the
10604 // top and a single exit at the bottom.
10605 // The point of exit cannot be a branch out of the structured block.
10606 // longjmp() and throw() must not violate the entry/exit criteria.
10607 CS->getCapturedDecl()->setNothrow();
10608 }
Kelvin Lida681182017-01-10 18:08:18 +000010609
10610 OMPLoopDirective::HelperExprs B;
10611 // In presence of clause 'collapse' with number of loops, it will
10612 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010613 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010614 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010615 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010616 VarsWithImplicitDSA, B);
10617 if (NestedLoopCount == 0)
10618 return StmtError();
10619
10620 assert((CurContext->isDependentContext() || B.builtAll()) &&
10621 "omp target teams distribute simd loop exprs were not built");
10622
Alexey Bataev438388c2017-11-22 18:34:02 +000010623 if (!CurContext->isDependentContext()) {
10624 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010625 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010626 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10627 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10628 B.NumIterations, *this, CurScope,
10629 DSAStack))
10630 return StmtError();
10631 }
10632 }
10633
10634 if (checkSimdlenSafelenSpecified(*this, Clauses))
10635 return StmtError();
10636
Reid Kleckner87a31802018-03-12 21:43:02 +000010637 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010638 return OMPTargetTeamsDistributeSimdDirective::Create(
10639 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10640}
10641
Alexey Bataeved09d242014-05-28 05:53:51 +000010642OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010643 SourceLocation StartLoc,
10644 SourceLocation LParenLoc,
10645 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010646 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010647 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010648 case OMPC_final:
10649 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10650 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010651 case OMPC_num_threads:
10652 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10653 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010654 case OMPC_safelen:
10655 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10656 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010657 case OMPC_simdlen:
10658 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10659 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010660 case OMPC_allocator:
10661 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10662 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010663 case OMPC_collapse:
10664 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10665 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010666 case OMPC_ordered:
10667 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10668 break;
Michael Wonge710d542015-08-07 16:16:36 +000010669 case OMPC_device:
10670 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10671 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010672 case OMPC_num_teams:
10673 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10674 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010675 case OMPC_thread_limit:
10676 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10677 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010678 case OMPC_priority:
10679 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10680 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010681 case OMPC_grainsize:
10682 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10683 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010684 case OMPC_num_tasks:
10685 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10686 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010687 case OMPC_hint:
10688 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10689 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010690 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010691 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010692 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010693 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010694 case OMPC_private:
10695 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010696 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010697 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010698 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010699 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010700 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010701 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010702 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010703 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010704 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010705 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010706 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010707 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010708 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010709 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010710 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010711 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010712 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010713 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010714 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010715 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010716 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010717 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010718 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010719 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010720 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010721 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010722 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010723 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010724 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010725 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010726 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010727 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010728 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010729 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010730 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010731 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010732 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010733 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010734 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010735 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010736 llvm_unreachable("Clause is not allowed.");
10737 }
10738 return Res;
10739}
10740
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010741// An OpenMP directive such as 'target parallel' has two captured regions:
10742// for the 'target' and 'parallel' respectively. This function returns
10743// the region in which to capture expressions associated with a clause.
10744// A return value of OMPD_unknown signifies that the expression should not
10745// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010746static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010747 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010748 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010749 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010750 switch (CKind) {
10751 case OMPC_if:
10752 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010753 case OMPD_target_parallel_for_simd:
10754 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010755 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010756 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010757 break;
10758 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010759 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010760 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010761 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010762 // If this clause applies to the nested 'parallel' region, capture within
10763 // the 'target' region, otherwise do not capture.
10764 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10765 CaptureRegion = OMPD_target;
10766 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010767 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050010768 if (OpenMPVersion >= 50 &&
10769 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10770 CaptureRegion = OMPD_parallel;
10771 break;
10772 }
10773 LLVM_FALLTHROUGH;
10774 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000010775 // If this clause applies to the nested 'parallel' region, capture within
10776 // the 'teams' region, otherwise do not capture.
10777 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10778 CaptureRegion = OMPD_teams;
10779 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010780 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050010781 if (OpenMPVersion >= 50 &&
10782 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10783 CaptureRegion = OMPD_parallel;
10784 break;
10785 }
10786 LLVM_FALLTHROUGH;
10787 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010788 CaptureRegion = OMPD_teams;
10789 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010790 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010791 case OMPD_target_enter_data:
10792 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010793 CaptureRegion = OMPD_task;
10794 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010795 case OMPD_parallel_master_taskloop:
10796 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10797 CaptureRegion = OMPD_parallel;
10798 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010799 case OMPD_parallel_master_taskloop_simd:
10800 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10801 NameModifier == OMPD_taskloop) {
10802 CaptureRegion = OMPD_parallel;
10803 break;
10804 }
10805 if (OpenMPVersion <= 45)
10806 break;
10807 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10808 CaptureRegion = OMPD_taskloop;
10809 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010810 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010811 if (OpenMPVersion <= 45)
10812 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010813 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10814 CaptureRegion = OMPD_parallel;
10815 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010816 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010817 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010818 if (OpenMPVersion <= 45)
10819 break;
10820 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10821 CaptureRegion = OMPD_taskloop;
10822 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050010823 case OMPD_distribute_parallel_for_simd:
10824 if (OpenMPVersion <= 45)
10825 break;
10826 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10827 CaptureRegion = OMPD_parallel;
10828 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050010829 case OMPD_target_simd:
10830 if (OpenMPVersion >= 50 &&
10831 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10832 CaptureRegion = OMPD_target;
10833 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050010834 case OMPD_teams_distribute_simd:
10835 if (OpenMPVersion >= 50 &&
10836 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10837 CaptureRegion = OMPD_teams;
10838 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010839 case OMPD_cancel:
10840 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010841 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010842 case OMPD_parallel_sections:
10843 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010844 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010845 case OMPD_target_teams:
10846 case OMPD_target_teams_distribute:
10847 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010848 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010849 case OMPD_task:
10850 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010851 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010852 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010853 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010854 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050010855 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010856 // Do not capture if-clause expressions.
10857 break;
10858 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010859 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010860 case OMPD_taskyield:
10861 case OMPD_barrier:
10862 case OMPD_taskwait:
10863 case OMPD_cancellation_point:
10864 case OMPD_flush:
10865 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010866 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010867 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010868 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010869 case OMPD_declare_target:
10870 case OMPD_end_declare_target:
10871 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010872 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010873 case OMPD_sections:
10874 case OMPD_section:
10875 case OMPD_single:
10876 case OMPD_master:
10877 case OMPD_critical:
10878 case OMPD_taskgroup:
10879 case OMPD_distribute:
10880 case OMPD_ordered:
10881 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010882 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000010883 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010884 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10885 case OMPD_unknown:
10886 llvm_unreachable("Unknown OpenMP directive");
10887 }
10888 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010889 case OMPC_num_threads:
10890 switch (DKind) {
10891 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010892 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010893 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010894 CaptureRegion = OMPD_target;
10895 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010896 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010897 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010898 case OMPD_target_teams_distribute_parallel_for:
10899 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010900 CaptureRegion = OMPD_teams;
10901 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010902 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010903 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010904 case OMPD_parallel_sections:
10905 case OMPD_parallel_for:
10906 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010907 case OMPD_distribute_parallel_for:
10908 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010909 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010910 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010911 // Do not capture num_threads-clause expressions.
10912 break;
10913 case OMPD_target_data:
10914 case OMPD_target_enter_data:
10915 case OMPD_target_exit_data:
10916 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010917 case OMPD_target:
10918 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010919 case OMPD_target_teams:
10920 case OMPD_target_teams_distribute:
10921 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010922 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010923 case OMPD_task:
10924 case OMPD_taskloop:
10925 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010926 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010927 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010928 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010929 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010930 case OMPD_taskyield:
10931 case OMPD_barrier:
10932 case OMPD_taskwait:
10933 case OMPD_cancellation_point:
10934 case OMPD_flush:
10935 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010936 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010937 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010938 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010939 case OMPD_declare_target:
10940 case OMPD_end_declare_target:
10941 case OMPD_teams:
10942 case OMPD_simd:
10943 case OMPD_for:
10944 case OMPD_for_simd:
10945 case OMPD_sections:
10946 case OMPD_section:
10947 case OMPD_single:
10948 case OMPD_master:
10949 case OMPD_critical:
10950 case OMPD_taskgroup:
10951 case OMPD_distribute:
10952 case OMPD_ordered:
10953 case OMPD_atomic:
10954 case OMPD_distribute_simd:
10955 case OMPD_teams_distribute:
10956 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010957 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010958 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10959 case OMPD_unknown:
10960 llvm_unreachable("Unknown OpenMP directive");
10961 }
10962 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010963 case OMPC_num_teams:
10964 switch (DKind) {
10965 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010966 case OMPD_target_teams_distribute:
10967 case OMPD_target_teams_distribute_simd:
10968 case OMPD_target_teams_distribute_parallel_for:
10969 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010970 CaptureRegion = OMPD_target;
10971 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010972 case OMPD_teams_distribute_parallel_for:
10973 case OMPD_teams_distribute_parallel_for_simd:
10974 case OMPD_teams:
10975 case OMPD_teams_distribute:
10976 case OMPD_teams_distribute_simd:
10977 // Do not capture num_teams-clause expressions.
10978 break;
10979 case OMPD_distribute_parallel_for:
10980 case OMPD_distribute_parallel_for_simd:
10981 case OMPD_task:
10982 case OMPD_taskloop:
10983 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010984 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010985 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010986 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010987 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010988 case OMPD_target_data:
10989 case OMPD_target_enter_data:
10990 case OMPD_target_exit_data:
10991 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010992 case OMPD_cancel:
10993 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010994 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010995 case OMPD_parallel_sections:
10996 case OMPD_parallel_for:
10997 case OMPD_parallel_for_simd:
10998 case OMPD_target:
10999 case OMPD_target_simd:
11000 case OMPD_target_parallel:
11001 case OMPD_target_parallel_for:
11002 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011003 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011004 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011005 case OMPD_taskyield:
11006 case OMPD_barrier:
11007 case OMPD_taskwait:
11008 case OMPD_cancellation_point:
11009 case OMPD_flush:
11010 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011011 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011012 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011013 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011014 case OMPD_declare_target:
11015 case OMPD_end_declare_target:
11016 case OMPD_simd:
11017 case OMPD_for:
11018 case OMPD_for_simd:
11019 case OMPD_sections:
11020 case OMPD_section:
11021 case OMPD_single:
11022 case OMPD_master:
11023 case OMPD_critical:
11024 case OMPD_taskgroup:
11025 case OMPD_distribute:
11026 case OMPD_ordered:
11027 case OMPD_atomic:
11028 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011029 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011030 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11031 case OMPD_unknown:
11032 llvm_unreachable("Unknown OpenMP directive");
11033 }
11034 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011035 case OMPC_thread_limit:
11036 switch (DKind) {
11037 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011038 case OMPD_target_teams_distribute:
11039 case OMPD_target_teams_distribute_simd:
11040 case OMPD_target_teams_distribute_parallel_for:
11041 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011042 CaptureRegion = OMPD_target;
11043 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011044 case OMPD_teams_distribute_parallel_for:
11045 case OMPD_teams_distribute_parallel_for_simd:
11046 case OMPD_teams:
11047 case OMPD_teams_distribute:
11048 case OMPD_teams_distribute_simd:
11049 // Do not capture thread_limit-clause expressions.
11050 break;
11051 case OMPD_distribute_parallel_for:
11052 case OMPD_distribute_parallel_for_simd:
11053 case OMPD_task:
11054 case OMPD_taskloop:
11055 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011056 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011057 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011058 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011059 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011060 case OMPD_target_data:
11061 case OMPD_target_enter_data:
11062 case OMPD_target_exit_data:
11063 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011064 case OMPD_cancel:
11065 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011066 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011067 case OMPD_parallel_sections:
11068 case OMPD_parallel_for:
11069 case OMPD_parallel_for_simd:
11070 case OMPD_target:
11071 case OMPD_target_simd:
11072 case OMPD_target_parallel:
11073 case OMPD_target_parallel_for:
11074 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011075 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011076 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011077 case OMPD_taskyield:
11078 case OMPD_barrier:
11079 case OMPD_taskwait:
11080 case OMPD_cancellation_point:
11081 case OMPD_flush:
11082 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011083 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011084 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011085 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011086 case OMPD_declare_target:
11087 case OMPD_end_declare_target:
11088 case OMPD_simd:
11089 case OMPD_for:
11090 case OMPD_for_simd:
11091 case OMPD_sections:
11092 case OMPD_section:
11093 case OMPD_single:
11094 case OMPD_master:
11095 case OMPD_critical:
11096 case OMPD_taskgroup:
11097 case OMPD_distribute:
11098 case OMPD_ordered:
11099 case OMPD_atomic:
11100 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011101 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011102 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11103 case OMPD_unknown:
11104 llvm_unreachable("Unknown OpenMP directive");
11105 }
11106 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011107 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011108 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011109 case OMPD_parallel_for:
11110 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011111 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011112 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011113 case OMPD_teams_distribute_parallel_for:
11114 case OMPD_teams_distribute_parallel_for_simd:
11115 case OMPD_target_parallel_for:
11116 case OMPD_target_parallel_for_simd:
11117 case OMPD_target_teams_distribute_parallel_for:
11118 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011119 CaptureRegion = OMPD_parallel;
11120 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011121 case OMPD_for:
11122 case OMPD_for_simd:
11123 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011124 break;
11125 case OMPD_task:
11126 case OMPD_taskloop:
11127 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011128 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011129 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011130 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011131 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011132 case OMPD_target_data:
11133 case OMPD_target_enter_data:
11134 case OMPD_target_exit_data:
11135 case OMPD_target_update:
11136 case OMPD_teams:
11137 case OMPD_teams_distribute:
11138 case OMPD_teams_distribute_simd:
11139 case OMPD_target_teams_distribute:
11140 case OMPD_target_teams_distribute_simd:
11141 case OMPD_target:
11142 case OMPD_target_simd:
11143 case OMPD_target_parallel:
11144 case OMPD_cancel:
11145 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011146 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011147 case OMPD_parallel_sections:
11148 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011149 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011150 case OMPD_taskyield:
11151 case OMPD_barrier:
11152 case OMPD_taskwait:
11153 case OMPD_cancellation_point:
11154 case OMPD_flush:
11155 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011156 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011157 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011158 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011159 case OMPD_declare_target:
11160 case OMPD_end_declare_target:
11161 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011162 case OMPD_sections:
11163 case OMPD_section:
11164 case OMPD_single:
11165 case OMPD_master:
11166 case OMPD_critical:
11167 case OMPD_taskgroup:
11168 case OMPD_distribute:
11169 case OMPD_ordered:
11170 case OMPD_atomic:
11171 case OMPD_distribute_simd:
11172 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011173 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011174 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11175 case OMPD_unknown:
11176 llvm_unreachable("Unknown OpenMP directive");
11177 }
11178 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011179 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011180 switch (DKind) {
11181 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011182 case OMPD_teams_distribute_parallel_for_simd:
11183 case OMPD_teams_distribute:
11184 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011185 case OMPD_target_teams_distribute_parallel_for:
11186 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011187 case OMPD_target_teams_distribute:
11188 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011189 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011190 break;
11191 case OMPD_distribute_parallel_for:
11192 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011193 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011194 case OMPD_distribute_simd:
11195 // Do not capture thread_limit-clause expressions.
11196 break;
11197 case OMPD_parallel_for:
11198 case OMPD_parallel_for_simd:
11199 case OMPD_target_parallel_for_simd:
11200 case OMPD_target_parallel_for:
11201 case OMPD_task:
11202 case OMPD_taskloop:
11203 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011204 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011205 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011206 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011207 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011208 case OMPD_target_data:
11209 case OMPD_target_enter_data:
11210 case OMPD_target_exit_data:
11211 case OMPD_target_update:
11212 case OMPD_teams:
11213 case OMPD_target:
11214 case OMPD_target_simd:
11215 case OMPD_target_parallel:
11216 case OMPD_cancel:
11217 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011218 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011219 case OMPD_parallel_sections:
11220 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011221 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011222 case OMPD_taskyield:
11223 case OMPD_barrier:
11224 case OMPD_taskwait:
11225 case OMPD_cancellation_point:
11226 case OMPD_flush:
11227 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011228 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011229 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011230 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011231 case OMPD_declare_target:
11232 case OMPD_end_declare_target:
11233 case OMPD_simd:
11234 case OMPD_for:
11235 case OMPD_for_simd:
11236 case OMPD_sections:
11237 case OMPD_section:
11238 case OMPD_single:
11239 case OMPD_master:
11240 case OMPD_critical:
11241 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011242 case OMPD_ordered:
11243 case OMPD_atomic:
11244 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011245 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011246 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11247 case OMPD_unknown:
11248 llvm_unreachable("Unknown OpenMP directive");
11249 }
11250 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011251 case OMPC_device:
11252 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011253 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011254 case OMPD_target_enter_data:
11255 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011256 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011257 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011258 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011259 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011260 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011261 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011262 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011263 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011264 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011265 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011266 CaptureRegion = OMPD_task;
11267 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011268 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011269 // Do not capture device-clause expressions.
11270 break;
11271 case OMPD_teams_distribute_parallel_for:
11272 case OMPD_teams_distribute_parallel_for_simd:
11273 case OMPD_teams:
11274 case OMPD_teams_distribute:
11275 case OMPD_teams_distribute_simd:
11276 case OMPD_distribute_parallel_for:
11277 case OMPD_distribute_parallel_for_simd:
11278 case OMPD_task:
11279 case OMPD_taskloop:
11280 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011281 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011282 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011283 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011284 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011285 case OMPD_cancel:
11286 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011287 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011288 case OMPD_parallel_sections:
11289 case OMPD_parallel_for:
11290 case OMPD_parallel_for_simd:
11291 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011292 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011293 case OMPD_taskyield:
11294 case OMPD_barrier:
11295 case OMPD_taskwait:
11296 case OMPD_cancellation_point:
11297 case OMPD_flush:
11298 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011299 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011300 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011301 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011302 case OMPD_declare_target:
11303 case OMPD_end_declare_target:
11304 case OMPD_simd:
11305 case OMPD_for:
11306 case OMPD_for_simd:
11307 case OMPD_sections:
11308 case OMPD_section:
11309 case OMPD_single:
11310 case OMPD_master:
11311 case OMPD_critical:
11312 case OMPD_taskgroup:
11313 case OMPD_distribute:
11314 case OMPD_ordered:
11315 case OMPD_atomic:
11316 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011317 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011318 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11319 case OMPD_unknown:
11320 llvm_unreachable("Unknown OpenMP directive");
11321 }
11322 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011323 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011324 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011325 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011326 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011327 switch (DKind) {
11328 case OMPD_task:
11329 case OMPD_taskloop:
11330 case OMPD_taskloop_simd:
11331 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011332 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011333 break;
11334 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011335 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011336 CaptureRegion = OMPD_parallel;
11337 break;
11338 case OMPD_target_update:
11339 case OMPD_target_enter_data:
11340 case OMPD_target_exit_data:
11341 case OMPD_target:
11342 case OMPD_target_simd:
11343 case OMPD_target_teams:
11344 case OMPD_target_parallel:
11345 case OMPD_target_teams_distribute:
11346 case OMPD_target_teams_distribute_simd:
11347 case OMPD_target_parallel_for:
11348 case OMPD_target_parallel_for_simd:
11349 case OMPD_target_teams_distribute_parallel_for:
11350 case OMPD_target_teams_distribute_parallel_for_simd:
11351 case OMPD_target_data:
11352 case OMPD_teams_distribute_parallel_for:
11353 case OMPD_teams_distribute_parallel_for_simd:
11354 case OMPD_teams:
11355 case OMPD_teams_distribute:
11356 case OMPD_teams_distribute_simd:
11357 case OMPD_distribute_parallel_for:
11358 case OMPD_distribute_parallel_for_simd:
11359 case OMPD_cancel:
11360 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011361 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011362 case OMPD_parallel_sections:
11363 case OMPD_parallel_for:
11364 case OMPD_parallel_for_simd:
11365 case OMPD_threadprivate:
11366 case OMPD_allocate:
11367 case OMPD_taskyield:
11368 case OMPD_barrier:
11369 case OMPD_taskwait:
11370 case OMPD_cancellation_point:
11371 case OMPD_flush:
11372 case OMPD_declare_reduction:
11373 case OMPD_declare_mapper:
11374 case OMPD_declare_simd:
11375 case OMPD_declare_variant:
11376 case OMPD_declare_target:
11377 case OMPD_end_declare_target:
11378 case OMPD_simd:
11379 case OMPD_for:
11380 case OMPD_for_simd:
11381 case OMPD_sections:
11382 case OMPD_section:
11383 case OMPD_single:
11384 case OMPD_master:
11385 case OMPD_critical:
11386 case OMPD_taskgroup:
11387 case OMPD_distribute:
11388 case OMPD_ordered:
11389 case OMPD_atomic:
11390 case OMPD_distribute_simd:
11391 case OMPD_requires:
11392 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11393 case OMPD_unknown:
11394 llvm_unreachable("Unknown OpenMP directive");
11395 }
11396 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011397 case OMPC_firstprivate:
11398 case OMPC_lastprivate:
11399 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011400 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011401 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011402 case OMPC_linear:
11403 case OMPC_default:
11404 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011405 case OMPC_safelen:
11406 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011407 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011408 case OMPC_collapse:
11409 case OMPC_private:
11410 case OMPC_shared:
11411 case OMPC_aligned:
11412 case OMPC_copyin:
11413 case OMPC_copyprivate:
11414 case OMPC_ordered:
11415 case OMPC_nowait:
11416 case OMPC_untied:
11417 case OMPC_mergeable:
11418 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011419 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011420 case OMPC_flush:
11421 case OMPC_read:
11422 case OMPC_write:
11423 case OMPC_update:
11424 case OMPC_capture:
11425 case OMPC_seq_cst:
11426 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011427 case OMPC_threads:
11428 case OMPC_simd:
11429 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011430 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011431 case OMPC_hint:
11432 case OMPC_defaultmap:
11433 case OMPC_unknown:
11434 case OMPC_uniform:
11435 case OMPC_to:
11436 case OMPC_from:
11437 case OMPC_use_device_ptr:
11438 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011439 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011440 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011441 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011442 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011443 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011444 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011445 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011446 llvm_unreachable("Unexpected OpenMP clause.");
11447 }
11448 return CaptureRegion;
11449}
11450
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011451OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11452 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011453 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011454 SourceLocation NameModifierLoc,
11455 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011456 SourceLocation EndLoc) {
11457 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011458 Stmt *HelperValStmt = nullptr;
11459 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011460 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11461 !Condition->isInstantiationDependent() &&
11462 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011463 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011464 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011465 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011466
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011467 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011468
11469 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011470 CaptureRegion = getOpenMPCaptureRegionForClause(
11471 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011472 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011473 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011474 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011475 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11476 HelperValStmt = buildPreInits(Context, Captures);
11477 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011478 }
11479
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011480 return new (Context)
11481 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11482 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011483}
11484
Alexey Bataev3778b602014-07-17 07:32:53 +000011485OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11486 SourceLocation StartLoc,
11487 SourceLocation LParenLoc,
11488 SourceLocation EndLoc) {
11489 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011490 Stmt *HelperValStmt = nullptr;
11491 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011492 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11493 !Condition->isInstantiationDependent() &&
11494 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011495 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011496 if (Val.isInvalid())
11497 return nullptr;
11498
Richard Smith03a4aa32016-06-23 19:02:52 +000011499 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011500
11501 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011502 CaptureRegion =
11503 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011504 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11505 ValExpr = MakeFullExpr(ValExpr).get();
11506 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11507 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11508 HelperValStmt = buildPreInits(Context, Captures);
11509 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011510 }
11511
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011512 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11513 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011514}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011515
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011516ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11517 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011518 if (!Op)
11519 return ExprError();
11520
11521 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11522 public:
11523 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011524 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011525 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11526 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011527 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11528 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011529 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11530 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011531 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11532 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011533 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11534 QualType T,
11535 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011536 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11537 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011538 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11539 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011540 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011541 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011542 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011543 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11544 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011545 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11546 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011547 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11548 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011549 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011550 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011551 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011552 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11553 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011554 llvm_unreachable("conversion functions are permitted");
11555 }
11556 } ConvertDiagnoser;
11557 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11558}
11559
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011560static bool
11561isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11562 bool StrictlyPositive, bool BuildCapture = false,
11563 OpenMPDirectiveKind DKind = OMPD_unknown,
11564 OpenMPDirectiveKind *CaptureRegion = nullptr,
11565 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011566 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11567 !ValExpr->isInstantiationDependent()) {
11568 SourceLocation Loc = ValExpr->getExprLoc();
11569 ExprResult Value =
11570 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11571 if (Value.isInvalid())
11572 return false;
11573
11574 ValExpr = Value.get();
11575 // The expression must evaluate to a non-negative integer value.
11576 llvm::APSInt Result;
11577 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011578 Result.isSigned() &&
11579 !((!StrictlyPositive && Result.isNonNegative()) ||
11580 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011581 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011582 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11583 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011584 return false;
11585 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011586 if (!BuildCapture)
11587 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011588 *CaptureRegion =
11589 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011590 if (*CaptureRegion != OMPD_unknown &&
11591 !SemaRef.CurContext->isDependentContext()) {
11592 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11593 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11594 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11595 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11596 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011597 }
11598 return true;
11599}
11600
Alexey Bataev568a8332014-03-06 06:15:19 +000011601OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11602 SourceLocation StartLoc,
11603 SourceLocation LParenLoc,
11604 SourceLocation EndLoc) {
11605 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011606 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011607
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011608 // OpenMP [2.5, Restrictions]
11609 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011610 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011611 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011612 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011613
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011614 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011615 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011616 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011617 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011618 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011619 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011620 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11621 HelperValStmt = buildPreInits(Context, Captures);
11622 }
11623
11624 return new (Context) OMPNumThreadsClause(
11625 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011626}
11627
Alexey Bataev62c87d22014-03-21 04:51:18 +000011628ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011629 OpenMPClauseKind CKind,
11630 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011631 if (!E)
11632 return ExprError();
11633 if (E->isValueDependent() || E->isTypeDependent() ||
11634 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011635 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011636 llvm::APSInt Result;
11637 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11638 if (ICE.isInvalid())
11639 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011640 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11641 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011642 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011643 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11644 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011645 return ExprError();
11646 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011647 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11648 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11649 << E->getSourceRange();
11650 return ExprError();
11651 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011652 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11653 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011654 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011655 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011656 return ICE;
11657}
11658
11659OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11660 SourceLocation LParenLoc,
11661 SourceLocation EndLoc) {
11662 // OpenMP [2.8.1, simd construct, Description]
11663 // The parameter of the safelen clause must be a constant
11664 // positive integer expression.
11665 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11666 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011667 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011668 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011669 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011670}
11671
Alexey Bataev66b15b52015-08-21 11:14:16 +000011672OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11673 SourceLocation LParenLoc,
11674 SourceLocation EndLoc) {
11675 // OpenMP [2.8.1, simd construct, Description]
11676 // The parameter of the simdlen clause must be a constant
11677 // positive integer expression.
11678 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11679 if (Simdlen.isInvalid())
11680 return nullptr;
11681 return new (Context)
11682 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11683}
11684
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011685/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011686static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11687 DSAStackTy *Stack) {
11688 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011689 if (!OMPAllocatorHandleT.isNull())
11690 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011691 // Build the predefined allocator expressions.
11692 bool ErrorFound = false;
11693 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11694 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11695 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11696 StringRef Allocator =
11697 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11698 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11699 auto *VD = dyn_cast_or_null<ValueDecl>(
11700 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11701 if (!VD) {
11702 ErrorFound = true;
11703 break;
11704 }
11705 QualType AllocatorType =
11706 VD->getType().getNonLValueExprType(S.getASTContext());
11707 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11708 if (!Res.isUsable()) {
11709 ErrorFound = true;
11710 break;
11711 }
11712 if (OMPAllocatorHandleT.isNull())
11713 OMPAllocatorHandleT = AllocatorType;
11714 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11715 ErrorFound = true;
11716 break;
11717 }
11718 Stack->setAllocator(AllocatorKind, Res.get());
11719 }
11720 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011721 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11722 return false;
11723 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011724 OMPAllocatorHandleT.addConst();
11725 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011726 return true;
11727}
11728
11729OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11730 SourceLocation LParenLoc,
11731 SourceLocation EndLoc) {
11732 // OpenMP [2.11.3, allocate Directive, Description]
11733 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011734 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011735 return nullptr;
11736
11737 ExprResult Allocator = DefaultLvalueConversion(A);
11738 if (Allocator.isInvalid())
11739 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011740 Allocator = PerformImplicitConversion(Allocator.get(),
11741 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011742 Sema::AA_Initializing,
11743 /*AllowExplicit=*/true);
11744 if (Allocator.isInvalid())
11745 return nullptr;
11746 return new (Context)
11747 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11748}
11749
Alexander Musman64d33f12014-06-04 07:53:32 +000011750OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11751 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011752 SourceLocation LParenLoc,
11753 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011754 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011755 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011756 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011757 // The parameter of the collapse clause must be a constant
11758 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011759 ExprResult NumForLoopsResult =
11760 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11761 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011762 return nullptr;
11763 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011764 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011765}
11766
Alexey Bataev10e775f2015-07-30 11:36:16 +000011767OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11768 SourceLocation EndLoc,
11769 SourceLocation LParenLoc,
11770 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011771 // OpenMP [2.7.1, loop construct, Description]
11772 // OpenMP [2.8.1, simd construct, Description]
11773 // OpenMP [2.9.6, distribute construct, Description]
11774 // The parameter of the ordered clause must be a constant
11775 // positive integer expression if any.
11776 if (NumForLoops && LParenLoc.isValid()) {
11777 ExprResult NumForLoopsResult =
11778 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11779 if (NumForLoopsResult.isInvalid())
11780 return nullptr;
11781 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011782 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011783 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011784 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011785 auto *Clause = OMPOrderedClause::Create(
11786 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11787 StartLoc, LParenLoc, EndLoc);
11788 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11789 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011790}
11791
Alexey Bataeved09d242014-05-28 05:53:51 +000011792OMPClause *Sema::ActOnOpenMPSimpleClause(
11793 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11794 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011795 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011796 switch (Kind) {
11797 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011798 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011799 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11800 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011801 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011802 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011803 Res = ActOnOpenMPProcBindClause(
11804 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11805 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011806 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011807 case OMPC_atomic_default_mem_order:
11808 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11809 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11810 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11811 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011812 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011813 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011814 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011815 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011816 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011817 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011818 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011819 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011820 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011821 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011822 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011823 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011824 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011825 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011826 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011827 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011828 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011829 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011830 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011831 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011832 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011833 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011834 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011835 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011836 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011837 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011838 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011839 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011840 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011841 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011842 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011843 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011844 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011845 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011846 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011847 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011848 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011849 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011850 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011851 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011852 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011853 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011854 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011855 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011856 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011857 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011858 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011859 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011860 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011861 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011862 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011863 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011864 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011865 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011866 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011867 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011868 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011869 llvm_unreachable("Clause is not allowed.");
11870 }
11871 return Res;
11872}
11873
Alexey Bataev6402bca2015-12-28 07:25:51 +000011874static std::string
11875getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11876 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011877 SmallString<256> Buffer;
11878 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011879 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11880 unsigned Skipped = Exclude.size();
11881 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011882 for (unsigned I = First; I < Last; ++I) {
11883 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011884 --Skipped;
11885 continue;
11886 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011887 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11888 if (I == Bound - Skipped)
11889 Out << " or ";
11890 else if (I != Bound + 1 - Skipped)
11891 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011892 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011893 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011894}
11895
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011896OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11897 SourceLocation KindKwLoc,
11898 SourceLocation StartLoc,
11899 SourceLocation LParenLoc,
11900 SourceLocation EndLoc) {
11901 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011902 static_assert(OMPC_DEFAULT_unknown > 0,
11903 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011904 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011905 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11906 /*Last=*/OMPC_DEFAULT_unknown)
11907 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011908 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011909 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011910 switch (Kind) {
11911 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011912 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011913 break;
11914 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011915 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011916 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011917 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011918 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011919 break;
11920 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011921 return new (Context)
11922 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011923}
11924
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011925OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11926 SourceLocation KindKwLoc,
11927 SourceLocation StartLoc,
11928 SourceLocation LParenLoc,
11929 SourceLocation EndLoc) {
11930 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011931 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011932 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11933 /*Last=*/OMPC_PROC_BIND_unknown)
11934 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011935 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011936 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011937 return new (Context)
11938 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011939}
11940
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011941OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11942 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11943 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11944 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11945 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11946 << getListOfPossibleValues(
11947 OMPC_atomic_default_mem_order, /*First=*/0,
11948 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11949 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11950 return nullptr;
11951 }
11952 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11953 LParenLoc, EndLoc);
11954}
11955
Alexey Bataev56dafe82014-06-20 07:16:17 +000011956OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011957 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011958 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011959 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011960 SourceLocation EndLoc) {
11961 OMPClause *Res = nullptr;
11962 switch (Kind) {
11963 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011964 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11965 assert(Argument.size() == NumberOfElements &&
11966 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011967 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011968 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11969 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11970 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11971 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11972 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011973 break;
11974 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011975 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11976 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11977 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11978 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011979 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011980 case OMPC_dist_schedule:
11981 Res = ActOnOpenMPDistScheduleClause(
11982 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11983 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11984 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011985 case OMPC_defaultmap:
11986 enum { Modifier, DefaultmapKind };
11987 Res = ActOnOpenMPDefaultmapClause(
11988 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11989 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011990 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11991 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011992 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011993 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011994 case OMPC_num_threads:
11995 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011996 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011997 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011998 case OMPC_collapse:
11999 case OMPC_default:
12000 case OMPC_proc_bind:
12001 case OMPC_private:
12002 case OMPC_firstprivate:
12003 case OMPC_lastprivate:
12004 case OMPC_shared:
12005 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012006 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012007 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012008 case OMPC_linear:
12009 case OMPC_aligned:
12010 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012011 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012012 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012013 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012014 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012015 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012016 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012017 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012018 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012019 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012020 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012021 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012022 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012023 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012024 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012025 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012026 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012027 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012028 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012029 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012030 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012031 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012032 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012033 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012034 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012035 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012036 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012037 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012038 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012039 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012040 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012041 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012042 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012043 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012044 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012045 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012046 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012047 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012048 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012049 llvm_unreachable("Clause is not allowed.");
12050 }
12051 return Res;
12052}
12053
Alexey Bataev6402bca2015-12-28 07:25:51 +000012054static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12055 OpenMPScheduleClauseModifier M2,
12056 SourceLocation M1Loc, SourceLocation M2Loc) {
12057 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12058 SmallVector<unsigned, 2> Excluded;
12059 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12060 Excluded.push_back(M2);
12061 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12062 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12063 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12064 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12065 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12066 << getListOfPossibleValues(OMPC_schedule,
12067 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12068 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12069 Excluded)
12070 << getOpenMPClauseName(OMPC_schedule);
12071 return true;
12072 }
12073 return false;
12074}
12075
Alexey Bataev56dafe82014-06-20 07:16:17 +000012076OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012077 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012078 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012079 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12080 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12081 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12082 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12083 return nullptr;
12084 // OpenMP, 2.7.1, Loop Construct, Restrictions
12085 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12086 // but not both.
12087 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12088 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12089 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12090 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12091 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12092 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12093 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12094 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12095 return nullptr;
12096 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012097 if (Kind == OMPC_SCHEDULE_unknown) {
12098 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012099 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12100 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12101 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12102 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12103 Exclude);
12104 } else {
12105 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12106 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012107 }
12108 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12109 << Values << getOpenMPClauseName(OMPC_schedule);
12110 return nullptr;
12111 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012112 // OpenMP, 2.7.1, Loop Construct, Restrictions
12113 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12114 // schedule(guided).
12115 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12116 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12117 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12118 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12119 diag::err_omp_schedule_nonmonotonic_static);
12120 return nullptr;
12121 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012122 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012123 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012124 if (ChunkSize) {
12125 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12126 !ChunkSize->isInstantiationDependent() &&
12127 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012128 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012129 ExprResult Val =
12130 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12131 if (Val.isInvalid())
12132 return nullptr;
12133
12134 ValExpr = Val.get();
12135
12136 // OpenMP [2.7.1, Restrictions]
12137 // chunk_size must be a loop invariant integer expression with a positive
12138 // value.
12139 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012140 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12141 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12142 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012143 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012144 return nullptr;
12145 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012146 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012147 DSAStack->getCurrentDirective(), OMPC_schedule,
12148 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012149 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012150 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012151 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012152 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12153 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012154 }
12155 }
12156 }
12157
Alexey Bataev6402bca2015-12-28 07:25:51 +000012158 return new (Context)
12159 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012160 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012161}
12162
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012163OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12164 SourceLocation StartLoc,
12165 SourceLocation EndLoc) {
12166 OMPClause *Res = nullptr;
12167 switch (Kind) {
12168 case OMPC_ordered:
12169 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12170 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012171 case OMPC_nowait:
12172 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12173 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012174 case OMPC_untied:
12175 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12176 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012177 case OMPC_mergeable:
12178 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12179 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012180 case OMPC_read:
12181 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12182 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012183 case OMPC_write:
12184 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12185 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012186 case OMPC_update:
12187 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12188 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012189 case OMPC_capture:
12190 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12191 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012192 case OMPC_seq_cst:
12193 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12194 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012195 case OMPC_threads:
12196 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12197 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012198 case OMPC_simd:
12199 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12200 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012201 case OMPC_nogroup:
12202 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12203 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012204 case OMPC_unified_address:
12205 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12206 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012207 case OMPC_unified_shared_memory:
12208 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12209 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012210 case OMPC_reverse_offload:
12211 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12212 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012213 case OMPC_dynamic_allocators:
12214 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12215 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012216 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012217 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012218 case OMPC_num_threads:
12219 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012220 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012221 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012222 case OMPC_collapse:
12223 case OMPC_schedule:
12224 case OMPC_private:
12225 case OMPC_firstprivate:
12226 case OMPC_lastprivate:
12227 case OMPC_shared:
12228 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012229 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012230 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012231 case OMPC_linear:
12232 case OMPC_aligned:
12233 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012234 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012235 case OMPC_default:
12236 case OMPC_proc_bind:
12237 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012238 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012239 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012240 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012241 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012242 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012243 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012244 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012245 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012246 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012247 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012248 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012249 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012250 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012251 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012252 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012253 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012254 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012255 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012256 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012257 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012258 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012259 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012260 llvm_unreachable("Clause is not allowed.");
12261 }
12262 return Res;
12263}
12264
Alexey Bataev236070f2014-06-20 11:19:47 +000012265OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12266 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012267 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012268 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12269}
12270
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012271OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12272 SourceLocation EndLoc) {
12273 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12274}
12275
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012276OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12277 SourceLocation EndLoc) {
12278 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12279}
12280
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012281OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12282 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012283 return new (Context) OMPReadClause(StartLoc, EndLoc);
12284}
12285
Alexey Bataevdea47612014-07-23 07:46:59 +000012286OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12287 SourceLocation EndLoc) {
12288 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12289}
12290
Alexey Bataev67a4f222014-07-23 10:25:33 +000012291OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12292 SourceLocation EndLoc) {
12293 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12294}
12295
Alexey Bataev459dec02014-07-24 06:46:57 +000012296OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12297 SourceLocation EndLoc) {
12298 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12299}
12300
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012301OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12302 SourceLocation EndLoc) {
12303 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12304}
12305
Alexey Bataev346265e2015-09-25 10:37:12 +000012306OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12307 SourceLocation EndLoc) {
12308 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12309}
12310
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012311OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12312 SourceLocation EndLoc) {
12313 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12314}
12315
Alexey Bataevb825de12015-12-07 10:51:44 +000012316OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12317 SourceLocation EndLoc) {
12318 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12319}
12320
Kelvin Li1408f912018-09-26 04:28:39 +000012321OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12322 SourceLocation EndLoc) {
12323 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12324}
12325
Patrick Lyster4a370b92018-10-01 13:47:43 +000012326OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12327 SourceLocation EndLoc) {
12328 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12329}
12330
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012331OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12332 SourceLocation EndLoc) {
12333 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12334}
12335
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012336OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12337 SourceLocation EndLoc) {
12338 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12339}
12340
Alexey Bataevc5e02582014-06-16 07:08:35 +000012341OMPClause *Sema::ActOnOpenMPVarListClause(
12342 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012343 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12344 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
12345 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000012346 OpenMPLinearClauseKind LinKind,
12347 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012348 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
12349 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
12350 SourceLocation StartLoc = Locs.StartLoc;
12351 SourceLocation LParenLoc = Locs.LParenLoc;
12352 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012353 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012354 switch (Kind) {
12355 case OMPC_private:
12356 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12357 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012358 case OMPC_firstprivate:
12359 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12360 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012361 case OMPC_lastprivate:
12362 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12363 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012364 case OMPC_shared:
12365 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12366 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012367 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012368 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012369 EndLoc, ReductionOrMapperIdScopeSpec,
12370 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012371 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012372 case OMPC_task_reduction:
12373 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012374 EndLoc, ReductionOrMapperIdScopeSpec,
12375 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012376 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012377 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012378 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12379 EndLoc, ReductionOrMapperIdScopeSpec,
12380 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012381 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012382 case OMPC_linear:
12383 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012384 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012385 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012386 case OMPC_aligned:
12387 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12388 ColonLoc, EndLoc);
12389 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012390 case OMPC_copyin:
12391 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12392 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012393 case OMPC_copyprivate:
12394 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12395 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012396 case OMPC_flush:
12397 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12398 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012399 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000012400 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012401 StartLoc, LParenLoc, EndLoc);
12402 break;
12403 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012404 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
12405 ReductionOrMapperIdScopeSpec,
12406 ReductionOrMapperId, MapType, IsMapTypeImplicit,
12407 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012408 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012409 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012410 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12411 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012412 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012413 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012414 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12415 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012416 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012417 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012418 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012419 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012420 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012421 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012422 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012423 case OMPC_allocate:
12424 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12425 ColonLoc, EndLoc);
12426 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012427 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012428 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012429 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012430 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012431 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012432 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012433 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012434 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012435 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012436 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012437 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012438 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012439 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012440 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012441 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012442 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012443 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012444 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012445 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012446 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012447 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012448 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012449 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012450 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012451 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012452 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012453 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012454 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012455 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012456 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012457 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012458 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012459 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012460 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012461 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012462 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012463 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012464 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012465 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012466 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012467 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012468 llvm_unreachable("Clause is not allowed.");
12469 }
12470 return Res;
12471}
12472
Alexey Bataev90c228f2016-02-08 09:29:13 +000012473ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012474 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012475 ExprResult Res = BuildDeclRefExpr(
12476 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12477 if (!Res.isUsable())
12478 return ExprError();
12479 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12480 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12481 if (!Res.isUsable())
12482 return ExprError();
12483 }
12484 if (VK != VK_LValue && Res.get()->isGLValue()) {
12485 Res = DefaultLvalueConversion(Res.get());
12486 if (!Res.isUsable())
12487 return ExprError();
12488 }
12489 return Res;
12490}
12491
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012492OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12493 SourceLocation StartLoc,
12494 SourceLocation LParenLoc,
12495 SourceLocation EndLoc) {
12496 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012497 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012498 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012499 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012500 SourceLocation ELoc;
12501 SourceRange ERange;
12502 Expr *SimpleRefExpr = RefExpr;
12503 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012504 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012505 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012506 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012507 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012508 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012509 ValueDecl *D = Res.first;
12510 if (!D)
12511 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012512
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012513 QualType Type = D->getType();
12514 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012515
12516 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12517 // A variable that appears in a private clause must not have an incomplete
12518 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012519 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012520 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012521 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012522
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012523 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12524 // A variable that is privatized must not have a const-qualified type
12525 // unless it is of class type with a mutable member. This restriction does
12526 // not apply to the firstprivate clause.
12527 //
12528 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12529 // A variable that appears in a private clause must not have a
12530 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012531 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012532 continue;
12533
Alexey Bataev758e55e2013-09-06 18:03:48 +000012534 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12535 // in a Construct]
12536 // Variables with the predetermined data-sharing attributes may not be
12537 // listed in data-sharing attributes clauses, except for the cases
12538 // listed below. For these exceptions only, listing a predetermined
12539 // variable in a data-sharing attribute clause is allowed and overrides
12540 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012541 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012542 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012543 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12544 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012545 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012546 continue;
12547 }
12548
Alexey Bataeve3727102018-04-18 15:57:46 +000012549 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012550 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012551 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012552 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012553 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12554 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012555 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012556 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012557 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012558 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012559 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012560 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012561 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012562 continue;
12563 }
12564
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012565 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12566 // A list item cannot appear in both a map clause and a data-sharing
12567 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012568 //
12569 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12570 // A list item cannot appear in both a map clause and a data-sharing
12571 // attribute clause on the same construct unless the construct is a
12572 // combined construct.
12573 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12574 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012575 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012576 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012577 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012578 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12579 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12580 ConflictKind = WhereFoundClauseKind;
12581 return true;
12582 })) {
12583 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012584 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012585 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012586 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012587 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012588 continue;
12589 }
12590 }
12591
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012592 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12593 // A variable of class type (or array thereof) that appears in a private
12594 // clause requires an accessible, unambiguous default constructor for the
12595 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012596 // Generate helper private variable and initialize it with the default
12597 // value. The address of the original variable is replaced by the address of
12598 // the new private variable in CodeGen. This new variable is not added to
12599 // IdResolver, so the code in the OpenMP region uses original variable for
12600 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012601 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012602 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012603 buildVarDecl(*this, ELoc, Type, D->getName(),
12604 D->hasAttrs() ? &D->getAttrs() : nullptr,
12605 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012606 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012607 if (VDPrivate->isInvalidDecl())
12608 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012609 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012610 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012611
Alexey Bataev90c228f2016-02-08 09:29:13 +000012612 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012613 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012614 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012615 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012616 Vars.push_back((VD || CurContext->isDependentContext())
12617 ? RefExpr->IgnoreParens()
12618 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012619 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012620 }
12621
Alexey Bataeved09d242014-05-28 05:53:51 +000012622 if (Vars.empty())
12623 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012624
Alexey Bataev03b340a2014-10-21 03:16:40 +000012625 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12626 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012627}
12628
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012629namespace {
12630class DiagsUninitializedSeveretyRAII {
12631private:
12632 DiagnosticsEngine &Diags;
12633 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012634 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012635
12636public:
12637 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12638 bool IsIgnored)
12639 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12640 if (!IsIgnored) {
12641 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12642 /*Map*/ diag::Severity::Ignored, Loc);
12643 }
12644 }
12645 ~DiagsUninitializedSeveretyRAII() {
12646 if (!IsIgnored)
12647 Diags.popMappings(SavedLoc);
12648 }
12649};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012650}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012651
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012652OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12653 SourceLocation StartLoc,
12654 SourceLocation LParenLoc,
12655 SourceLocation EndLoc) {
12656 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012657 SmallVector<Expr *, 8> PrivateCopies;
12658 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012659 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012660 bool IsImplicitClause =
12661 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012662 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012663
Alexey Bataeve3727102018-04-18 15:57:46 +000012664 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012665 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012666 SourceLocation ELoc;
12667 SourceRange ERange;
12668 Expr *SimpleRefExpr = RefExpr;
12669 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012670 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012671 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012672 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012673 PrivateCopies.push_back(nullptr);
12674 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012675 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012676 ValueDecl *D = Res.first;
12677 if (!D)
12678 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012679
Alexey Bataev60da77e2016-02-29 05:54:20 +000012680 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012681 QualType Type = D->getType();
12682 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012683
12684 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12685 // A variable that appears in a private clause must not have an incomplete
12686 // type or a reference type.
12687 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012688 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012689 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012690 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012691
12692 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12693 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012694 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012695 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012696 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012697
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012698 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012699 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012700 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012701 DSAStackTy::DSAVarData DVar =
12702 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012703 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012704 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012705 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012706 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12707 // A list item that specifies a given variable may not appear in more
12708 // than one clause on the same directive, except that a variable may be
12709 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012710 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12711 // A list item may appear in a firstprivate or lastprivate clause but not
12712 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012713 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012714 (isOpenMPDistributeDirective(CurrDir) ||
12715 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012716 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012717 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012718 << getOpenMPClauseName(DVar.CKind)
12719 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012720 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012721 continue;
12722 }
12723
12724 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12725 // in a Construct]
12726 // Variables with the predetermined data-sharing attributes may not be
12727 // listed in data-sharing attributes clauses, except for the cases
12728 // listed below. For these exceptions only, listing a predetermined
12729 // variable in a data-sharing attribute clause is allowed and overrides
12730 // the variable's predetermined data-sharing attributes.
12731 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12732 // in a Construct, C/C++, p.2]
12733 // Variables with const-qualified type having no mutable member may be
12734 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012735 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012736 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12737 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012738 << getOpenMPClauseName(DVar.CKind)
12739 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012740 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012741 continue;
12742 }
12743
12744 // OpenMP [2.9.3.4, Restrictions, p.2]
12745 // A list item that is private within a parallel region must not appear
12746 // in a firstprivate clause on a worksharing construct if any of the
12747 // worksharing regions arising from the worksharing construct ever bind
12748 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012749 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12750 // A list item that is private within a teams region must not appear in a
12751 // firstprivate clause on a distribute construct if any of the distribute
12752 // regions arising from the distribute construct ever bind to any of the
12753 // teams regions arising from the teams construct.
12754 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12755 // A list item that appears in a reduction clause of a teams construct
12756 // must not appear in a firstprivate clause on a distribute construct if
12757 // any of the distribute regions arising from the distribute construct
12758 // ever bind to any of the teams regions arising from the teams construct.
12759 if ((isOpenMPWorksharingDirective(CurrDir) ||
12760 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012761 !isOpenMPParallelDirective(CurrDir) &&
12762 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012763 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012764 if (DVar.CKind != OMPC_shared &&
12765 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012766 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012767 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012768 Diag(ELoc, diag::err_omp_required_access)
12769 << getOpenMPClauseName(OMPC_firstprivate)
12770 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012771 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012772 continue;
12773 }
12774 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012775 // OpenMP [2.9.3.4, Restrictions, p.3]
12776 // A list item that appears in a reduction clause of a parallel construct
12777 // must not appear in a firstprivate clause on a worksharing or task
12778 // construct if any of the worksharing or task regions arising from the
12779 // worksharing or task construct ever bind to any of the parallel regions
12780 // arising from the parallel construct.
12781 // OpenMP [2.9.3.4, Restrictions, p.4]
12782 // A list item that appears in a reduction clause in worksharing
12783 // construct must not appear in a firstprivate clause in a task construct
12784 // encountered during execution of any of the worksharing regions arising
12785 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012786 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012787 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012788 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12789 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012790 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012791 isOpenMPWorksharingDirective(K) ||
12792 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012793 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012794 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012795 if (DVar.CKind == OMPC_reduction &&
12796 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012797 isOpenMPWorksharingDirective(DVar.DKind) ||
12798 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012799 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12800 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012801 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012802 continue;
12803 }
12804 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012805
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012806 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12807 // A list item cannot appear in both a map clause and a data-sharing
12808 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012809 //
12810 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12811 // A list item cannot appear in both a map clause and a data-sharing
12812 // attribute clause on the same construct unless the construct is a
12813 // combined construct.
12814 if ((LangOpts.OpenMP <= 45 &&
12815 isOpenMPTargetExecutionDirective(CurrDir)) ||
12816 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012817 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012818 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012819 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012820 [&ConflictKind](
12821 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12822 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012823 ConflictKind = WhereFoundClauseKind;
12824 return true;
12825 })) {
12826 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012827 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012828 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012829 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012830 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012831 continue;
12832 }
12833 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012834 }
12835
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012836 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012837 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012838 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012839 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12840 << getOpenMPClauseName(OMPC_firstprivate) << Type
12841 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12842 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012843 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012844 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012845 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012846 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012847 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012848 continue;
12849 }
12850
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012851 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012852 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012853 buildVarDecl(*this, ELoc, Type, D->getName(),
12854 D->hasAttrs() ? &D->getAttrs() : nullptr,
12855 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012856 // Generate helper private variable and initialize it with the value of the
12857 // original variable. The address of the original variable is replaced by
12858 // the address of the new private variable in the CodeGen. This new variable
12859 // is not added to IdResolver, so the code in the OpenMP region uses
12860 // original variable for proper diagnostics and variable capturing.
12861 Expr *VDInitRefExpr = nullptr;
12862 // For arrays generate initializer for single element and replace it by the
12863 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012864 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012865 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012866 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012867 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012868 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012869 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012870 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12871 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012872 InitializedEntity Entity =
12873 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012874 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12875
12876 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12877 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12878 if (Result.isInvalid())
12879 VDPrivate->setInvalidDecl();
12880 else
12881 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012882 // Remove temp variable declaration.
12883 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012884 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012885 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12886 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012887 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12888 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012889 AddInitializerToDecl(VDPrivate,
12890 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012891 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012892 }
12893 if (VDPrivate->isInvalidDecl()) {
12894 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012895 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012896 diag::note_omp_task_predetermined_firstprivate_here);
12897 }
12898 continue;
12899 }
12900 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012901 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012902 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12903 RefExpr->getExprLoc());
12904 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012905 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012906 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012907 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012908 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012909 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012910 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012911 ExprCaptures.push_back(Ref->getDecl());
12912 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012913 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012914 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012915 Vars.push_back((VD || CurContext->isDependentContext())
12916 ? RefExpr->IgnoreParens()
12917 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012918 PrivateCopies.push_back(VDPrivateRefExpr);
12919 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012920 }
12921
Alexey Bataeved09d242014-05-28 05:53:51 +000012922 if (Vars.empty())
12923 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012924
12925 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012926 Vars, PrivateCopies, Inits,
12927 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012928}
12929
Alexander Musman1bb328c2014-06-04 13:06:39 +000012930OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12931 SourceLocation StartLoc,
12932 SourceLocation LParenLoc,
12933 SourceLocation EndLoc) {
12934 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012935 SmallVector<Expr *, 8> SrcExprs;
12936 SmallVector<Expr *, 8> DstExprs;
12937 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012938 SmallVector<Decl *, 4> ExprCaptures;
12939 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012940 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012941 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012942 SourceLocation ELoc;
12943 SourceRange ERange;
12944 Expr *SimpleRefExpr = RefExpr;
12945 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012946 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012947 // It will be analyzed later.
12948 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012949 SrcExprs.push_back(nullptr);
12950 DstExprs.push_back(nullptr);
12951 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012952 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012953 ValueDecl *D = Res.first;
12954 if (!D)
12955 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012956
Alexey Bataev74caaf22016-02-20 04:09:36 +000012957 QualType Type = D->getType();
12958 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012959
12960 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12961 // A variable that appears in a lastprivate clause must not have an
12962 // incomplete type or a reference type.
12963 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012964 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012965 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012966 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012967
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012968 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12969 // A variable that is privatized must not have a const-qualified type
12970 // unless it is of class type with a mutable member. This restriction does
12971 // not apply to the firstprivate clause.
12972 //
12973 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12974 // A variable that appears in a lastprivate clause must not have a
12975 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012976 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012977 continue;
12978
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012979 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012980 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12981 // in a Construct]
12982 // Variables with the predetermined data-sharing attributes may not be
12983 // listed in data-sharing attributes clauses, except for the cases
12984 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012985 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12986 // A list item may appear in a firstprivate or lastprivate clause but not
12987 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012988 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012989 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012990 (isOpenMPDistributeDirective(CurrDir) ||
12991 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012992 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12993 Diag(ELoc, diag::err_omp_wrong_dsa)
12994 << getOpenMPClauseName(DVar.CKind)
12995 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012996 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012997 continue;
12998 }
12999
Alexey Bataevf29276e2014-06-18 04:14:57 +000013000 // OpenMP [2.14.3.5, Restrictions, p.2]
13001 // A list item that is private within a parallel region, or that appears in
13002 // the reduction clause of a parallel construct, must not appear in a
13003 // lastprivate clause on a worksharing construct if any of the corresponding
13004 // worksharing regions ever binds to any of the corresponding parallel
13005 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013006 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013007 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013008 !isOpenMPParallelDirective(CurrDir) &&
13009 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013010 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013011 if (DVar.CKind != OMPC_shared) {
13012 Diag(ELoc, diag::err_omp_required_access)
13013 << getOpenMPClauseName(OMPC_lastprivate)
13014 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013015 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013016 continue;
13017 }
13018 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013019
Alexander Musman1bb328c2014-06-04 13:06:39 +000013020 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013021 // A variable of class type (or array thereof) that appears in a
13022 // lastprivate clause requires an accessible, unambiguous default
13023 // constructor for the class type, unless the list item is also specified
13024 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013025 // A variable of class type (or array thereof) that appears in a
13026 // lastprivate clause requires an accessible, unambiguous copy assignment
13027 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013028 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013029 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13030 Type.getUnqualifiedType(), ".lastprivate.src",
13031 D->hasAttrs() ? &D->getAttrs() : nullptr);
13032 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013033 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013034 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013035 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013036 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013037 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013038 // For arrays generate assignment operation for single element and replace
13039 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013040 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13041 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013042 if (AssignmentOp.isInvalid())
13043 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013044 AssignmentOp =
13045 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013046 if (AssignmentOp.isInvalid())
13047 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013048
Alexey Bataev74caaf22016-02-20 04:09:36 +000013049 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013050 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013051 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013052 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013053 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013054 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013055 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013056 ExprCaptures.push_back(Ref->getDecl());
13057 }
13058 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013059 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013060 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013061 ExprResult RefRes = DefaultLvalueConversion(Ref);
13062 if (!RefRes.isUsable())
13063 continue;
13064 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013065 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13066 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013067 if (!PostUpdateRes.isUsable())
13068 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013069 ExprPostUpdates.push_back(
13070 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013071 }
13072 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013073 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013074 Vars.push_back((VD || CurContext->isDependentContext())
13075 ? RefExpr->IgnoreParens()
13076 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013077 SrcExprs.push_back(PseudoSrcExpr);
13078 DstExprs.push_back(PseudoDstExpr);
13079 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013080 }
13081
13082 if (Vars.empty())
13083 return nullptr;
13084
13085 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013086 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013087 buildPreInits(Context, ExprCaptures),
13088 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013089}
13090
Alexey Bataev758e55e2013-09-06 18:03:48 +000013091OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13092 SourceLocation StartLoc,
13093 SourceLocation LParenLoc,
13094 SourceLocation EndLoc) {
13095 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013096 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013097 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013098 SourceLocation ELoc;
13099 SourceRange ERange;
13100 Expr *SimpleRefExpr = RefExpr;
13101 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013102 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013103 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013104 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013105 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013106 ValueDecl *D = Res.first;
13107 if (!D)
13108 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013109
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013110 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013111 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13112 // in a Construct]
13113 // Variables with the predetermined data-sharing attributes may not be
13114 // listed in data-sharing attributes clauses, except for the cases
13115 // listed below. For these exceptions only, listing a predetermined
13116 // variable in a data-sharing attribute clause is allowed and overrides
13117 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013118 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013119 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13120 DVar.RefExpr) {
13121 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13122 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013123 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013124 continue;
13125 }
13126
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013127 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013128 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013129 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013130 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013131 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13132 ? RefExpr->IgnoreParens()
13133 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013134 }
13135
Alexey Bataeved09d242014-05-28 05:53:51 +000013136 if (Vars.empty())
13137 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013138
13139 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13140}
13141
Alexey Bataevc5e02582014-06-16 07:08:35 +000013142namespace {
13143class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13144 DSAStackTy *Stack;
13145
13146public:
13147 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013148 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13149 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013150 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13151 return false;
13152 if (DVar.CKind != OMPC_unknown)
13153 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013154 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013155 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013156 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013157 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013158 }
13159 return false;
13160 }
13161 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013162 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013163 if (Child && Visit(Child))
13164 return true;
13165 }
13166 return false;
13167 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013168 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013169};
Alexey Bataev23b69422014-06-18 07:08:49 +000013170} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013171
Alexey Bataev60da77e2016-02-29 05:54:20 +000013172namespace {
13173// Transform MemberExpression for specified FieldDecl of current class to
13174// DeclRefExpr to specified OMPCapturedExprDecl.
13175class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13176 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013177 ValueDecl *Field = nullptr;
13178 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013179
13180public:
13181 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13182 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13183
13184 ExprResult TransformMemberExpr(MemberExpr *E) {
13185 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13186 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013187 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013188 return CapturedExpr;
13189 }
13190 return BaseTransform::TransformMemberExpr(E);
13191 }
13192 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13193};
13194} // namespace
13195
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013196template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013197static T filterLookupForUDReductionAndMapper(
13198 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013199 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013200 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013201 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013202 return Res;
13203 }
13204 }
13205 return T();
13206}
13207
Alexey Bataev43b90b72018-09-12 16:31:59 +000013208static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13209 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13210
13211 for (auto RD : D->redecls()) {
13212 // Don't bother with extra checks if we already know this one isn't visible.
13213 if (RD == D)
13214 continue;
13215
13216 auto ND = cast<NamedDecl>(RD);
13217 if (LookupResult::isVisible(SemaRef, ND))
13218 return ND;
13219 }
13220
13221 return nullptr;
13222}
13223
13224static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013225argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013226 SourceLocation Loc, QualType Ty,
13227 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13228 // Find all of the associated namespaces and classes based on the
13229 // arguments we have.
13230 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13231 Sema::AssociatedClassSet AssociatedClasses;
13232 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13233 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13234 AssociatedClasses);
13235
13236 // C++ [basic.lookup.argdep]p3:
13237 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13238 // and let Y be the lookup set produced by argument dependent
13239 // lookup (defined as follows). If X contains [...] then Y is
13240 // empty. Otherwise Y is the set of declarations found in the
13241 // namespaces associated with the argument types as described
13242 // below. The set of declarations found by the lookup of the name
13243 // is the union of X and Y.
13244 //
13245 // Here, we compute Y and add its members to the overloaded
13246 // candidate set.
13247 for (auto *NS : AssociatedNamespaces) {
13248 // When considering an associated namespace, the lookup is the
13249 // same as the lookup performed when the associated namespace is
13250 // used as a qualifier (3.4.3.2) except that:
13251 //
13252 // -- Any using-directives in the associated namespace are
13253 // ignored.
13254 //
13255 // -- Any namespace-scope friend functions declared in
13256 // associated classes are visible within their respective
13257 // namespaces even if they are not visible during an ordinary
13258 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013259 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013260 for (auto *D : R) {
13261 auto *Underlying = D;
13262 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13263 Underlying = USD->getTargetDecl();
13264
Michael Kruse4304e9d2019-02-19 16:38:20 +000013265 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13266 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013267 continue;
13268
13269 if (!SemaRef.isVisible(D)) {
13270 D = findAcceptableDecl(SemaRef, D);
13271 if (!D)
13272 continue;
13273 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13274 Underlying = USD->getTargetDecl();
13275 }
13276 Lookups.emplace_back();
13277 Lookups.back().addDecl(Underlying);
13278 }
13279 }
13280}
13281
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013282static ExprResult
13283buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13284 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13285 const DeclarationNameInfo &ReductionId, QualType Ty,
13286 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13287 if (ReductionIdScopeSpec.isInvalid())
13288 return ExprError();
13289 SmallVector<UnresolvedSet<8>, 4> Lookups;
13290 if (S) {
13291 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13292 Lookup.suppressDiagnostics();
13293 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013294 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013295 do {
13296 S = S->getParent();
13297 } while (S && !S->isDeclScope(D));
13298 if (S)
13299 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013300 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013301 Lookups.back().append(Lookup.begin(), Lookup.end());
13302 Lookup.clear();
13303 }
13304 } else if (auto *ULE =
13305 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13306 Lookups.push_back(UnresolvedSet<8>());
13307 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013308 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013309 if (D == PrevD)
13310 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013311 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013312 Lookups.back().addDecl(DRD);
13313 PrevD = D;
13314 }
13315 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013316 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13317 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013318 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013319 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013320 return !D->isInvalidDecl() &&
13321 (D->getType()->isDependentType() ||
13322 D->getType()->isInstantiationDependentType() ||
13323 D->getType()->containsUnexpandedParameterPack());
13324 })) {
13325 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013326 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013327 if (Set.empty())
13328 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013329 ResSet.append(Set.begin(), Set.end());
13330 // The last item marks the end of all declarations at the specified scope.
13331 ResSet.addDecl(Set[Set.size() - 1]);
13332 }
13333 return UnresolvedLookupExpr::Create(
13334 SemaRef.Context, /*NamingClass=*/nullptr,
13335 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13336 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13337 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013338 // Lookup inside the classes.
13339 // C++ [over.match.oper]p3:
13340 // For a unary operator @ with an operand of a type whose
13341 // cv-unqualified version is T1, and for a binary operator @ with
13342 // a left operand of a type whose cv-unqualified version is T1 and
13343 // a right operand of a type whose cv-unqualified version is T2,
13344 // three sets of candidate functions, designated member
13345 // candidates, non-member candidates and built-in candidates, are
13346 // constructed as follows:
13347 // -- If T1 is a complete class type or a class currently being
13348 // defined, the set of member candidates is the result of the
13349 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13350 // the set of member candidates is empty.
13351 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13352 Lookup.suppressDiagnostics();
13353 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13354 // Complete the type if it can be completed.
13355 // If the type is neither complete nor being defined, bail out now.
13356 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13357 TyRec->getDecl()->getDefinition()) {
13358 Lookup.clear();
13359 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13360 if (Lookup.empty()) {
13361 Lookups.emplace_back();
13362 Lookups.back().append(Lookup.begin(), Lookup.end());
13363 }
13364 }
13365 }
13366 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013367 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013368 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013369 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13370 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13371 if (!D->isInvalidDecl() &&
13372 SemaRef.Context.hasSameType(D->getType(), Ty))
13373 return D;
13374 return nullptr;
13375 }))
13376 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13377 VK_LValue, Loc);
13378 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013379 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13380 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13381 if (!D->isInvalidDecl() &&
13382 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13383 !Ty.isMoreQualifiedThan(D->getType()))
13384 return D;
13385 return nullptr;
13386 })) {
13387 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13388 /*DetectVirtual=*/false);
13389 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13390 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13391 VD->getType().getUnqualifiedType()))) {
13392 if (SemaRef.CheckBaseClassAccess(
13393 Loc, VD->getType(), Ty, Paths.front(),
13394 /*DiagID=*/0) != Sema::AR_inaccessible) {
13395 SemaRef.BuildBasePathArray(Paths, BasePath);
13396 return SemaRef.BuildDeclRefExpr(
13397 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13398 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013399 }
13400 }
13401 }
13402 }
13403 if (ReductionIdScopeSpec.isSet()) {
13404 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13405 return ExprError();
13406 }
13407 return ExprEmpty();
13408}
13409
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013410namespace {
13411/// Data for the reduction-based clauses.
13412struct ReductionData {
13413 /// List of original reduction items.
13414 SmallVector<Expr *, 8> Vars;
13415 /// List of private copies of the reduction items.
13416 SmallVector<Expr *, 8> Privates;
13417 /// LHS expressions for the reduction_op expressions.
13418 SmallVector<Expr *, 8> LHSs;
13419 /// RHS expressions for the reduction_op expressions.
13420 SmallVector<Expr *, 8> RHSs;
13421 /// Reduction operation expression.
13422 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013423 /// Taskgroup descriptors for the corresponding reduction items in
13424 /// in_reduction clauses.
13425 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013426 /// List of captures for clause.
13427 SmallVector<Decl *, 4> ExprCaptures;
13428 /// List of postupdate expressions.
13429 SmallVector<Expr *, 4> ExprPostUpdates;
13430 ReductionData() = delete;
13431 /// Reserves required memory for the reduction data.
13432 ReductionData(unsigned Size) {
13433 Vars.reserve(Size);
13434 Privates.reserve(Size);
13435 LHSs.reserve(Size);
13436 RHSs.reserve(Size);
13437 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013438 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013439 ExprCaptures.reserve(Size);
13440 ExprPostUpdates.reserve(Size);
13441 }
13442 /// Stores reduction item and reduction operation only (required for dependent
13443 /// reduction item).
13444 void push(Expr *Item, Expr *ReductionOp) {
13445 Vars.emplace_back(Item);
13446 Privates.emplace_back(nullptr);
13447 LHSs.emplace_back(nullptr);
13448 RHSs.emplace_back(nullptr);
13449 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013450 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013451 }
13452 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013453 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13454 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013455 Vars.emplace_back(Item);
13456 Privates.emplace_back(Private);
13457 LHSs.emplace_back(LHS);
13458 RHSs.emplace_back(RHS);
13459 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013460 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013461 }
13462};
13463} // namespace
13464
Alexey Bataeve3727102018-04-18 15:57:46 +000013465static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013466 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13467 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13468 const Expr *Length = OASE->getLength();
13469 if (Length == nullptr) {
13470 // For array sections of the form [1:] or [:], we would need to analyze
13471 // the lower bound...
13472 if (OASE->getColonLoc().isValid())
13473 return false;
13474
13475 // This is an array subscript which has implicit length 1!
13476 SingleElement = true;
13477 ArraySizes.push_back(llvm::APSInt::get(1));
13478 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013479 Expr::EvalResult Result;
13480 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013481 return false;
13482
Fangrui Song407659a2018-11-30 23:41:18 +000013483 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013484 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13485 ArraySizes.push_back(ConstantLengthValue);
13486 }
13487
13488 // Get the base of this array section and walk up from there.
13489 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13490
13491 // We require length = 1 for all array sections except the right-most to
13492 // guarantee that the memory region is contiguous and has no holes in it.
13493 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13494 Length = TempOASE->getLength();
13495 if (Length == nullptr) {
13496 // For array sections of the form [1:] or [:], we would need to analyze
13497 // the lower bound...
13498 if (OASE->getColonLoc().isValid())
13499 return false;
13500
13501 // This is an array subscript which has implicit length 1!
13502 ArraySizes.push_back(llvm::APSInt::get(1));
13503 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013504 Expr::EvalResult Result;
13505 if (!Length->EvaluateAsInt(Result, Context))
13506 return false;
13507
13508 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13509 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013510 return false;
13511
13512 ArraySizes.push_back(ConstantLengthValue);
13513 }
13514 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13515 }
13516
13517 // If we have a single element, we don't need to add the implicit lengths.
13518 if (!SingleElement) {
13519 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13520 // Has implicit length 1!
13521 ArraySizes.push_back(llvm::APSInt::get(1));
13522 Base = TempASE->getBase()->IgnoreParenImpCasts();
13523 }
13524 }
13525
13526 // This array section can be privatized as a single value or as a constant
13527 // sized array.
13528 return true;
13529}
13530
Alexey Bataeve3727102018-04-18 15:57:46 +000013531static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013532 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13533 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13534 SourceLocation ColonLoc, SourceLocation EndLoc,
13535 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013536 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013537 DeclarationName DN = ReductionId.getName();
13538 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013539 BinaryOperatorKind BOK = BO_Comma;
13540
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013541 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013542 // OpenMP [2.14.3.6, reduction clause]
13543 // C
13544 // reduction-identifier is either an identifier or one of the following
13545 // operators: +, -, *, &, |, ^, && and ||
13546 // C++
13547 // reduction-identifier is either an id-expression or one of the following
13548 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013549 switch (OOK) {
13550 case OO_Plus:
13551 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013552 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013553 break;
13554 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013555 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013556 break;
13557 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013558 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013559 break;
13560 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013561 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013562 break;
13563 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013564 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013565 break;
13566 case OO_AmpAmp:
13567 BOK = BO_LAnd;
13568 break;
13569 case OO_PipePipe:
13570 BOK = BO_LOr;
13571 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013572 case OO_New:
13573 case OO_Delete:
13574 case OO_Array_New:
13575 case OO_Array_Delete:
13576 case OO_Slash:
13577 case OO_Percent:
13578 case OO_Tilde:
13579 case OO_Exclaim:
13580 case OO_Equal:
13581 case OO_Less:
13582 case OO_Greater:
13583 case OO_LessEqual:
13584 case OO_GreaterEqual:
13585 case OO_PlusEqual:
13586 case OO_MinusEqual:
13587 case OO_StarEqual:
13588 case OO_SlashEqual:
13589 case OO_PercentEqual:
13590 case OO_CaretEqual:
13591 case OO_AmpEqual:
13592 case OO_PipeEqual:
13593 case OO_LessLess:
13594 case OO_GreaterGreater:
13595 case OO_LessLessEqual:
13596 case OO_GreaterGreaterEqual:
13597 case OO_EqualEqual:
13598 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013599 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013600 case OO_PlusPlus:
13601 case OO_MinusMinus:
13602 case OO_Comma:
13603 case OO_ArrowStar:
13604 case OO_Arrow:
13605 case OO_Call:
13606 case OO_Subscript:
13607 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013608 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013609 case NUM_OVERLOADED_OPERATORS:
13610 llvm_unreachable("Unexpected reduction identifier");
13611 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013612 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013613 if (II->isStr("max"))
13614 BOK = BO_GT;
13615 else if (II->isStr("min"))
13616 BOK = BO_LT;
13617 }
13618 break;
13619 }
13620 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013621 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013622 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013623 else
13624 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013625 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013626
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013627 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13628 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013629 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013630 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013631 // OpenMP [2.1, C/C++]
13632 // A list item is a variable or array section, subject to the restrictions
13633 // specified in Section 2.4 on page 42 and in each of the sections
13634 // describing clauses and directives for which a list appears.
13635 // OpenMP [2.14.3.3, Restrictions, p.1]
13636 // A variable that is part of another variable (as an array or
13637 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013638 if (!FirstIter && IR != ER)
13639 ++IR;
13640 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013641 SourceLocation ELoc;
13642 SourceRange ERange;
13643 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013644 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013645 /*AllowArraySection=*/true);
13646 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013647 // Try to find 'declare reduction' corresponding construct before using
13648 // builtin/overloaded operators.
13649 QualType Type = Context.DependentTy;
13650 CXXCastPath BasePath;
13651 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013652 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013653 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013654 Expr *ReductionOp = nullptr;
13655 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013656 (DeclareReductionRef.isUnset() ||
13657 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013658 ReductionOp = DeclareReductionRef.get();
13659 // It will be analyzed later.
13660 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013661 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013662 ValueDecl *D = Res.first;
13663 if (!D)
13664 continue;
13665
Alexey Bataev88202be2017-07-27 13:20:36 +000013666 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013667 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013668 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13669 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013670 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013671 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013672 } else if (OASE) {
13673 QualType BaseType =
13674 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13675 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013676 Type = ATy->getElementType();
13677 else
13678 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013679 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013680 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013681 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013682 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013683 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013684
Alexey Bataevc5e02582014-06-16 07:08:35 +000013685 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13686 // A variable that appears in a private clause must not have an incomplete
13687 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013688 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013689 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013690 continue;
13691 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013692 // A list item that appears in a reduction clause must not be
13693 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013694 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13695 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013696 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013697
13698 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013699 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13700 // If a list-item is a reference type then it must bind to the same object
13701 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013702 if (!ASE && !OASE) {
13703 if (VD) {
13704 VarDecl *VDDef = VD->getDefinition();
13705 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13706 DSARefChecker Check(Stack);
13707 if (Check.Visit(VDDef->getInit())) {
13708 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13709 << getOpenMPClauseName(ClauseKind) << ERange;
13710 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13711 continue;
13712 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013713 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013714 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013715
Alexey Bataevbc529672018-09-28 19:33:14 +000013716 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13717 // in a Construct]
13718 // Variables with the predetermined data-sharing attributes may not be
13719 // listed in data-sharing attributes clauses, except for the cases
13720 // listed below. For these exceptions only, listing a predetermined
13721 // variable in a data-sharing attribute clause is allowed and overrides
13722 // the variable's predetermined data-sharing attributes.
13723 // OpenMP [2.14.3.6, Restrictions, p.3]
13724 // Any number of reduction clauses can be specified on the directive,
13725 // but a list item can appear only once in the reduction clauses for that
13726 // directive.
13727 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13728 if (DVar.CKind == OMPC_reduction) {
13729 S.Diag(ELoc, diag::err_omp_once_referenced)
13730 << getOpenMPClauseName(ClauseKind);
13731 if (DVar.RefExpr)
13732 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13733 continue;
13734 }
13735 if (DVar.CKind != OMPC_unknown) {
13736 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13737 << getOpenMPClauseName(DVar.CKind)
13738 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013739 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013740 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013741 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013742
13743 // OpenMP [2.14.3.6, Restrictions, p.1]
13744 // A list item that appears in a reduction clause of a worksharing
13745 // construct must be shared in the parallel regions to which any of the
13746 // worksharing regions arising from the worksharing construct bind.
13747 if (isOpenMPWorksharingDirective(CurrDir) &&
13748 !isOpenMPParallelDirective(CurrDir) &&
13749 !isOpenMPTeamsDirective(CurrDir)) {
13750 DVar = Stack->getImplicitDSA(D, true);
13751 if (DVar.CKind != OMPC_shared) {
13752 S.Diag(ELoc, diag::err_omp_required_access)
13753 << getOpenMPClauseName(OMPC_reduction)
13754 << getOpenMPClauseName(OMPC_shared);
13755 reportOriginalDsa(S, Stack, D, DVar);
13756 continue;
13757 }
13758 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013759 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013760
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013761 // Try to find 'declare reduction' corresponding construct before using
13762 // builtin/overloaded operators.
13763 CXXCastPath BasePath;
13764 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013765 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013766 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13767 if (DeclareReductionRef.isInvalid())
13768 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013769 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013770 (DeclareReductionRef.isUnset() ||
13771 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013772 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013773 continue;
13774 }
13775 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13776 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013777 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013778 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013779 << Type << ReductionIdRange;
13780 continue;
13781 }
13782
13783 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13784 // The type of a list item that appears in a reduction clause must be valid
13785 // for the reduction-identifier. For a max or min reduction in C, the type
13786 // of the list item must be an allowed arithmetic data type: char, int,
13787 // float, double, or _Bool, possibly modified with long, short, signed, or
13788 // unsigned. For a max or min reduction in C++, the type of the list item
13789 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13790 // double, or bool, possibly modified with long, short, signed, or unsigned.
13791 if (DeclareReductionRef.isUnset()) {
13792 if ((BOK == BO_GT || BOK == BO_LT) &&
13793 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013794 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13795 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013796 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013797 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013798 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13799 VarDecl::DeclarationOnly;
13800 S.Diag(D->getLocation(),
13801 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013802 << D;
13803 }
13804 continue;
13805 }
13806 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013807 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013808 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13809 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013810 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013811 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13812 VarDecl::DeclarationOnly;
13813 S.Diag(D->getLocation(),
13814 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013815 << D;
13816 }
13817 continue;
13818 }
13819 }
13820
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013821 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013822 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13823 D->hasAttrs() ? &D->getAttrs() : nullptr);
13824 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13825 D->hasAttrs() ? &D->getAttrs() : nullptr);
13826 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013827
13828 // Try if we can determine constant lengths for all array sections and avoid
13829 // the VLA.
13830 bool ConstantLengthOASE = false;
13831 if (OASE) {
13832 bool SingleElement;
13833 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013834 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013835 Context, OASE, SingleElement, ArraySizes);
13836
13837 // If we don't have a single element, we must emit a constant array type.
13838 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013839 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013840 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13841 ArrayType::Normal,
13842 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013843 }
13844 }
13845
13846 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013847 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013848 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013849 if (!Context.getTargetInfo().isVLASupported()) {
13850 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13851 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13852 S.Diag(ELoc, diag::note_vla_unsupported);
13853 } else {
13854 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13855 S.targetDiag(ELoc, diag::note_vla_unsupported);
13856 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013857 continue;
13858 }
David Majnemer9d168222016-08-05 17:44:54 +000013859 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013860 // Create pseudo array type for private copy. The size for this array will
13861 // be generated during codegen.
13862 // For array subscripts or single variables Private Ty is the same as Type
13863 // (type of the variable or single array element).
13864 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013865 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013866 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013867 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013868 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013869 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013870 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013871 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013872 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013873 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013874 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13875 D->hasAttrs() ? &D->getAttrs() : nullptr,
13876 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013877 // Add initializer for private variable.
13878 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013879 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13880 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013881 if (DeclareReductionRef.isUsable()) {
13882 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13883 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13884 if (DRD->getInitializer()) {
13885 Init = DRDRef;
13886 RHSVD->setInit(DRDRef);
13887 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013888 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013889 } else {
13890 switch (BOK) {
13891 case BO_Add:
13892 case BO_Xor:
13893 case BO_Or:
13894 case BO_LOr:
13895 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13896 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013897 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013898 break;
13899 case BO_Mul:
13900 case BO_LAnd:
13901 if (Type->isScalarType() || Type->isAnyComplexType()) {
13902 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013903 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013904 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013905 break;
13906 case BO_And: {
13907 // '&' reduction op - initializer is '~0'.
13908 QualType OrigType = Type;
13909 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13910 Type = ComplexTy->getElementType();
13911 if (Type->isRealFloatingType()) {
13912 llvm::APFloat InitValue =
13913 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13914 /*isIEEE=*/true);
13915 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13916 Type, ELoc);
13917 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013918 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013919 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13920 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13921 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13922 }
13923 if (Init && OrigType->isAnyComplexType()) {
13924 // Init = 0xFFFF + 0xFFFFi;
13925 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013926 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013927 }
13928 Type = OrigType;
13929 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013930 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013931 case BO_LT:
13932 case BO_GT: {
13933 // 'min' reduction op - initializer is 'Largest representable number in
13934 // the reduction list item type'.
13935 // 'max' reduction op - initializer is 'Least representable number in
13936 // the reduction list item type'.
13937 if (Type->isIntegerType() || Type->isPointerType()) {
13938 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013939 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013940 QualType IntTy =
13941 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13942 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013943 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13944 : llvm::APInt::getMinValue(Size)
13945 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13946 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013947 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13948 if (Type->isPointerType()) {
13949 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013950 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013951 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013952 if (CastExpr.isInvalid())
13953 continue;
13954 Init = CastExpr.get();
13955 }
13956 } else if (Type->isRealFloatingType()) {
13957 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13958 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13959 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13960 Type, ELoc);
13961 }
13962 break;
13963 }
13964 case BO_PtrMemD:
13965 case BO_PtrMemI:
13966 case BO_MulAssign:
13967 case BO_Div:
13968 case BO_Rem:
13969 case BO_Sub:
13970 case BO_Shl:
13971 case BO_Shr:
13972 case BO_LE:
13973 case BO_GE:
13974 case BO_EQ:
13975 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013976 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013977 case BO_AndAssign:
13978 case BO_XorAssign:
13979 case BO_OrAssign:
13980 case BO_Assign:
13981 case BO_AddAssign:
13982 case BO_SubAssign:
13983 case BO_DivAssign:
13984 case BO_RemAssign:
13985 case BO_ShlAssign:
13986 case BO_ShrAssign:
13987 case BO_Comma:
13988 llvm_unreachable("Unexpected reduction operation");
13989 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013990 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013991 if (Init && DeclareReductionRef.isUnset())
13992 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13993 else if (!Init)
13994 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013995 if (RHSVD->isInvalidDecl())
13996 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013997 if (!RHSVD->hasInit() &&
13998 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013999 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14000 << Type << ReductionIdRange;
14001 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14002 VarDecl::DeclarationOnly;
14003 S.Diag(D->getLocation(),
14004 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014005 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014006 continue;
14007 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014008 // Store initializer for single element in private copy. Will be used during
14009 // codegen.
14010 PrivateVD->setInit(RHSVD->getInit());
14011 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014012 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014013 ExprResult ReductionOp;
14014 if (DeclareReductionRef.isUsable()) {
14015 QualType RedTy = DeclareReductionRef.get()->getType();
14016 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014017 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14018 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014019 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014020 LHS = S.DefaultLvalueConversion(LHS.get());
14021 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014022 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14023 CK_UncheckedDerivedToBase, LHS.get(),
14024 &BasePath, LHS.get()->getValueKind());
14025 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14026 CK_UncheckedDerivedToBase, RHS.get(),
14027 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014028 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014029 FunctionProtoType::ExtProtoInfo EPI;
14030 QualType Params[] = {PtrRedTy, PtrRedTy};
14031 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14032 auto *OVE = new (Context) OpaqueValueExpr(
14033 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014034 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014035 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014036 ReductionOp =
14037 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014038 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014039 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014040 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014041 if (ReductionOp.isUsable()) {
14042 if (BOK != BO_LT && BOK != BO_GT) {
14043 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014044 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014045 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014046 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014047 auto *ConditionalOp = new (Context)
14048 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14049 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014050 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014051 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014052 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014053 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014054 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014055 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14056 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014057 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014058 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014059 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014060 }
14061
Alexey Bataevfa312f32017-07-21 18:48:21 +000014062 // OpenMP [2.15.4.6, Restrictions, p.2]
14063 // A list item that appears in an in_reduction clause of a task construct
14064 // must appear in a task_reduction clause of a construct associated with a
14065 // taskgroup region that includes the participating task in its taskgroup
14066 // set. The construct associated with the innermost region that meets this
14067 // condition must specify the same reduction-identifier as the in_reduction
14068 // clause.
14069 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014070 SourceRange ParentSR;
14071 BinaryOperatorKind ParentBOK;
14072 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014073 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014074 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014075 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14076 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014077 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014078 Stack->getTopMostTaskgroupReductionData(
14079 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014080 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14081 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14082 if (!IsParentBOK && !IsParentReductionOp) {
14083 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14084 continue;
14085 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014086 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14087 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14088 IsParentReductionOp) {
14089 bool EmitError = true;
14090 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14091 llvm::FoldingSetNodeID RedId, ParentRedId;
14092 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14093 DeclareReductionRef.get()->Profile(RedId, Context,
14094 /*Canonical=*/true);
14095 EmitError = RedId != ParentRedId;
14096 }
14097 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014098 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014099 diag::err_omp_reduction_identifier_mismatch)
14100 << ReductionIdRange << RefExpr->getSourceRange();
14101 S.Diag(ParentSR.getBegin(),
14102 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014103 << ParentSR
14104 << (IsParentBOK ? ParentBOKDSA.RefExpr
14105 : ParentReductionOpDSA.RefExpr)
14106 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014107 continue;
14108 }
14109 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014110 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14111 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014112 }
14113
Alexey Bataev60da77e2016-02-29 05:54:20 +000014114 DeclRefExpr *Ref = nullptr;
14115 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014116 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014117 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014118 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014119 VarsExpr =
14120 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14121 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014122 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014123 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014124 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014125 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014126 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014127 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014128 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014129 if (!RefRes.isUsable())
14130 continue;
14131 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014132 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14133 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014134 if (!PostUpdateRes.isUsable())
14135 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014136 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14137 Stack->getCurrentDirective() == OMPD_taskgroup) {
14138 S.Diag(RefExpr->getExprLoc(),
14139 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014140 << RefExpr->getSourceRange();
14141 continue;
14142 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014143 RD.ExprPostUpdates.emplace_back(
14144 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014145 }
14146 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014147 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014148 // All reduction items are still marked as reduction (to do not increase
14149 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014150 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014151 if (CurrDir == OMPD_taskgroup) {
14152 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014153 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14154 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014155 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014156 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014157 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014158 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14159 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014160 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014161 return RD.Vars.empty();
14162}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014163
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014164OMPClause *Sema::ActOnOpenMPReductionClause(
14165 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14166 SourceLocation ColonLoc, SourceLocation EndLoc,
14167 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14168 ArrayRef<Expr *> UnresolvedReductions) {
14169 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014170 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014171 StartLoc, LParenLoc, ColonLoc, EndLoc,
14172 ReductionIdScopeSpec, ReductionId,
14173 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014174 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014175
Alexey Bataevc5e02582014-06-16 07:08:35 +000014176 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014177 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14178 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14179 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14180 buildPreInits(Context, RD.ExprCaptures),
14181 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014182}
14183
Alexey Bataev169d96a2017-07-18 20:17:46 +000014184OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14185 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14186 SourceLocation ColonLoc, SourceLocation EndLoc,
14187 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14188 ArrayRef<Expr *> UnresolvedReductions) {
14189 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014190 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14191 StartLoc, LParenLoc, ColonLoc, EndLoc,
14192 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014193 UnresolvedReductions, RD))
14194 return nullptr;
14195
14196 return OMPTaskReductionClause::Create(
14197 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14198 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14199 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14200 buildPreInits(Context, RD.ExprCaptures),
14201 buildPostUpdate(*this, RD.ExprPostUpdates));
14202}
14203
Alexey Bataevfa312f32017-07-21 18:48:21 +000014204OMPClause *Sema::ActOnOpenMPInReductionClause(
14205 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14206 SourceLocation ColonLoc, SourceLocation EndLoc,
14207 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14208 ArrayRef<Expr *> UnresolvedReductions) {
14209 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014210 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014211 StartLoc, LParenLoc, ColonLoc, EndLoc,
14212 ReductionIdScopeSpec, ReductionId,
14213 UnresolvedReductions, RD))
14214 return nullptr;
14215
14216 return OMPInReductionClause::Create(
14217 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14218 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014219 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014220 buildPreInits(Context, RD.ExprCaptures),
14221 buildPostUpdate(*this, RD.ExprPostUpdates));
14222}
14223
Alexey Bataevecba70f2016-04-12 11:02:11 +000014224bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14225 SourceLocation LinLoc) {
14226 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14227 LinKind == OMPC_LINEAR_unknown) {
14228 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14229 return true;
14230 }
14231 return false;
14232}
14233
Alexey Bataeve3727102018-04-18 15:57:46 +000014234bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014235 OpenMPLinearClauseKind LinKind,
14236 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014237 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014238 // A variable must not have an incomplete type or a reference type.
14239 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14240 return true;
14241 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14242 !Type->isReferenceType()) {
14243 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14244 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14245 return true;
14246 }
14247 Type = Type.getNonReferenceType();
14248
Joel E. Dennybae586f2019-01-04 22:12:13 +000014249 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14250 // A variable that is privatized must not have a const-qualified type
14251 // unless it is of class type with a mutable member. This restriction does
14252 // not apply to the firstprivate clause.
14253 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014254 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014255
14256 // A list item must be of integral or pointer type.
14257 Type = Type.getUnqualifiedType().getCanonicalType();
14258 const auto *Ty = Type.getTypePtrOrNull();
14259 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
14260 !Ty->isPointerType())) {
14261 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14262 if (D) {
14263 bool IsDecl =
14264 !VD ||
14265 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14266 Diag(D->getLocation(),
14267 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14268 << D;
14269 }
14270 return true;
14271 }
14272 return false;
14273}
14274
Alexey Bataev182227b2015-08-20 10:54:39 +000014275OMPClause *Sema::ActOnOpenMPLinearClause(
14276 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14277 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14278 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014279 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014280 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014281 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014282 SmallVector<Decl *, 4> ExprCaptures;
14283 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014284 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014285 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014286 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014287 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014288 SourceLocation ELoc;
14289 SourceRange ERange;
14290 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014291 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014292 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014293 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014294 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014295 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014296 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014297 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014298 ValueDecl *D = Res.first;
14299 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014300 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014301
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014302 QualType Type = D->getType();
14303 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014304
14305 // OpenMP [2.14.3.7, linear clause]
14306 // A list-item cannot appear in more than one linear clause.
14307 // A list-item that appears in a linear clause cannot appear in any
14308 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014309 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014310 if (DVar.RefExpr) {
14311 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14312 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014313 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014314 continue;
14315 }
14316
Alexey Bataevecba70f2016-04-12 11:02:11 +000014317 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014318 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014319 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014320
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014321 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014322 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014323 buildVarDecl(*this, ELoc, Type, D->getName(),
14324 D->hasAttrs() ? &D->getAttrs() : nullptr,
14325 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014326 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014327 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014328 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014329 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014330 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014331 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014332 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014333 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014334 ExprCaptures.push_back(Ref->getDecl());
14335 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14336 ExprResult RefRes = DefaultLvalueConversion(Ref);
14337 if (!RefRes.isUsable())
14338 continue;
14339 ExprResult PostUpdateRes =
14340 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14341 SimpleRefExpr, RefRes.get());
14342 if (!PostUpdateRes.isUsable())
14343 continue;
14344 ExprPostUpdates.push_back(
14345 IgnoredValueConversions(PostUpdateRes.get()).get());
14346 }
14347 }
14348 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014349 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014350 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014351 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014352 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014353 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014354 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014355 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014356
14357 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014358 Vars.push_back((VD || CurContext->isDependentContext())
14359 ? RefExpr->IgnoreParens()
14360 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014361 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014362 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014363 }
14364
14365 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014366 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014367
14368 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014369 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014370 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14371 !Step->isInstantiationDependent() &&
14372 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014373 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014374 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014375 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014376 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014377 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014378
Alexander Musman3276a272015-03-21 10:12:56 +000014379 // Build var to save the step value.
14380 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014381 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014382 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014383 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014384 ExprResult CalcStep =
14385 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014386 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014387
Alexander Musman8dba6642014-04-22 13:09:42 +000014388 // Warn about zero linear step (it would be probably better specified as
14389 // making corresponding variables 'const').
14390 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014391 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14392 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014393 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14394 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014395 if (!IsConstant && CalcStep.isUsable()) {
14396 // Calculate the step beforehand instead of doing this on each iteration.
14397 // (This is not used if the number of iterations may be kfold-ed).
14398 CalcStepExpr = CalcStep.get();
14399 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014400 }
14401
Alexey Bataev182227b2015-08-20 10:54:39 +000014402 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14403 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014404 StepExpr, CalcStepExpr,
14405 buildPreInits(Context, ExprCaptures),
14406 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014407}
14408
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014409static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14410 Expr *NumIterations, Sema &SemaRef,
14411 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014412 // Walk the vars and build update/final expressions for the CodeGen.
14413 SmallVector<Expr *, 8> Updates;
14414 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014415 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014416 Expr *Step = Clause.getStep();
14417 Expr *CalcStep = Clause.getCalcStep();
14418 // OpenMP [2.14.3.7, linear clause]
14419 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014420 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014421 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014422 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014423 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14424 bool HasErrors = false;
14425 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014426 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014427 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14428 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014429 SourceLocation ELoc;
14430 SourceRange ERange;
14431 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014432 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014433 ValueDecl *D = Res.first;
14434 if (Res.second || !D) {
14435 Updates.push_back(nullptr);
14436 Finals.push_back(nullptr);
14437 HasErrors = true;
14438 continue;
14439 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014440 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014441 // OpenMP [2.15.11, distribute simd Construct]
14442 // A list item may not appear in a linear clause, unless it is the loop
14443 // iteration variable.
14444 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14445 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14446 SemaRef.Diag(ELoc,
14447 diag::err_omp_linear_distribute_var_non_loop_iteration);
14448 Updates.push_back(nullptr);
14449 Finals.push_back(nullptr);
14450 HasErrors = true;
14451 continue;
14452 }
Alexander Musman3276a272015-03-21 10:12:56 +000014453 Expr *InitExpr = *CurInit;
14454
14455 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014456 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014457 Expr *CapturedRef;
14458 if (LinKind == OMPC_LINEAR_uval)
14459 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14460 else
14461 CapturedRef =
14462 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14463 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14464 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014465
14466 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014467 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014468 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014469 Update = buildCounterUpdate(
14470 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14471 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014472 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014473 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014474 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014475 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014476
14477 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014478 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014479 if (!Info.first)
14480 Final =
14481 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014482 InitExpr, NumIterations, Step, /*Subtract=*/false,
14483 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014484 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014485 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014486 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014487 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014488
Alexander Musman3276a272015-03-21 10:12:56 +000014489 if (!Update.isUsable() || !Final.isUsable()) {
14490 Updates.push_back(nullptr);
14491 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014492 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014493 HasErrors = true;
14494 } else {
14495 Updates.push_back(Update.get());
14496 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014497 if (!Info.first)
14498 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014499 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014500 ++CurInit;
14501 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014502 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014503 if (Expr *S = Clause.getStep())
14504 UsedExprs.push_back(S);
14505 // Fill the remaining part with the nullptr.
14506 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014507 Clause.setUpdates(Updates);
14508 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014509 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014510 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014511}
14512
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014513OMPClause *Sema::ActOnOpenMPAlignedClause(
14514 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14515 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014516 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014517 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014518 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14519 SourceLocation ELoc;
14520 SourceRange ERange;
14521 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014522 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014523 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014524 // It will be analyzed later.
14525 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014526 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014527 ValueDecl *D = Res.first;
14528 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014529 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014530
Alexey Bataev1efd1662016-03-29 10:59:56 +000014531 QualType QType = D->getType();
14532 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014533
14534 // OpenMP [2.8.1, simd construct, Restrictions]
14535 // The type of list items appearing in the aligned clause must be
14536 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014537 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014538 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014539 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014540 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014541 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014542 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014543 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014544 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014545 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014546 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014547 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014548 continue;
14549 }
14550
14551 // OpenMP [2.8.1, simd construct, Restrictions]
14552 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014553 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000014554 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014555 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14556 << getOpenMPClauseName(OMPC_aligned);
14557 continue;
14558 }
14559
Alexey Bataev1efd1662016-03-29 10:59:56 +000014560 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014561 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014562 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14563 Vars.push_back(DefaultFunctionArrayConversion(
14564 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14565 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014566 }
14567
14568 // OpenMP [2.8.1, simd construct, Description]
14569 // The parameter of the aligned clause, alignment, must be a constant
14570 // positive integer expression.
14571 // If no optional parameter is specified, implementation-defined default
14572 // alignments for SIMD instructions on the target platforms are assumed.
14573 if (Alignment != nullptr) {
14574 ExprResult AlignResult =
14575 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14576 if (AlignResult.isInvalid())
14577 return nullptr;
14578 Alignment = AlignResult.get();
14579 }
14580 if (Vars.empty())
14581 return nullptr;
14582
14583 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14584 EndLoc, Vars, Alignment);
14585}
14586
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014587OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14588 SourceLocation StartLoc,
14589 SourceLocation LParenLoc,
14590 SourceLocation EndLoc) {
14591 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014592 SmallVector<Expr *, 8> SrcExprs;
14593 SmallVector<Expr *, 8> DstExprs;
14594 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014595 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014596 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14597 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014598 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014599 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014600 SrcExprs.push_back(nullptr);
14601 DstExprs.push_back(nullptr);
14602 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014603 continue;
14604 }
14605
Alexey Bataeved09d242014-05-28 05:53:51 +000014606 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014607 // OpenMP [2.1, C/C++]
14608 // A list item is a variable name.
14609 // OpenMP [2.14.4.1, Restrictions, p.1]
14610 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014611 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014612 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014613 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14614 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014615 continue;
14616 }
14617
14618 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014619 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014620
14621 QualType Type = VD->getType();
14622 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14623 // It will be analyzed later.
14624 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014625 SrcExprs.push_back(nullptr);
14626 DstExprs.push_back(nullptr);
14627 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014628 continue;
14629 }
14630
14631 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14632 // A list item that appears in a copyin clause must be threadprivate.
14633 if (!DSAStack->isThreadPrivate(VD)) {
14634 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014635 << getOpenMPClauseName(OMPC_copyin)
14636 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014637 continue;
14638 }
14639
14640 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14641 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014642 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014643 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014644 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14645 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014646 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014647 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014648 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014649 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014650 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014651 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014652 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014653 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014654 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014655 // For arrays generate assignment operation for single element and replace
14656 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014657 ExprResult AssignmentOp =
14658 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14659 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014660 if (AssignmentOp.isInvalid())
14661 continue;
14662 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014663 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014664 if (AssignmentOp.isInvalid())
14665 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014666
14667 DSAStack->addDSA(VD, DE, OMPC_copyin);
14668 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014669 SrcExprs.push_back(PseudoSrcExpr);
14670 DstExprs.push_back(PseudoDstExpr);
14671 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014672 }
14673
Alexey Bataeved09d242014-05-28 05:53:51 +000014674 if (Vars.empty())
14675 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014676
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014677 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14678 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014679}
14680
Alexey Bataevbae9a792014-06-27 10:37:06 +000014681OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14682 SourceLocation StartLoc,
14683 SourceLocation LParenLoc,
14684 SourceLocation EndLoc) {
14685 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014686 SmallVector<Expr *, 8> SrcExprs;
14687 SmallVector<Expr *, 8> DstExprs;
14688 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014689 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014690 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14691 SourceLocation ELoc;
14692 SourceRange ERange;
14693 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014694 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014695 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014696 // It will be analyzed later.
14697 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014698 SrcExprs.push_back(nullptr);
14699 DstExprs.push_back(nullptr);
14700 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014701 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014702 ValueDecl *D = Res.first;
14703 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014704 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014705
Alexey Bataeve122da12016-03-17 10:50:17 +000014706 QualType Type = D->getType();
14707 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014708
14709 // OpenMP [2.14.4.2, Restrictions, p.2]
14710 // A list item that appears in a copyprivate clause may not appear in a
14711 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014712 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014713 DSAStackTy::DSAVarData DVar =
14714 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014715 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14716 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014717 Diag(ELoc, diag::err_omp_wrong_dsa)
14718 << getOpenMPClauseName(DVar.CKind)
14719 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014720 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014721 continue;
14722 }
14723
14724 // OpenMP [2.11.4.2, Restrictions, p.1]
14725 // All list items that appear in a copyprivate clause must be either
14726 // threadprivate or private in the enclosing context.
14727 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014728 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014729 if (DVar.CKind == OMPC_shared) {
14730 Diag(ELoc, diag::err_omp_required_access)
14731 << getOpenMPClauseName(OMPC_copyprivate)
14732 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014733 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014734 continue;
14735 }
14736 }
14737 }
14738
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014739 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014740 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014741 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014742 << getOpenMPClauseName(OMPC_copyprivate) << Type
14743 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014744 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014745 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014746 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014747 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014748 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014749 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014750 continue;
14751 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014752
Alexey Bataevbae9a792014-06-27 10:37:06 +000014753 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14754 // A variable of class type (or array thereof) that appears in a
14755 // copyin clause requires an accessible, unambiguous copy assignment
14756 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014757 Type = Context.getBaseElementType(Type.getNonReferenceType())
14758 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014759 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014760 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014761 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014762 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14763 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014764 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014765 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014766 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14767 ExprResult AssignmentOp = BuildBinOp(
14768 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014769 if (AssignmentOp.isInvalid())
14770 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014771 AssignmentOp =
14772 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014773 if (AssignmentOp.isInvalid())
14774 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014775
14776 // No need to mark vars as copyprivate, they are already threadprivate or
14777 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014778 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014779 Vars.push_back(
14780 VD ? RefExpr->IgnoreParens()
14781 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014782 SrcExprs.push_back(PseudoSrcExpr);
14783 DstExprs.push_back(PseudoDstExpr);
14784 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014785 }
14786
14787 if (Vars.empty())
14788 return nullptr;
14789
Alexey Bataeva63048e2015-03-23 06:18:07 +000014790 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14791 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014792}
14793
Alexey Bataev6125da92014-07-21 11:26:11 +000014794OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14795 SourceLocation StartLoc,
14796 SourceLocation LParenLoc,
14797 SourceLocation EndLoc) {
14798 if (VarList.empty())
14799 return nullptr;
14800
14801 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14802}
Alexey Bataevdea47612014-07-23 07:46:59 +000014803
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014804OMPClause *
14805Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14806 SourceLocation DepLoc, SourceLocation ColonLoc,
14807 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14808 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014809 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014810 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014811 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014812 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014813 return nullptr;
14814 }
14815 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014816 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14817 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014818 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014819 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014820 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14821 /*Last=*/OMPC_DEPEND_unknown, Except)
14822 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014823 return nullptr;
14824 }
14825 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014826 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014827 llvm::APSInt DepCounter(/*BitWidth=*/32);
14828 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014829 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14830 if (const Expr *OrderedCountExpr =
14831 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014832 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14833 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014834 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014835 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014836 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014837 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14838 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14839 // It will be analyzed later.
14840 Vars.push_back(RefExpr);
14841 continue;
14842 }
14843
14844 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014845 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014846 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014847 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014848 DepCounter >= TotalDepCount) {
14849 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14850 continue;
14851 }
14852 ++DepCounter;
14853 // OpenMP [2.13.9, Summary]
14854 // depend(dependence-type : vec), where dependence-type is:
14855 // 'sink' and where vec is the iteration vector, which has the form:
14856 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14857 // where n is the value specified by the ordered clause in the loop
14858 // directive, xi denotes the loop iteration variable of the i-th nested
14859 // loop associated with the loop directive, and di is a constant
14860 // non-negative integer.
14861 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014862 // It will be analyzed later.
14863 Vars.push_back(RefExpr);
14864 continue;
14865 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014866 SimpleExpr = SimpleExpr->IgnoreImplicit();
14867 OverloadedOperatorKind OOK = OO_None;
14868 SourceLocation OOLoc;
14869 Expr *LHS = SimpleExpr;
14870 Expr *RHS = nullptr;
14871 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14872 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14873 OOLoc = BO->getOperatorLoc();
14874 LHS = BO->getLHS()->IgnoreParenImpCasts();
14875 RHS = BO->getRHS()->IgnoreParenImpCasts();
14876 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14877 OOK = OCE->getOperator();
14878 OOLoc = OCE->getOperatorLoc();
14879 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14880 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14881 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14882 OOK = MCE->getMethodDecl()
14883 ->getNameInfo()
14884 .getName()
14885 .getCXXOverloadedOperator();
14886 OOLoc = MCE->getCallee()->getExprLoc();
14887 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14888 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014889 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014890 SourceLocation ELoc;
14891 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014892 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014893 if (Res.second) {
14894 // It will be analyzed later.
14895 Vars.push_back(RefExpr);
14896 }
14897 ValueDecl *D = Res.first;
14898 if (!D)
14899 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014900
Alexey Bataev17daedf2018-02-15 22:42:57 +000014901 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14902 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14903 continue;
14904 }
14905 if (RHS) {
14906 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14907 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14908 if (RHSRes.isInvalid())
14909 continue;
14910 }
14911 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014912 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014913 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014914 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014915 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014916 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014917 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14918 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014919 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014920 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014921 continue;
14922 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014923 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014924 } else {
14925 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14926 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14927 (ASE &&
14928 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14929 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14930 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14931 << RefExpr->getSourceRange();
14932 continue;
14933 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014934
14935 ExprResult Res;
14936 {
14937 Sema::TentativeAnalysisScope Trap(*this);
14938 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14939 RefExpr->IgnoreParenImpCasts());
14940 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014941 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14942 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14943 << RefExpr->getSourceRange();
14944 continue;
14945 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014946 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014947 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014948 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014949
14950 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14951 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014952 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014953 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14954 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14955 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14956 }
14957 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14958 Vars.empty())
14959 return nullptr;
14960
Alexey Bataev8b427062016-05-25 12:36:08 +000014961 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014962 DepKind, DepLoc, ColonLoc, Vars,
14963 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014964 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14965 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014966 DSAStack->addDoacrossDependClause(C, OpsOffs);
14967 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014968}
Michael Wonge710d542015-08-07 16:16:36 +000014969
14970OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14971 SourceLocation LParenLoc,
14972 SourceLocation EndLoc) {
14973 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014974 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014975
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014976 // OpenMP [2.9.1, Restrictions]
14977 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014978 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014979 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014980 return nullptr;
14981
Alexey Bataev931e19b2017-10-02 16:32:39 +000014982 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014983 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050014984 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000014985 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014986 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014987 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014988 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14989 HelperValStmt = buildPreInits(Context, Captures);
14990 }
14991
Alexey Bataev8451efa2018-01-15 19:06:12 +000014992 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14993 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014994}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014995
Alexey Bataeve3727102018-04-18 15:57:46 +000014996static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014997 DSAStackTy *Stack, QualType QTy,
14998 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014999 NamedDecl *ND;
15000 if (QTy->isIncompleteType(&ND)) {
15001 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15002 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015003 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015004 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015005 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015006 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015007 return true;
15008}
15009
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015010/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015011/// (array section or array subscript) does NOT specify the whole size of the
15012/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015013static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015014 const Expr *E,
15015 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015016 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015017
15018 // If this is an array subscript, it refers to the whole size if the size of
15019 // the dimension is constant and equals 1. Also, an array section assumes the
15020 // format of an array subscript if no colon is used.
15021 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015022 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015023 return ATy->getSize().getSExtValue() != 1;
15024 // Size can't be evaluated statically.
15025 return false;
15026 }
15027
15028 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015029 const Expr *LowerBound = OASE->getLowerBound();
15030 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015031
15032 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015033 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015034 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015035 Expr::EvalResult Result;
15036 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015037 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015038
15039 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015040 if (ConstLowerBound.getSExtValue())
15041 return true;
15042 }
15043
15044 // If we don't have a length we covering the whole dimension.
15045 if (!Length)
15046 return false;
15047
15048 // If the base is a pointer, we don't have a way to get the size of the
15049 // pointee.
15050 if (BaseQTy->isPointerType())
15051 return false;
15052
15053 // We can only check if the length is the same as the size of the dimension
15054 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015055 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015056 if (!CATy)
15057 return false;
15058
Fangrui Song407659a2018-11-30 23:41:18 +000015059 Expr::EvalResult Result;
15060 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015061 return false; // Can't get the integer value as a constant.
15062
Fangrui Song407659a2018-11-30 23:41:18 +000015063 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015064 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15065}
15066
15067// Return true if it can be proven that the provided array expression (array
15068// section or array subscript) does NOT specify a single element of the array
15069// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015070static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015071 const Expr *E,
15072 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015073 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015074
15075 // An array subscript always refer to a single element. Also, an array section
15076 // assumes the format of an array subscript if no colon is used.
15077 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15078 return false;
15079
15080 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015081 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015082
15083 // If we don't have a length we have to check if the array has unitary size
15084 // for this dimension. Also, we should always expect a length if the base type
15085 // is pointer.
15086 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015087 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015088 return ATy->getSize().getSExtValue() != 1;
15089 // We cannot assume anything.
15090 return false;
15091 }
15092
15093 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015094 Expr::EvalResult Result;
15095 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015096 return false; // Can't get the integer value as a constant.
15097
Fangrui Song407659a2018-11-30 23:41:18 +000015098 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015099 return ConstLength.getSExtValue() != 1;
15100}
15101
Samuel Antao661c0902016-05-26 17:39:58 +000015102// Return the expression of the base of the mappable expression or null if it
15103// cannot be determined and do all the necessary checks to see if the expression
15104// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015105// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015106static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015107 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015108 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015109 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015110 SourceLocation ELoc = E->getExprLoc();
15111 SourceRange ERange = E->getSourceRange();
15112
15113 // The base of elements of list in a map clause have to be either:
15114 // - a reference to variable or field.
15115 // - a member expression.
15116 // - an array expression.
15117 //
15118 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15119 // reference to 'r'.
15120 //
15121 // If we have:
15122 //
15123 // struct SS {
15124 // Bla S;
15125 // foo() {
15126 // #pragma omp target map (S.Arr[:12]);
15127 // }
15128 // }
15129 //
15130 // We want to retrieve the member expression 'this->S';
15131
Alexey Bataeve3727102018-04-18 15:57:46 +000015132 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015133
Samuel Antao5de996e2016-01-22 20:21:36 +000015134 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15135 // If a list item is an array section, it must specify contiguous storage.
15136 //
15137 // For this restriction it is sufficient that we make sure only references
15138 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015139 // exist except in the rightmost expression (unless they cover the whole
15140 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015141 //
15142 // r.ArrS[3:5].Arr[6:7]
15143 //
15144 // r.ArrS[3:5].x
15145 //
15146 // but these would be valid:
15147 // r.ArrS[3].Arr[6:7]
15148 //
15149 // r.ArrS[3].x
15150
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015151 bool AllowUnitySizeArraySection = true;
15152 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015153
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015154 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015155 E = E->IgnoreParenImpCasts();
15156
15157 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15158 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015159 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015160
15161 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015162
15163 // If we got a reference to a declaration, we should not expect any array
15164 // section before that.
15165 AllowUnitySizeArraySection = false;
15166 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015167
15168 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015169 CurComponents.emplace_back(CurE, CurE->getDecl());
15170 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015171 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015172
15173 if (isa<CXXThisExpr>(BaseE))
15174 // We found a base expression: this->Val.
15175 RelevantExpr = CurE;
15176 else
15177 E = BaseE;
15178
15179 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015180 if (!NoDiagnose) {
15181 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15182 << CurE->getSourceRange();
15183 return nullptr;
15184 }
15185 if (RelevantExpr)
15186 return nullptr;
15187 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015188 }
15189
15190 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15191
15192 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15193 // A bit-field cannot appear in a map clause.
15194 //
15195 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015196 if (!NoDiagnose) {
15197 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15198 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15199 return nullptr;
15200 }
15201 if (RelevantExpr)
15202 return nullptr;
15203 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015204 }
15205
15206 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15207 // If the type of a list item is a reference to a type T then the type
15208 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015209 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015210
15211 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15212 // A list item cannot be a variable that is a member of a structure with
15213 // a union type.
15214 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015215 if (CurType->isUnionType()) {
15216 if (!NoDiagnose) {
15217 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15218 << CurE->getSourceRange();
15219 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015220 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015221 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015222 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015223
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015224 // If we got a member expression, we should not expect any array section
15225 // before that:
15226 //
15227 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15228 // If a list item is an element of a structure, only the rightmost symbol
15229 // of the variable reference can be an array section.
15230 //
15231 AllowUnitySizeArraySection = false;
15232 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015233
15234 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015235 CurComponents.emplace_back(CurE, FD);
15236 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015237 E = CurE->getBase()->IgnoreParenImpCasts();
15238
15239 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015240 if (!NoDiagnose) {
15241 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15242 << 0 << CurE->getSourceRange();
15243 return nullptr;
15244 }
15245 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015246 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015247
15248 // If we got an array subscript that express the whole dimension we
15249 // can have any array expressions before. If it only expressing part of
15250 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015251 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015252 E->getType()))
15253 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015254
Patrick Lystere13b1e32019-01-02 19:28:48 +000015255 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15256 Expr::EvalResult Result;
15257 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15258 if (!Result.Val.getInt().isNullValue()) {
15259 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15260 diag::err_omp_invalid_map_this_expr);
15261 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15262 diag::note_omp_invalid_subscript_on_this_ptr_map);
15263 }
15264 }
15265 RelevantExpr = TE;
15266 }
15267
Samuel Antao90927002016-04-26 14:54:23 +000015268 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015269 CurComponents.emplace_back(CurE, nullptr);
15270 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015271 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015272 E = CurE->getBase()->IgnoreParenImpCasts();
15273
Alexey Bataev27041fa2017-12-05 15:22:49 +000015274 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015275 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15276
Samuel Antao5de996e2016-01-22 20:21:36 +000015277 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15278 // If the type of a list item is a reference to a type T then the type
15279 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015280 if (CurType->isReferenceType())
15281 CurType = CurType->getPointeeType();
15282
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015283 bool IsPointer = CurType->isAnyPointerType();
15284
15285 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015286 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15287 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015288 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015289 }
15290
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015291 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015292 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015293 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015294 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015295
Samuel Antaodab51bb2016-07-18 23:22:11 +000015296 if (AllowWholeSizeArraySection) {
15297 // Any array section is currently allowed. Allowing a whole size array
15298 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015299 //
15300 // If this array section refers to the whole dimension we can still
15301 // accept other array sections before this one, except if the base is a
15302 // pointer. Otherwise, only unitary sections are accepted.
15303 if (NotWhole || IsPointer)
15304 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015305 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015306 // A unity or whole array section is not allowed and that is not
15307 // compatible with the properties of the current array section.
15308 SemaRef.Diag(
15309 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15310 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015311 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015312 }
Samuel Antao90927002016-04-26 14:54:23 +000015313
Patrick Lystere13b1e32019-01-02 19:28:48 +000015314 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15315 Expr::EvalResult ResultR;
15316 Expr::EvalResult ResultL;
15317 if (CurE->getLength()->EvaluateAsInt(ResultR,
15318 SemaRef.getASTContext())) {
15319 if (!ResultR.Val.getInt().isOneValue()) {
15320 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15321 diag::err_omp_invalid_map_this_expr);
15322 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15323 diag::note_omp_invalid_length_on_this_ptr_mapping);
15324 }
15325 }
15326 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15327 ResultL, SemaRef.getASTContext())) {
15328 if (!ResultL.Val.getInt().isNullValue()) {
15329 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15330 diag::err_omp_invalid_map_this_expr);
15331 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15332 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15333 }
15334 }
15335 RelevantExpr = TE;
15336 }
15337
Samuel Antao90927002016-04-26 14:54:23 +000015338 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015339 CurComponents.emplace_back(CurE, nullptr);
15340 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015341 if (!NoDiagnose) {
15342 // If nothing else worked, this is not a valid map clause expression.
15343 SemaRef.Diag(
15344 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15345 << ERange;
15346 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015347 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015348 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015349 }
15350
15351 return RelevantExpr;
15352}
15353
15354// Return true if expression E associated with value VD has conflicts with other
15355// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015356static bool checkMapConflicts(
15357 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015358 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015359 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15360 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015361 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015362 SourceLocation ELoc = E->getExprLoc();
15363 SourceRange ERange = E->getSourceRange();
15364
15365 // In order to easily check the conflicts we need to match each component of
15366 // the expression under test with the components of the expressions that are
15367 // already in the stack.
15368
Samuel Antao5de996e2016-01-22 20:21:36 +000015369 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015370 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015371 "Map clause expression with unexpected base!");
15372
15373 // Variables to help detecting enclosing problems in data environment nests.
15374 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015375 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015376
Samuel Antao90927002016-04-26 14:54:23 +000015377 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15378 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015379 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15380 ERange, CKind, &EnclosingExpr,
15381 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15382 StackComponents,
15383 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015384 assert(!StackComponents.empty() &&
15385 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015386 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015387 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015388 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015389
Samuel Antao90927002016-04-26 14:54:23 +000015390 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015391 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015392
Samuel Antao5de996e2016-01-22 20:21:36 +000015393 // Expressions must start from the same base. Here we detect at which
15394 // point both expressions diverge from each other and see if we can
15395 // detect if the memory referred to both expressions is contiguous and
15396 // do not overlap.
15397 auto CI = CurComponents.rbegin();
15398 auto CE = CurComponents.rend();
15399 auto SI = StackComponents.rbegin();
15400 auto SE = StackComponents.rend();
15401 for (; CI != CE && SI != SE; ++CI, ++SI) {
15402
15403 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15404 // At most one list item can be an array item derived from a given
15405 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015406 if (CurrentRegionOnly &&
15407 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15408 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15409 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15410 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15411 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015412 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015413 << CI->getAssociatedExpression()->getSourceRange();
15414 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15415 diag::note_used_here)
15416 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015417 return true;
15418 }
15419
15420 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015421 if (CI->getAssociatedExpression()->getStmtClass() !=
15422 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015423 break;
15424
15425 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015426 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015427 break;
15428 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015429 // Check if the extra components of the expressions in the enclosing
15430 // data environment are redundant for the current base declaration.
15431 // If they are, the maps completely overlap, which is legal.
15432 for (; SI != SE; ++SI) {
15433 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015434 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015435 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015436 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015437 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015438 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015439 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015440 Type =
15441 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15442 }
15443 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015444 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015445 SemaRef, SI->getAssociatedExpression(), Type))
15446 break;
15447 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015448
15449 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15450 // List items of map clauses in the same construct must not share
15451 // original storage.
15452 //
15453 // If the expressions are exactly the same or one is a subset of the
15454 // other, it means they are sharing storage.
15455 if (CI == CE && SI == SE) {
15456 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015457 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015458 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015459 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015460 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015461 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15462 << ERange;
15463 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015464 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15465 << RE->getSourceRange();
15466 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015467 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015468 // If we find the same expression in the enclosing data environment,
15469 // that is legal.
15470 IsEnclosedByDataEnvironmentExpr = true;
15471 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015472 }
15473
Samuel Antao90927002016-04-26 14:54:23 +000015474 QualType DerivedType =
15475 std::prev(CI)->getAssociatedDeclaration()->getType();
15476 SourceLocation DerivedLoc =
15477 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015478
15479 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15480 // If the type of a list item is a reference to a type T then the type
15481 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015482 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015483
15484 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15485 // A variable for which the type is pointer and an array section
15486 // derived from that variable must not appear as list items of map
15487 // clauses of the same construct.
15488 //
15489 // Also, cover one of the cases in:
15490 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15491 // If any part of the original storage of a list item has corresponding
15492 // storage in the device data environment, all of the original storage
15493 // must have corresponding storage in the device data environment.
15494 //
15495 if (DerivedType->isAnyPointerType()) {
15496 if (CI == CE || SI == SE) {
15497 SemaRef.Diag(
15498 DerivedLoc,
15499 diag::err_omp_pointer_mapped_along_with_derived_section)
15500 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015501 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15502 << RE->getSourceRange();
15503 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015504 }
15505 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015506 SI->getAssociatedExpression()->getStmtClass() ||
15507 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15508 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015509 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015510 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015511 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015512 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15513 << RE->getSourceRange();
15514 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015515 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015516 }
15517
15518 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15519 // List items of map clauses in the same construct must not share
15520 // original storage.
15521 //
15522 // An expression is a subset of the other.
15523 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015524 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015525 if (CI != CE || SI != SE) {
15526 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15527 // a pointer.
15528 auto Begin =
15529 CI != CE ? CurComponents.begin() : StackComponents.begin();
15530 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15531 auto It = Begin;
15532 while (It != End && !It->getAssociatedDeclaration())
15533 std::advance(It, 1);
15534 assert(It != End &&
15535 "Expected at least one component with the declaration.");
15536 if (It != Begin && It->getAssociatedDeclaration()
15537 ->getType()
15538 .getCanonicalType()
15539 ->isAnyPointerType()) {
15540 IsEnclosedByDataEnvironmentExpr = false;
15541 EnclosingExpr = nullptr;
15542 return false;
15543 }
15544 }
Samuel Antao661c0902016-05-26 17:39:58 +000015545 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015546 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015547 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015548 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15549 << ERange;
15550 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015551 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15552 << RE->getSourceRange();
15553 return true;
15554 }
15555
15556 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015557 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015558 if (!CurrentRegionOnly && SI != SE)
15559 EnclosingExpr = RE;
15560
15561 // The current expression is a subset of the expression in the data
15562 // environment.
15563 IsEnclosedByDataEnvironmentExpr |=
15564 (!CurrentRegionOnly && CI != CE && SI == SE);
15565
15566 return false;
15567 });
15568
15569 if (CurrentRegionOnly)
15570 return FoundError;
15571
15572 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15573 // If any part of the original storage of a list item has corresponding
15574 // storage in the device data environment, all of the original storage must
15575 // have corresponding storage in the device data environment.
15576 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15577 // If a list item is an element of a structure, and a different element of
15578 // the structure has a corresponding list item in the device data environment
15579 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015580 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015581 // data environment prior to the task encountering the construct.
15582 //
15583 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15584 SemaRef.Diag(ELoc,
15585 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15586 << ERange;
15587 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15588 << EnclosingExpr->getSourceRange();
15589 return true;
15590 }
15591
15592 return FoundError;
15593}
15594
Michael Kruse4304e9d2019-02-19 16:38:20 +000015595// Look up the user-defined mapper given the mapper name and mapped type, and
15596// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015597static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15598 CXXScopeSpec &MapperIdScopeSpec,
15599 const DeclarationNameInfo &MapperId,
15600 QualType Type,
15601 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015602 if (MapperIdScopeSpec.isInvalid())
15603 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015604 // Get the actual type for the array type.
15605 if (Type->isArrayType()) {
15606 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15607 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15608 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015609 // Find all user-defined mappers with the given MapperId.
15610 SmallVector<UnresolvedSet<8>, 4> Lookups;
15611 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15612 Lookup.suppressDiagnostics();
15613 if (S) {
15614 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15615 NamedDecl *D = Lookup.getRepresentativeDecl();
15616 while (S && !S->isDeclScope(D))
15617 S = S->getParent();
15618 if (S)
15619 S = S->getParent();
15620 Lookups.emplace_back();
15621 Lookups.back().append(Lookup.begin(), Lookup.end());
15622 Lookup.clear();
15623 }
15624 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15625 // Extract the user-defined mappers with the given MapperId.
15626 Lookups.push_back(UnresolvedSet<8>());
15627 for (NamedDecl *D : ULE->decls()) {
15628 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15629 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15630 Lookups.back().addDecl(DMD);
15631 }
15632 }
15633 // Defer the lookup for dependent types. The results will be passed through
15634 // UnresolvedMapper on instantiation.
15635 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15636 Type->isInstantiationDependentType() ||
15637 Type->containsUnexpandedParameterPack() ||
15638 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15639 return !D->isInvalidDecl() &&
15640 (D->getType()->isDependentType() ||
15641 D->getType()->isInstantiationDependentType() ||
15642 D->getType()->containsUnexpandedParameterPack());
15643 })) {
15644 UnresolvedSet<8> URS;
15645 for (const UnresolvedSet<8> &Set : Lookups) {
15646 if (Set.empty())
15647 continue;
15648 URS.append(Set.begin(), Set.end());
15649 }
15650 return UnresolvedLookupExpr::Create(
15651 SemaRef.Context, /*NamingClass=*/nullptr,
15652 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15653 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15654 }
Michael Kruse945249b2019-09-26 22:53:01 +000015655 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015656 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15657 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015658 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15659 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15660 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15661 return ExprError();
15662 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015663 // Perform argument dependent lookup.
15664 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15665 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15666 // Return the first user-defined mapper with the desired type.
15667 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15668 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15669 if (!D->isInvalidDecl() &&
15670 SemaRef.Context.hasSameType(D->getType(), Type))
15671 return D;
15672 return nullptr;
15673 }))
15674 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15675 // Find the first user-defined mapper with a type derived from the desired
15676 // type.
15677 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15678 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15679 if (!D->isInvalidDecl() &&
15680 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15681 !Type.isMoreQualifiedThan(D->getType()))
15682 return D;
15683 return nullptr;
15684 })) {
15685 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15686 /*DetectVirtual=*/false);
15687 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15688 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15689 VD->getType().getUnqualifiedType()))) {
15690 if (SemaRef.CheckBaseClassAccess(
15691 Loc, VD->getType(), Type, Paths.front(),
15692 /*DiagID=*/0) != Sema::AR_inaccessible) {
15693 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15694 }
15695 }
15696 }
15697 }
15698 // Report error if a mapper is specified, but cannot be found.
15699 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15700 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15701 << Type << MapperId.getName();
15702 return ExprError();
15703 }
15704 return ExprEmpty();
15705}
15706
Samuel Antao661c0902016-05-26 17:39:58 +000015707namespace {
15708// Utility struct that gathers all the related lists associated with a mappable
15709// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015710struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015711 // The list of expressions.
15712 ArrayRef<Expr *> VarList;
15713 // The list of processed expressions.
15714 SmallVector<Expr *, 16> ProcessedVarList;
15715 // The mappble components for each expression.
15716 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15717 // The base declaration of the variable.
15718 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015719 // The reference to the user-defined mapper associated with every expression.
15720 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015721
15722 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15723 // We have a list of components and base declarations for each entry in the
15724 // variable list.
15725 VarComponents.reserve(VarList.size());
15726 VarBaseDeclarations.reserve(VarList.size());
15727 }
15728};
15729}
15730
15731// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015732// \a CKind. In the check process the valid expressions, mappable expression
15733// components, variables, and user-defined mappers are extracted and used to
15734// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15735// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15736// and \a MapperId are expected to be valid if the clause kind is 'map'.
15737static void checkMappableExpressionList(
15738 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15739 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015740 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15741 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015742 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015743 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015744 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15745 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015746 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015747
15748 // If the identifier of user-defined mapper is not specified, it is "default".
15749 // We do not change the actual name in this clause to distinguish whether a
15750 // mapper is specified explicitly, i.e., it is not explicitly specified when
15751 // MapperId.getName() is empty.
15752 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15753 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15754 MapperId.setName(DeclNames.getIdentifier(
15755 &SemaRef.getASTContext().Idents.get("default")));
15756 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015757
15758 // Iterators to find the current unresolved mapper expression.
15759 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15760 bool UpdateUMIt = false;
15761 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015762
Samuel Antao90927002016-04-26 14:54:23 +000015763 // Keep track of the mappable components and base declarations in this clause.
15764 // Each entry in the list is going to have a list of components associated. We
15765 // record each set of the components so that we can build the clause later on.
15766 // In the end we should have the same amount of declarations and component
15767 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015768
Alexey Bataeve3727102018-04-18 15:57:46 +000015769 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015770 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015771 SourceLocation ELoc = RE->getExprLoc();
15772
Michael Kruse4304e9d2019-02-19 16:38:20 +000015773 // Find the current unresolved mapper expression.
15774 if (UpdateUMIt && UMIt != UMEnd) {
15775 UMIt++;
15776 assert(
15777 UMIt != UMEnd &&
15778 "Expect the size of UnresolvedMappers to match with that of VarList");
15779 }
15780 UpdateUMIt = true;
15781 if (UMIt != UMEnd)
15782 UnresolvedMapper = *UMIt;
15783
Alexey Bataeve3727102018-04-18 15:57:46 +000015784 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015785
15786 if (VE->isValueDependent() || VE->isTypeDependent() ||
15787 VE->isInstantiationDependent() ||
15788 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015789 // Try to find the associated user-defined mapper.
15790 ExprResult ER = buildUserDefinedMapperRef(
15791 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15792 VE->getType().getCanonicalType(), UnresolvedMapper);
15793 if (ER.isInvalid())
15794 continue;
15795 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015796 // We can only analyze this information once the missing information is
15797 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015798 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015799 continue;
15800 }
15801
Alexey Bataeve3727102018-04-18 15:57:46 +000015802 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015803
Samuel Antao5de996e2016-01-22 20:21:36 +000015804 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015805 SemaRef.Diag(ELoc,
15806 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015807 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015808 continue;
15809 }
15810
Samuel Antao90927002016-04-26 14:54:23 +000015811 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15812 ValueDecl *CurDeclaration = nullptr;
15813
15814 // Obtain the array or member expression bases if required. Also, fill the
15815 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015816 const Expr *BE = checkMapClauseExpressionBase(
15817 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015818 if (!BE)
15819 continue;
15820
Samuel Antao90927002016-04-26 14:54:23 +000015821 assert(!CurComponents.empty() &&
15822 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015823
Patrick Lystere13b1e32019-01-02 19:28:48 +000015824 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15825 // Add store "this" pointer to class in DSAStackTy for future checking
15826 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015827 // Try to find the associated user-defined mapper.
15828 ExprResult ER = buildUserDefinedMapperRef(
15829 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15830 VE->getType().getCanonicalType(), UnresolvedMapper);
15831 if (ER.isInvalid())
15832 continue;
15833 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015834 // Skip restriction checking for variable or field declarations
15835 MVLI.ProcessedVarList.push_back(RE);
15836 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15837 MVLI.VarComponents.back().append(CurComponents.begin(),
15838 CurComponents.end());
15839 MVLI.VarBaseDeclarations.push_back(nullptr);
15840 continue;
15841 }
15842
Samuel Antao90927002016-04-26 14:54:23 +000015843 // For the following checks, we rely on the base declaration which is
15844 // expected to be associated with the last component. The declaration is
15845 // expected to be a variable or a field (if 'this' is being mapped).
15846 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15847 assert(CurDeclaration && "Null decl on map clause.");
15848 assert(
15849 CurDeclaration->isCanonicalDecl() &&
15850 "Expecting components to have associated only canonical declarations.");
15851
15852 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015853 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015854
15855 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015856 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015857
15858 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015859 // threadprivate variables cannot appear in a map clause.
15860 // OpenMP 4.5 [2.10.5, target update Construct]
15861 // threadprivate variables cannot appear in a from clause.
15862 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015863 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015864 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15865 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015866 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015867 continue;
15868 }
15869
Samuel Antao5de996e2016-01-22 20:21:36 +000015870 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15871 // A list item cannot appear in both a map clause and a data-sharing
15872 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015873
Samuel Antao5de996e2016-01-22 20:21:36 +000015874 // Check conflicts with other map clause expressions. We check the conflicts
15875 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015876 // environment, because the restrictions are different. We only have to
15877 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015878 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015879 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015880 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015881 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015882 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015883 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015884 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015885
Samuel Antao661c0902016-05-26 17:39:58 +000015886 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015887 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15888 // If the type of a list item is a reference to a type T then the type will
15889 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015890 auto I = llvm::find_if(
15891 CurComponents,
15892 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15893 return MC.getAssociatedDeclaration();
15894 });
15895 assert(I != CurComponents.end() && "Null decl on map clause.");
15896 QualType Type =
15897 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015898
Samuel Antao661c0902016-05-26 17:39:58 +000015899 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15900 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015901 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015902 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015903 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015904 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015905 continue;
15906
Samuel Antao661c0902016-05-26 17:39:58 +000015907 if (CKind == OMPC_map) {
15908 // target enter data
15909 // OpenMP [2.10.2, Restrictions, p. 99]
15910 // A map-type must be specified in all map clauses and must be either
15911 // to or alloc.
15912 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15913 if (DKind == OMPD_target_enter_data &&
15914 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15915 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15916 << (IsMapTypeImplicit ? 1 : 0)
15917 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15918 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015919 continue;
15920 }
Samuel Antao661c0902016-05-26 17:39:58 +000015921
15922 // target exit_data
15923 // OpenMP [2.10.3, Restrictions, p. 102]
15924 // A map-type must be specified in all map clauses and must be either
15925 // from, release, or delete.
15926 if (DKind == OMPD_target_exit_data &&
15927 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15928 MapType == OMPC_MAP_delete)) {
15929 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15930 << (IsMapTypeImplicit ? 1 : 0)
15931 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15932 << getOpenMPDirectiveName(DKind);
15933 continue;
15934 }
15935
15936 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15937 // A list item cannot appear in both a map clause and a data-sharing
15938 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015939 //
15940 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15941 // A list item cannot appear in both a map clause and a data-sharing
15942 // attribute clause on the same construct unless the construct is a
15943 // combined construct.
15944 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15945 isOpenMPTargetExecutionDirective(DKind)) ||
15946 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015947 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015948 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015949 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015950 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015951 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015952 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015953 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015954 continue;
15955 }
15956 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015957 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015958
Michael Kruse01f670d2019-02-22 22:29:42 +000015959 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015960 ExprResult ER = buildUserDefinedMapperRef(
15961 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15962 Type.getCanonicalType(), UnresolvedMapper);
15963 if (ER.isInvalid())
15964 continue;
15965 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015966
Samuel Antao90927002016-04-26 14:54:23 +000015967 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015968 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015969
15970 // Store the components in the stack so that they can be used to check
15971 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015972 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15973 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015974
15975 // Save the components and declaration to create the clause. For purposes of
15976 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015977 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015978 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15979 MVLI.VarComponents.back().append(CurComponents.begin(),
15980 CurComponents.end());
15981 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15982 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015983 }
Samuel Antao661c0902016-05-26 17:39:58 +000015984}
15985
Michael Kruse4304e9d2019-02-19 16:38:20 +000015986OMPClause *Sema::ActOnOpenMPMapClause(
15987 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15988 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15989 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15990 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15991 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15992 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15993 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15994 OMPC_MAP_MODIFIER_unknown,
15995 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015996 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15997
15998 // Process map-type-modifiers, flag errors for duplicate modifiers.
15999 unsigned Count = 0;
16000 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16001 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16002 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16003 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16004 continue;
16005 }
16006 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016007 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016008 Modifiers[Count] = MapTypeModifiers[I];
16009 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16010 ++Count;
16011 }
16012
Michael Kruse4304e9d2019-02-19 16:38:20 +000016013 MappableVarListInfo MVLI(VarList);
16014 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016015 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16016 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016017
Samuel Antao5de996e2016-01-22 20:21:36 +000016018 // We need to produce a map clause even if we don't have variables so that
16019 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016020 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16021 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16022 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16023 MapperIdScopeSpec.getWithLocInContext(Context),
16024 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016025}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016026
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016027QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16028 TypeResult ParsedType) {
16029 assert(ParsedType.isUsable());
16030
16031 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16032 if (ReductionType.isNull())
16033 return QualType();
16034
16035 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16036 // A type name in a declare reduction directive cannot be a function type, an
16037 // array type, a reference type, or a type qualified with const, volatile or
16038 // restrict.
16039 if (ReductionType.hasQualifiers()) {
16040 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16041 return QualType();
16042 }
16043
16044 if (ReductionType->isFunctionType()) {
16045 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16046 return QualType();
16047 }
16048 if (ReductionType->isReferenceType()) {
16049 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16050 return QualType();
16051 }
16052 if (ReductionType->isArrayType()) {
16053 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16054 return QualType();
16055 }
16056 return ReductionType;
16057}
16058
16059Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16060 Scope *S, DeclContext *DC, DeclarationName Name,
16061 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16062 AccessSpecifier AS, Decl *PrevDeclInScope) {
16063 SmallVector<Decl *, 8> Decls;
16064 Decls.reserve(ReductionTypes.size());
16065
16066 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016067 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016068 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16069 // A reduction-identifier may not be re-declared in the current scope for the
16070 // same type or for a type that is compatible according to the base language
16071 // rules.
16072 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16073 OMPDeclareReductionDecl *PrevDRD = nullptr;
16074 bool InCompoundScope = true;
16075 if (S != nullptr) {
16076 // Find previous declaration with the same name not referenced in other
16077 // declarations.
16078 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16079 InCompoundScope =
16080 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16081 LookupName(Lookup, S);
16082 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16083 /*AllowInlineNamespace=*/false);
16084 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016085 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016086 while (Filter.hasNext()) {
16087 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16088 if (InCompoundScope) {
16089 auto I = UsedAsPrevious.find(PrevDecl);
16090 if (I == UsedAsPrevious.end())
16091 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016092 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016093 UsedAsPrevious[D] = true;
16094 }
16095 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16096 PrevDecl->getLocation();
16097 }
16098 Filter.done();
16099 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016100 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016101 if (!PrevData.second) {
16102 PrevDRD = PrevData.first;
16103 break;
16104 }
16105 }
16106 }
16107 } else if (PrevDeclInScope != nullptr) {
16108 auto *PrevDRDInScope = PrevDRD =
16109 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16110 do {
16111 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16112 PrevDRDInScope->getLocation();
16113 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16114 } while (PrevDRDInScope != nullptr);
16115 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016116 for (const auto &TyData : ReductionTypes) {
16117 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016118 bool Invalid = false;
16119 if (I != PreviousRedeclTypes.end()) {
16120 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16121 << TyData.first;
16122 Diag(I->second, diag::note_previous_definition);
16123 Invalid = true;
16124 }
16125 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16126 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16127 Name, TyData.first, PrevDRD);
16128 DC->addDecl(DRD);
16129 DRD->setAccess(AS);
16130 Decls.push_back(DRD);
16131 if (Invalid)
16132 DRD->setInvalidDecl();
16133 else
16134 PrevDRD = DRD;
16135 }
16136
16137 return DeclGroupPtrTy::make(
16138 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16139}
16140
16141void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16142 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16143
16144 // Enter new function scope.
16145 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016146 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016147 getCurFunction()->setHasOMPDeclareReductionCombiner();
16148
16149 if (S != nullptr)
16150 PushDeclContext(S, DRD);
16151 else
16152 CurContext = DRD;
16153
Faisal Valid143a0c2017-04-01 21:30:49 +000016154 PushExpressionEvaluationContext(
16155 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016156
16157 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016158 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16159 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16160 // uses semantics of argument handles by value, but it should be passed by
16161 // reference. C lang does not support references, so pass all parameters as
16162 // pointers.
16163 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016164 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016165 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016166 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16167 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16168 // uses semantics of argument handles by value, but it should be passed by
16169 // reference. C lang does not support references, so pass all parameters as
16170 // pointers.
16171 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016172 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016173 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16174 if (S != nullptr) {
16175 PushOnScopeChains(OmpInParm, S);
16176 PushOnScopeChains(OmpOutParm, S);
16177 } else {
16178 DRD->addDecl(OmpInParm);
16179 DRD->addDecl(OmpOutParm);
16180 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016181 Expr *InE =
16182 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16183 Expr *OutE =
16184 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16185 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016186}
16187
16188void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16189 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16190 DiscardCleanupsInEvaluationContext();
16191 PopExpressionEvaluationContext();
16192
16193 PopDeclContext();
16194 PopFunctionScopeInfo();
16195
16196 if (Combiner != nullptr)
16197 DRD->setCombiner(Combiner);
16198 else
16199 DRD->setInvalidDecl();
16200}
16201
Alexey Bataev070f43a2017-09-06 14:49:58 +000016202VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016203 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16204
16205 // Enter new function scope.
16206 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016207 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016208
16209 if (S != nullptr)
16210 PushDeclContext(S, DRD);
16211 else
16212 CurContext = DRD;
16213
Faisal Valid143a0c2017-04-01 21:30:49 +000016214 PushExpressionEvaluationContext(
16215 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016216
16217 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016218 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16219 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16220 // uses semantics of argument handles by value, but it should be passed by
16221 // reference. C lang does not support references, so pass all parameters as
16222 // pointers.
16223 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016224 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016225 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016226 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16227 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16228 // uses semantics of argument handles by value, but it should be passed by
16229 // reference. C lang does not support references, so pass all parameters as
16230 // pointers.
16231 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016232 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016233 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016234 if (S != nullptr) {
16235 PushOnScopeChains(OmpPrivParm, S);
16236 PushOnScopeChains(OmpOrigParm, S);
16237 } else {
16238 DRD->addDecl(OmpPrivParm);
16239 DRD->addDecl(OmpOrigParm);
16240 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016241 Expr *OrigE =
16242 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16243 Expr *PrivE =
16244 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16245 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016246 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016247}
16248
Alexey Bataev070f43a2017-09-06 14:49:58 +000016249void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16250 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016251 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16252 DiscardCleanupsInEvaluationContext();
16253 PopExpressionEvaluationContext();
16254
16255 PopDeclContext();
16256 PopFunctionScopeInfo();
16257
Alexey Bataev070f43a2017-09-06 14:49:58 +000016258 if (Initializer != nullptr) {
16259 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16260 } else if (OmpPrivParm->hasInit()) {
16261 DRD->setInitializer(OmpPrivParm->getInit(),
16262 OmpPrivParm->isDirectInit()
16263 ? OMPDeclareReductionDecl::DirectInit
16264 : OMPDeclareReductionDecl::CopyInit);
16265 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016266 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016267 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016268}
16269
16270Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16271 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016272 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016273 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016274 if (S)
16275 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16276 /*AddToContext=*/false);
16277 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016278 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016279 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016280 }
16281 return DeclReductions;
16282}
16283
Michael Kruse251e1482019-02-01 20:25:04 +000016284TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16285 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16286 QualType T = TInfo->getType();
16287 if (D.isInvalidType())
16288 return true;
16289
16290 if (getLangOpts().CPlusPlus) {
16291 // Check that there are no default arguments (C++ only).
16292 CheckExtraCXXDefaultArguments(D);
16293 }
16294
16295 return CreateParsedType(T, TInfo);
16296}
16297
16298QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16299 TypeResult ParsedType) {
16300 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16301
16302 QualType MapperType = GetTypeFromParser(ParsedType.get());
16303 assert(!MapperType.isNull() && "Expect valid mapper type");
16304
16305 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16306 // The type must be of struct, union or class type in C and C++
16307 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16308 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16309 return QualType();
16310 }
16311 return MapperType;
16312}
16313
16314OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16315 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16316 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16317 Decl *PrevDeclInScope) {
16318 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16319 forRedeclarationInCurContext());
16320 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16321 // A mapper-identifier may not be redeclared in the current scope for the
16322 // same type or for a type that is compatible according to the base language
16323 // rules.
16324 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16325 OMPDeclareMapperDecl *PrevDMD = nullptr;
16326 bool InCompoundScope = true;
16327 if (S != nullptr) {
16328 // Find previous declaration with the same name not referenced in other
16329 // declarations.
16330 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16331 InCompoundScope =
16332 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16333 LookupName(Lookup, S);
16334 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16335 /*AllowInlineNamespace=*/false);
16336 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16337 LookupResult::Filter Filter = Lookup.makeFilter();
16338 while (Filter.hasNext()) {
16339 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16340 if (InCompoundScope) {
16341 auto I = UsedAsPrevious.find(PrevDecl);
16342 if (I == UsedAsPrevious.end())
16343 UsedAsPrevious[PrevDecl] = false;
16344 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16345 UsedAsPrevious[D] = true;
16346 }
16347 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16348 PrevDecl->getLocation();
16349 }
16350 Filter.done();
16351 if (InCompoundScope) {
16352 for (const auto &PrevData : UsedAsPrevious) {
16353 if (!PrevData.second) {
16354 PrevDMD = PrevData.first;
16355 break;
16356 }
16357 }
16358 }
16359 } else if (PrevDeclInScope) {
16360 auto *PrevDMDInScope = PrevDMD =
16361 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16362 do {
16363 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16364 PrevDMDInScope->getLocation();
16365 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16366 } while (PrevDMDInScope != nullptr);
16367 }
16368 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16369 bool Invalid = false;
16370 if (I != PreviousRedeclTypes.end()) {
16371 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16372 << MapperType << Name;
16373 Diag(I->second, diag::note_previous_definition);
16374 Invalid = true;
16375 }
16376 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16377 MapperType, VN, PrevDMD);
16378 DC->addDecl(DMD);
16379 DMD->setAccess(AS);
16380 if (Invalid)
16381 DMD->setInvalidDecl();
16382
16383 // Enter new function scope.
16384 PushFunctionScope();
16385 setFunctionHasBranchProtectedScope();
16386
16387 CurContext = DMD;
16388
16389 return DMD;
16390}
16391
16392void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16393 Scope *S,
16394 QualType MapperType,
16395 SourceLocation StartLoc,
16396 DeclarationName VN) {
16397 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16398 if (S)
16399 PushOnScopeChains(VD, S);
16400 else
16401 DMD->addDecl(VD);
16402 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16403 DMD->setMapperVarRef(MapperVarRefExpr);
16404}
16405
16406Sema::DeclGroupPtrTy
16407Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16408 ArrayRef<OMPClause *> ClauseList) {
16409 PopDeclContext();
16410 PopFunctionScopeInfo();
16411
16412 if (D) {
16413 if (S)
16414 PushOnScopeChains(D, S, /*AddToContext=*/false);
16415 D->CreateClauses(Context, ClauseList);
16416 }
16417
16418 return DeclGroupPtrTy::make(DeclGroupRef(D));
16419}
16420
David Majnemer9d168222016-08-05 17:44:54 +000016421OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016422 SourceLocation StartLoc,
16423 SourceLocation LParenLoc,
16424 SourceLocation EndLoc) {
16425 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016426 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016427
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016428 // OpenMP [teams Constrcut, Restrictions]
16429 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016430 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016431 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016432 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016433
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016434 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016435 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016436 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016437 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016438 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016439 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016440 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16441 HelperValStmt = buildPreInits(Context, Captures);
16442 }
16443
16444 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16445 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016446}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016447
16448OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16449 SourceLocation StartLoc,
16450 SourceLocation LParenLoc,
16451 SourceLocation EndLoc) {
16452 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016453 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016454
16455 // OpenMP [teams Constrcut, Restrictions]
16456 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016457 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016458 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016459 return nullptr;
16460
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016461 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016462 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16463 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016464 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016465 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016466 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016467 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16468 HelperValStmt = buildPreInits(Context, Captures);
16469 }
16470
16471 return new (Context) OMPThreadLimitClause(
16472 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016473}
Alexey Bataeva0569352015-12-01 10:17:31 +000016474
16475OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16476 SourceLocation StartLoc,
16477 SourceLocation LParenLoc,
16478 SourceLocation EndLoc) {
16479 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016480 Stmt *HelperValStmt = nullptr;
16481 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016482
16483 // OpenMP [2.9.1, task Constrcut]
16484 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016485 if (!isNonNegativeIntegerValue(
16486 ValExpr, *this, OMPC_priority,
16487 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16488 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016489 return nullptr;
16490
Alexey Bataev31ba4762019-10-16 18:09:37 +000016491 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16492 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016493}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016494
16495OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16496 SourceLocation StartLoc,
16497 SourceLocation LParenLoc,
16498 SourceLocation EndLoc) {
16499 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016500 Stmt *HelperValStmt = nullptr;
16501 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016502
16503 // OpenMP [2.9.2, taskloop Constrcut]
16504 // The parameter of the grainsize clause must be a positive integer
16505 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016506 if (!isNonNegativeIntegerValue(
16507 ValExpr, *this, OMPC_grainsize,
16508 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16509 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016510 return nullptr;
16511
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016512 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16513 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016514}
Alexey Bataev382967a2015-12-08 12:06:20 +000016515
16516OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16517 SourceLocation StartLoc,
16518 SourceLocation LParenLoc,
16519 SourceLocation EndLoc) {
16520 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016521 Stmt *HelperValStmt = nullptr;
16522 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016523
16524 // OpenMP [2.9.2, taskloop Constrcut]
16525 // The parameter of the num_tasks clause must be a positive integer
16526 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016527 if (!isNonNegativeIntegerValue(
16528 ValExpr, *this, OMPC_num_tasks,
16529 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16530 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016531 return nullptr;
16532
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016533 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16534 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016535}
16536
Alexey Bataev28c75412015-12-15 08:19:24 +000016537OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16538 SourceLocation LParenLoc,
16539 SourceLocation EndLoc) {
16540 // OpenMP [2.13.2, critical construct, Description]
16541 // ... where hint-expression is an integer constant expression that evaluates
16542 // to a valid lock hint.
16543 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16544 if (HintExpr.isInvalid())
16545 return nullptr;
16546 return new (Context)
16547 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16548}
16549
Carlo Bertollib4adf552016-01-15 18:50:31 +000016550OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16551 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16552 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16553 SourceLocation EndLoc) {
16554 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16555 std::string Values;
16556 Values += "'";
16557 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16558 Values += "'";
16559 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16560 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16561 return nullptr;
16562 }
16563 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016564 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016565 if (ChunkSize) {
16566 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16567 !ChunkSize->isInstantiationDependent() &&
16568 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016569 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016570 ExprResult Val =
16571 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16572 if (Val.isInvalid())
16573 return nullptr;
16574
16575 ValExpr = Val.get();
16576
16577 // OpenMP [2.7.1, Restrictions]
16578 // chunk_size must be a loop invariant integer expression with a positive
16579 // value.
16580 llvm::APSInt Result;
16581 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16582 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16583 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16584 << "dist_schedule" << ChunkSize->getSourceRange();
16585 return nullptr;
16586 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016587 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016588 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16589 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016590 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016591 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016592 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016593 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16594 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016595 }
16596 }
16597 }
16598
16599 return new (Context)
16600 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016601 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016602}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016603
16604OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16605 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16606 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16607 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016608 if (getLangOpts().OpenMP < 50) {
16609 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16610 Kind != OMPC_DEFAULTMAP_scalar) {
16611 std::string Value;
16612 SourceLocation Loc;
16613 Value += "'";
16614 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16615 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16616 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16617 Loc = MLoc;
16618 } else {
16619 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16620 OMPC_DEFAULTMAP_scalar);
16621 Loc = KindLoc;
16622 }
16623 Value += "'";
16624 Diag(Loc, diag::err_omp_unexpected_clause_value)
16625 << Value << getOpenMPClauseName(OMPC_defaultmap);
16626 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016627 }
cchene06f3e02019-11-15 13:02:06 -050016628 } else {
16629 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16630 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16631 if (!isDefaultmapKind || !isDefaultmapModifier) {
16632 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16633 "'firstprivate', 'none', 'default'";
16634 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16635 if (!isDefaultmapKind && isDefaultmapModifier) {
16636 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16637 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16638 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16639 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16640 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16641 } else {
16642 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16643 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16644 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16645 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16646 }
16647 return nullptr;
16648 }
16649
16650 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16651 // At most one defaultmap clause for each category can appear on the
16652 // directive.
16653 if (DSAStack->checkDefaultmapCategory(Kind)) {
16654 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16655 return nullptr;
16656 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016657 }
cchene06f3e02019-11-15 13:02:06 -050016658 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016659
16660 return new (Context)
16661 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16662}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016663
16664bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16665 DeclContext *CurLexicalContext = getCurLexicalContext();
16666 if (!CurLexicalContext->isFileContext() &&
16667 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016668 !CurLexicalContext->isExternCXXContext() &&
16669 !isa<CXXRecordDecl>(CurLexicalContext) &&
16670 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16671 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16672 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016673 Diag(Loc, diag::err_omp_region_not_file_context);
16674 return false;
16675 }
Kelvin Libc38e632018-09-10 02:07:09 +000016676 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016677 return true;
16678}
16679
16680void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016681 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016682 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016683 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016684}
16685
Alexey Bataev729e2422019-08-23 16:11:14 +000016686NamedDecl *
16687Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16688 const DeclarationNameInfo &Id,
16689 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016690 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16691 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16692
16693 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016694 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016695 Lookup.suppressDiagnostics();
16696
16697 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016698 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016699 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016700 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016701 CTK_ErrorRecovery)) {
16702 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16703 << Id.getName());
16704 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016705 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016706 }
16707
16708 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016709 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016710 }
16711
16712 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016713 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16714 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016715 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016716 return nullptr;
16717 }
16718 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16719 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16720 return ND;
16721}
16722
16723void Sema::ActOnOpenMPDeclareTargetName(
16724 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16725 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16726 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16727 isa<FunctionTemplateDecl>(ND)) &&
16728 "Expected variable, function or function template.");
16729
16730 // Diagnose marking after use as it may lead to incorrect diagnosis and
16731 // codegen.
16732 if (LangOpts.OpenMP >= 50 &&
16733 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16734 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16735
16736 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16737 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16738 if (DevTy.hasValue() && *DevTy != DT) {
16739 Diag(Loc, diag::err_omp_device_type_mismatch)
16740 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16741 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16742 return;
16743 }
16744 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16745 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16746 if (!Res) {
16747 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16748 SourceRange(Loc, Loc));
16749 ND->addAttr(A);
16750 if (ASTMutationListener *ML = Context.getASTMutationListener())
16751 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16752 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16753 } else if (*Res != MT) {
16754 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016755 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016756}
16757
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016758static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16759 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016760 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016761 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016762 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016763 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16764 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16765 if (SemaRef.LangOpts.OpenMP >= 50 &&
16766 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16767 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16768 VD->hasGlobalStorage()) {
16769 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16770 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16771 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16772 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16773 // If a lambda declaration and definition appears between a
16774 // declare target directive and the matching end declare target
16775 // directive, all variables that are captured by the lambda
16776 // expression must also appear in a to clause.
16777 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016778 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016779 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16780 << VD << 0 << SR;
16781 return;
16782 }
16783 }
16784 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016785 return;
16786 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16787 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016788}
16789
16790static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16791 Sema &SemaRef, DSAStackTy *Stack,
16792 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016793 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016794 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16795 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016796}
16797
Kelvin Li1ce87c72017-12-12 20:08:12 +000016798void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16799 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016800 if (!D || D->isInvalidDecl())
16801 return;
16802 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016803 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016804 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016805 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016806 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16807 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016808 return;
16809 // 2.10.6: threadprivate variable cannot appear in a declare target
16810 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016811 if (DSAStack->isThreadPrivate(VD)) {
16812 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016813 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016814 return;
16815 }
16816 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016817 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16818 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016819 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016820 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16821 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016822 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016823 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16824 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16825 return;
16826 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016827 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016828 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16829 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16830 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16831 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016832 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016833 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16834 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16835 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016836 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016837 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16838 // Problem if any with var declared with incomplete type will be reported
16839 // as normal, so no need to check it here.
16840 if ((E || !VD->getType()->isIncompleteType()) &&
16841 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16842 return;
16843 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16844 // Checking declaration inside declare target region.
16845 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16846 isa<FunctionTemplateDecl>(D)) {
16847 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016848 Context, OMPDeclareTargetDeclAttr::MT_To,
16849 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016850 D->addAttr(A);
16851 if (ASTMutationListener *ML = Context.getASTMutationListener())
16852 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16853 }
16854 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016855 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016856 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016857 if (!E)
16858 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016859 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16860}
Samuel Antao661c0902016-05-26 17:39:58 +000016861
16862OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016863 CXXScopeSpec &MapperIdScopeSpec,
16864 DeclarationNameInfo &MapperId,
16865 const OMPVarListLocTy &Locs,
16866 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016867 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016868 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16869 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016870 if (MVLI.ProcessedVarList.empty())
16871 return nullptr;
16872
Michael Kruse01f670d2019-02-22 22:29:42 +000016873 return OMPToClause::Create(
16874 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16875 MVLI.VarComponents, MVLI.UDMapperList,
16876 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016877}
Samuel Antaoec172c62016-05-26 17:49:04 +000016878
16879OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016880 CXXScopeSpec &MapperIdScopeSpec,
16881 DeclarationNameInfo &MapperId,
16882 const OMPVarListLocTy &Locs,
16883 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016884 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016885 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16886 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016887 if (MVLI.ProcessedVarList.empty())
16888 return nullptr;
16889
Michael Kruse0336c752019-02-25 20:34:15 +000016890 return OMPFromClause::Create(
16891 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16892 MVLI.VarComponents, MVLI.UDMapperList,
16893 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016894}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016895
16896OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016897 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016898 MappableVarListInfo MVLI(VarList);
16899 SmallVector<Expr *, 8> PrivateCopies;
16900 SmallVector<Expr *, 8> Inits;
16901
Alexey Bataeve3727102018-04-18 15:57:46 +000016902 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016903 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16904 SourceLocation ELoc;
16905 SourceRange ERange;
16906 Expr *SimpleRefExpr = RefExpr;
16907 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16908 if (Res.second) {
16909 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016910 MVLI.ProcessedVarList.push_back(RefExpr);
16911 PrivateCopies.push_back(nullptr);
16912 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016913 }
16914 ValueDecl *D = Res.first;
16915 if (!D)
16916 continue;
16917
16918 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016919 Type = Type.getNonReferenceType().getUnqualifiedType();
16920
16921 auto *VD = dyn_cast<VarDecl>(D);
16922
16923 // Item should be a pointer or reference to pointer.
16924 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016925 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16926 << 0 << RefExpr->getSourceRange();
16927 continue;
16928 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016929
16930 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016931 auto VDPrivate =
16932 buildVarDecl(*this, ELoc, Type, D->getName(),
16933 D->hasAttrs() ? &D->getAttrs() : nullptr,
16934 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016935 if (VDPrivate->isInvalidDecl())
16936 continue;
16937
16938 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016939 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016940 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16941
16942 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016943 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016944 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016945 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16946 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016947 AddInitializerToDecl(VDPrivate,
16948 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016949 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016950
16951 // If required, build a capture to implement the privatization initialized
16952 // with the current list item value.
16953 DeclRefExpr *Ref = nullptr;
16954 if (!VD)
16955 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16956 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16957 PrivateCopies.push_back(VDPrivateRefExpr);
16958 Inits.push_back(VDInitRefExpr);
16959
16960 // We need to add a data sharing attribute for this variable to make sure it
16961 // is correctly captured. A variable that shows up in a use_device_ptr has
16962 // similar properties of a first private variable.
16963 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16964
16965 // Create a mappable component for the list item. List items in this clause
16966 // only need a component.
16967 MVLI.VarBaseDeclarations.push_back(D);
16968 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16969 MVLI.VarComponents.back().push_back(
16970 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016971 }
16972
Samuel Antaocc10b852016-07-28 14:23:26 +000016973 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016974 return nullptr;
16975
Samuel Antaocc10b852016-07-28 14:23:26 +000016976 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016977 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16978 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016979}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016980
16981OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016982 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016983 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016984 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016985 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016986 SourceLocation ELoc;
16987 SourceRange ERange;
16988 Expr *SimpleRefExpr = RefExpr;
16989 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16990 if (Res.second) {
16991 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016992 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016993 }
16994 ValueDecl *D = Res.first;
16995 if (!D)
16996 continue;
16997
16998 QualType Type = D->getType();
16999 // item should be a pointer or array or reference to pointer or array
17000 if (!Type.getNonReferenceType()->isPointerType() &&
17001 !Type.getNonReferenceType()->isArrayType()) {
17002 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17003 << 0 << RefExpr->getSourceRange();
17004 continue;
17005 }
Samuel Antao6890b092016-07-28 14:25:09 +000017006
17007 // Check if the declaration in the clause does not show up in any data
17008 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017009 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017010 if (isOpenMPPrivate(DVar.CKind)) {
17011 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17012 << getOpenMPClauseName(DVar.CKind)
17013 << getOpenMPClauseName(OMPC_is_device_ptr)
17014 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017015 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017016 continue;
17017 }
17018
Alexey Bataeve3727102018-04-18 15:57:46 +000017019 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017020 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017021 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017022 [&ConflictExpr](
17023 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17024 OpenMPClauseKind) -> bool {
17025 ConflictExpr = R.front().getAssociatedExpression();
17026 return true;
17027 })) {
17028 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17029 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17030 << ConflictExpr->getSourceRange();
17031 continue;
17032 }
17033
17034 // Store the components in the stack so that they can be used to check
17035 // against other clauses later on.
17036 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17037 DSAStack->addMappableExpressionComponents(
17038 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17039
17040 // Record the expression we've just processed.
17041 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17042
17043 // Create a mappable component for the list item. List items in this clause
17044 // only need a component. We use a null declaration to signal fields in
17045 // 'this'.
17046 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17047 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17048 "Unexpected device pointer expression!");
17049 MVLI.VarBaseDeclarations.push_back(
17050 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17051 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17052 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017053 }
17054
Samuel Antao6890b092016-07-28 14:25:09 +000017055 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017056 return nullptr;
17057
Michael Kruse4304e9d2019-02-19 16:38:20 +000017058 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17059 MVLI.VarBaseDeclarations,
17060 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017061}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017062
17063OMPClause *Sema::ActOnOpenMPAllocateClause(
17064 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17065 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17066 if (Allocator) {
17067 // OpenMP [2.11.4 allocate Clause, Description]
17068 // allocator is an expression of omp_allocator_handle_t type.
17069 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17070 return nullptr;
17071
17072 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17073 if (AllocatorRes.isInvalid())
17074 return nullptr;
17075 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17076 DSAStack->getOMPAllocatorHandleT(),
17077 Sema::AA_Initializing,
17078 /*AllowExplicit=*/true);
17079 if (AllocatorRes.isInvalid())
17080 return nullptr;
17081 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017082 } else {
17083 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17084 // allocate clauses that appear on a target construct or on constructs in a
17085 // target region must specify an allocator expression unless a requires
17086 // directive with the dynamic_allocators clause is present in the same
17087 // compilation unit.
17088 if (LangOpts.OpenMPIsDevice &&
17089 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17090 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017091 }
17092 // Analyze and build list of variables.
17093 SmallVector<Expr *, 8> Vars;
17094 for (Expr *RefExpr : VarList) {
17095 assert(RefExpr && "NULL expr in OpenMP private clause.");
17096 SourceLocation ELoc;
17097 SourceRange ERange;
17098 Expr *SimpleRefExpr = RefExpr;
17099 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17100 if (Res.second) {
17101 // It will be analyzed later.
17102 Vars.push_back(RefExpr);
17103 }
17104 ValueDecl *D = Res.first;
17105 if (!D)
17106 continue;
17107
17108 auto *VD = dyn_cast<VarDecl>(D);
17109 DeclRefExpr *Ref = nullptr;
17110 if (!VD && !CurContext->isDependentContext())
17111 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17112 Vars.push_back((VD || CurContext->isDependentContext())
17113 ? RefExpr->IgnoreParens()
17114 : Ref);
17115 }
17116
17117 if (Vars.empty())
17118 return nullptr;
17119
17120 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17121 ColonLoc, EndLoc, Vars);
17122}