blob: 97844cd57056c592ac0ad0f5f73fad22e2aeb937 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000142 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000143 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000144 bool NowaitRegion = false;
145 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000146 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000147 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000148 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000149 /// Reference to the taskgroup task_reduction reference expression.
150 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000151 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000152 /// List of globals marked as declare target link in this target region
153 /// (isOpenMPTargetExecutionDirective(Directive) == true).
154 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000155 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000156 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000157 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
158 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000159 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 };
161
Alexey Bataeve3727102018-04-18 15:57:46 +0000162 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000164 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000165 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000166 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
167 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000168 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000169 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000171 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000172 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000173 /// true if all the vaiables in the target executable directives must be
174 /// captured by reference.
175 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000176 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000177 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000178
Richard Smith375dec52019-05-30 23:21:14 +0000179 /// Iterators over the stack iterate in order from innermost to outermost
180 /// directive.
181 using const_iterator = StackTy::const_reverse_iterator;
182 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000183 return Stack.empty() ? const_iterator()
184 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000185 }
186 const_iterator end() const {
187 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
188 }
189 using iterator = StackTy::reverse_iterator;
190 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000191 return Stack.empty() ? iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000193 }
194 iterator end() {
195 return Stack.empty() ? iterator() : Stack.back().first.rend();
196 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197
Richard Smith375dec52019-05-30 23:21:14 +0000198 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000199
Alexey Bataev4b465392017-04-26 15:06:24 +0000200 bool isStackEmpty() const {
201 return Stack.empty() ||
202 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000203 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000204 }
Richard Smith375dec52019-05-30 23:21:14 +0000205 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000206 return isStackEmpty() ? 0
207 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000208 }
209
210 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000211 size_t Size = getStackSize();
212 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000213 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000214 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000215 }
216 const SharingMapTy *getTopOfStackOrNull() const {
217 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
218 }
219 SharingMapTy &getTopOfStack() {
220 assert(!isStackEmpty() && "no current directive");
221 return *getTopOfStackOrNull();
222 }
223 const SharingMapTy &getTopOfStack() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStack();
225 }
226
227 SharingMapTy *getSecondOnStackOrNull() {
228 size_t Size = getStackSize();
229 if (Size <= 1)
230 return nullptr;
231 return &Stack.back().first[Size - 2];
232 }
233 const SharingMapTy *getSecondOnStackOrNull() const {
234 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
235 }
236
237 /// Get the stack element at a certain level (previously returned by
238 /// \c getNestingLevel).
239 ///
240 /// Note that nesting levels count from outermost to innermost, and this is
241 /// the reverse of our iteration order where new inner levels are pushed at
242 /// the front of the stack.
243 SharingMapTy &getStackElemAtLevel(unsigned Level) {
244 assert(Level < getStackSize() && "no such stack element");
245 return Stack.back().first[Level];
246 }
247 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
248 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
249 }
250
251 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
252
253 /// Checks if the variable is a local for OpenMP region.
254 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000255
Kelvin Li1408f912018-09-26 04:28:39 +0000256 /// Vector of previously declared requires directives
257 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000258 /// omp_allocator_handle_t type.
259 QualType OMPAllocatorHandleT;
260 /// Expression for the predefined allocators.
261 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
262 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000263 /// Vector of previously encountered target directives
264 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000265
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000267 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000268
Alexey Bataev27ef9512019-03-20 20:14:22 +0000269 /// Sets omp_allocator_handle_t type.
270 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
271 /// Gets omp_allocator_handle_t type.
272 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
273 /// Sets the given default allocator.
274 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
275 Expr *Allocator) {
276 OMPPredefinedAllocators[AllocatorKind] = Allocator;
277 }
278 /// Returns the specified default allocator.
279 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
280 return OMPPredefinedAllocators[AllocatorKind];
281 }
282
Alexey Bataevaac108a2015-06-23 04:51:00 +0000283 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000284 OpenMPClauseKind getClauseParsingMode() const {
285 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
286 return ClauseKindMode;
287 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000288 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000289
Richard Smith0621a8f2019-05-31 00:45:10 +0000290 bool isBodyComplete() const {
291 const SharingMapTy *Top = getTopOfStackOrNull();
292 return Top && Top->BodyComplete;
293 }
294 void setBodyComplete() {
295 getTopOfStack().BodyComplete = true;
296 }
297
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000298 bool isForceVarCapturing() const { return ForceCapturing; }
299 void setForceVarCapturing(bool V) { ForceCapturing = V; }
300
Alexey Bataev60705422018-10-30 15:50:12 +0000301 void setForceCaptureByReferenceInTargetExecutable(bool V) {
302 ForceCaptureByReferenceInTargetExecutable = V;
303 }
304 bool isForceCaptureByReferenceInTargetExecutable() const {
305 return ForceCaptureByReferenceInTargetExecutable;
306 }
307
Alexey Bataev758e55e2013-09-06 18:03:48 +0000308 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000309 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000310 assert(!IgnoredStackElements &&
311 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000312 if (Stack.empty() ||
313 Stack.back().second != CurrentNonCapturingFunctionScope)
314 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
315 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
316 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000317 }
318
319 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000320 assert(!IgnoredStackElements &&
321 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000322 assert(!Stack.back().first.empty() &&
323 "Data-sharing attributes stack is empty!");
324 Stack.back().first.pop_back();
325 }
326
Richard Smith0621a8f2019-05-31 00:45:10 +0000327 /// RAII object to temporarily leave the scope of a directive when we want to
328 /// logically operate in its parent.
329 class ParentDirectiveScope {
330 DSAStackTy &Self;
331 bool Active;
332 public:
333 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
334 : Self(Self), Active(false) {
335 if (Activate)
336 enable();
337 }
338 ~ParentDirectiveScope() { disable(); }
339 void disable() {
340 if (Active) {
341 --Self.IgnoredStackElements;
342 Active = false;
343 }
344 }
345 void enable() {
346 if (!Active) {
347 ++Self.IgnoredStackElements;
348 Active = true;
349 }
350 }
351 };
352
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000353 /// Marks that we're started loop parsing.
354 void loopInit() {
355 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
356 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000357 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000358 }
359 /// Start capturing of the variables in the loop context.
360 void loopStart() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
362 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000363 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000364 }
365 /// true, if variables are captured, false otherwise.
366 bool isLoopStarted() const {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
368 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000369 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000370 }
371 /// Marks (or clears) declaration as possibly loop counter.
372 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000373 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000374 D ? D->getCanonicalDecl() : D;
375 }
376 /// Gets the possible loop counter decl.
377 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000378 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000379 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 /// Start new OpenMP region stack in new non-capturing function.
381 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000382 assert(!IgnoredStackElements &&
383 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
385 assert(!isa<CapturingScopeInfo>(CurFnScope));
386 CurrentNonCapturingFunctionScope = CurFnScope;
387 }
388 /// Pop region stack for non-capturing function.
389 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000390 assert(!IgnoredStackElements &&
391 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000392 if (!Stack.empty() && Stack.back().second == OldFSI) {
393 assert(Stack.back().first.empty());
394 Stack.pop_back();
395 }
396 CurrentNonCapturingFunctionScope = nullptr;
397 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
398 if (!isa<CapturingScopeInfo>(FSI)) {
399 CurrentNonCapturingFunctionScope = FSI;
400 break;
401 }
402 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000403 }
404
Alexey Bataeve3727102018-04-18 15:57:46 +0000405 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000406 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000407 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000408 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000409 getCriticalWithHint(const DeclarationNameInfo &Name) const {
410 auto I = Criticals.find(Name.getAsString());
411 if (I != Criticals.end())
412 return I->second;
413 return std::make_pair(nullptr, llvm::APSInt());
414 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000416 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000417 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000418 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000420 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000421 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000423 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000424 /// \return The index of the loop control variable in the list of associated
425 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000426 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000427 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000428 /// parent region.
429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000431 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000433 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000434 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000437 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000438 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439
Alexey Bataevfa312f32017-07-21 18:48:21 +0000440 /// Adds additional information for the reduction items with the reduction id
441 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000442 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000443 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000444 /// Adds additional information for the reduction items with the reduction id
445 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000446 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000447 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000448 /// Returns the location and reduction operation from the innermost parent
449 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000450 const DSAVarData
451 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
452 BinaryOperatorKind &BOK,
453 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000454 /// Returns the location and reduction operation from the innermost parent
455 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000456 const DSAVarData
457 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
458 const Expr *&ReductionRef,
459 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000460 /// Return reduction reference expression for the current taskgroup.
461 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000462 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000463 "taskgroup reference expression requested for non taskgroup "
464 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000465 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000466 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000467 /// Checks if the given \p VD declaration is actually a taskgroup reduction
468 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000469 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000470 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
471 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000472 ->getDecl() == VD;
473 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000474
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000475 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000476 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000477 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000478 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000479 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000480 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000481 /// match specified \a CPred predicate in any directive which matches \a DPred
482 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000483 const DSAVarData
484 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
485 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
486 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000488 /// match specified \a CPred predicate in any innermost directive which
489 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000490 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000491 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000492 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
493 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000494 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000496 /// attributes which match specified \a CPred predicate at the specified
497 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000498 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000499 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000500 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000502 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000503 /// specified \a DPred predicate.
504 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000506 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000509 bool hasDirective(
510 const llvm::function_ref<bool(
511 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
512 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000513 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000517 const SharingMapTy *Top = getTopOfStackOrNull();
518 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000521 OpenMPDirectiveKind getDirective(unsigned Level) const {
522 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000523 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000524 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000525 /// Returns the capture region at the specified level.
526 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
527 unsigned OpenMPCaptureLevel) const {
528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
529 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
530 return CaptureRegions[OpenMPCaptureLevel];
531 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000533 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000534 const SharingMapTy *Parent = getSecondOnStackOrNull();
535 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000536 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000537
Kelvin Li1408f912018-09-26 04:28:39 +0000538 /// Add requires decl to internal vector
539 void addRequiresDecl(OMPRequiresDecl *RD) {
540 RequiresDecls.push_back(RD);
541 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000542
Alexey Bataev318f431b2019-03-22 15:25:12 +0000543 /// Checks if the defined 'requires' directive has specified type of clause.
544 template <typename ClauseType>
545 bool hasRequiresDeclWithClause() {
546 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
547 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
548 return isa<ClauseType>(C);
549 });
550 });
551 }
552
Kelvin Li1408f912018-09-26 04:28:39 +0000553 /// Checks for a duplicate clause amongst previously declared requires
554 /// directives
555 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
556 bool IsDuplicate = false;
557 for (OMPClause *CNew : ClauseList) {
558 for (const OMPRequiresDecl *D : RequiresDecls) {
559 for (const OMPClause *CPrev : D->clauselists()) {
560 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
561 SemaRef.Diag(CNew->getBeginLoc(),
562 diag::err_omp_requires_clause_redeclaration)
563 << getOpenMPClauseName(CNew->getClauseKind());
564 SemaRef.Diag(CPrev->getBeginLoc(),
565 diag::note_omp_requires_previous_clause)
566 << getOpenMPClauseName(CPrev->getClauseKind());
567 IsDuplicate = true;
568 }
569 }
570 }
571 }
572 return IsDuplicate;
573 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000574
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000575 /// Add location of previously encountered target to internal vector
576 void addTargetDirLocation(SourceLocation LocStart) {
577 TargetLocations.push_back(LocStart);
578 }
579
580 // Return previously encountered target region locations.
581 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
582 return TargetLocations;
583 }
584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000585 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000586 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000587 getTopOfStack().DefaultAttr = DSA_none;
588 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000589 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000590 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000591 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000592 getTopOfStack().DefaultAttr = DSA_shared;
593 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000594 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000595 /// Set default data mapping attribute to 'tofrom:scalar'.
596 void setDefaultDMAToFromScalar(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000597 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
598 getTopOfStack().DefaultMapAttrLoc = Loc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600
601 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000602 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000603 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000604 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000605 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000606 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000607 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000608 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000609 DefaultMapAttributes getDefaultDMA() const {
610 return isStackEmpty() ? DMA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000611 : getTopOfStack().DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000612 }
613 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000614 return getStackElemAtLevel(Level).DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000615 }
616 SourceLocation getDefaultDMALocation() const {
617 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000618 : getTopOfStack().DefaultMapAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000619 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000622 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000623 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000624 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000625 }
626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000627 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000628 void setOrderedRegion(bool IsOrdered, const Expr *Param,
629 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000630 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000631 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000632 else
Richard Smith375dec52019-05-30 23:21:14 +0000633 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000634 }
635 /// Returns true, if region is ordered (has associated 'ordered' clause),
636 /// false - otherwise.
637 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000638 if (const SharingMapTy *Top = getTopOfStackOrNull())
639 return Top->OrderedRegion.hasValue();
640 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000641 }
642 /// Returns optional parameter for the ordered region.
643 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000644 if (const SharingMapTy *Top = getTopOfStackOrNull())
645 if (Top->OrderedRegion.hasValue())
646 return Top->OrderedRegion.getValue();
647 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000648 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000649 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000650 /// 'ordered' clause), false - otherwise.
651 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000652 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
653 return Parent->OrderedRegion.hasValue();
654 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000655 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000656 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000657 std::pair<const Expr *, OMPOrderedClause *>
658 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000659 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
660 if (Parent->OrderedRegion.hasValue())
661 return Parent->OrderedRegion.getValue();
662 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000663 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000664 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000665 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000666 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000667 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000668 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000669 /// 'nowait' clause), false - otherwise.
670 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000671 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
672 return Parent->NowaitRegion;
673 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000674 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000675 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000676 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000677 if (SharingMapTy *Parent = getSecondOnStackOrNull())
678 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000679 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000680 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000681 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000682 const SharingMapTy *Top = getTopOfStackOrNull();
683 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000684 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000686 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000687 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000688 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000689 if (Val > 1)
690 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000691 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000692 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000693 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000694 const SharingMapTy *Top = getTopOfStackOrNull();
695 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000696 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000697 /// Returns true if the construct is associated with multiple loops.
698 bool hasMutipleLoops() const {
699 const SharingMapTy *Top = getTopOfStackOrNull();
700 return Top ? Top->HasMutipleLoops : false;
701 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000702
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000703 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000704 /// region.
705 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000706 if (SharingMapTy *Parent = getSecondOnStackOrNull())
707 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000708 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000709 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000710 bool hasInnerTeamsRegion() const {
711 return getInnerTeamsRegionLoc().isValid();
712 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000713 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000714 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000715 const SharingMapTy *Top = getTopOfStackOrNull();
716 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000717 }
718
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000719 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000720 const SharingMapTy *Top = getTopOfStackOrNull();
721 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000722 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000723 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000724 const SharingMapTy *Top = getTopOfStackOrNull();
725 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000726 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000727
Samuel Antao4c8035b2016-12-12 18:00:20 +0000728 /// Do the check specified in \a Check to all component lists and return true
729 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000730 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000731 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000732 const llvm::function_ref<
733 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000734 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000735 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty())
737 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000738 auto SI = begin();
739 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000740
741 if (SI == SE)
742 return false;
743
Alexey Bataeve3727102018-04-18 15:57:46 +0000744 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000745 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000746 else
747 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000748
749 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000750 auto MI = SI->MappedExprComponents.find(VD);
751 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000752 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
753 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000754 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000755 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000756 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000757 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000758 }
759
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000760 /// Do the check specified in \a Check to all component lists at a given level
761 /// and return true if any issue is found.
762 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000763 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000764 const llvm::function_ref<
765 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000766 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000767 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000768 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000769 return false;
770
Richard Smith375dec52019-05-30 23:21:14 +0000771 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
772 auto MI = StackElem.MappedExprComponents.find(VD);
773 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000774 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
775 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000776 if (Check(L, MI->second.Kind))
777 return true;
778 return false;
779 }
780
Samuel Antao4c8035b2016-12-12 18:00:20 +0000781 /// Create a new mappable expression component list associated with a given
782 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000783 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000784 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000785 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
786 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000787 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000788 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000789 MEC.Components.resize(MEC.Components.size() + 1);
790 MEC.Components.back().append(Components.begin(), Components.end());
791 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000792 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793
794 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000795 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000796 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000797 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000798 void addDoacrossDependClause(OMPDependClause *C,
799 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000800 SharingMapTy *Parent = getSecondOnStackOrNull();
801 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
802 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000803 }
804 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
805 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000806 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000807 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000808 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000809 return llvm::make_range(Ref.begin(), Ref.end());
810 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000811 return llvm::make_range(StackElem.DoacrossDepends.end(),
812 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000813 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000814
815 // Store types of classes which have been explicitly mapped
816 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000817 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000818 StackElem.MappedClassesQualTypes.insert(QT);
819 }
820
821 // Return set of mapped classes types
822 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000823 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000824 return StackElem.MappedClassesQualTypes.count(QT) != 0;
825 }
826
Alexey Bataeva495c642019-03-11 19:51:42 +0000827 /// Adds global declare target to the parent target region.
828 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
829 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
830 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
831 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000832 for (auto &Elem : *this) {
833 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
834 Elem.DeclareTargetLinkVarDecls.push_back(E);
835 return;
836 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000837 }
838 }
839
840 /// Returns the list of globals with declare target link if current directive
841 /// is target.
842 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
843 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
844 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000845 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000846 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000847};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000848
849bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
850 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
851}
852
853bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000854 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
855 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000856}
Alexey Bataeve3727102018-04-18 15:57:46 +0000857
Alexey Bataeved09d242014-05-28 05:53:51 +0000858} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000859
Alexey Bataeve3727102018-04-18 15:57:46 +0000860static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000861 if (const auto *FE = dyn_cast<FullExpr>(E))
862 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000863
Alexey Bataeve3727102018-04-18 15:57:46 +0000864 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000865 E = MTE->GetTemporaryExpr();
866
Alexey Bataeve3727102018-04-18 15:57:46 +0000867 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000868 E = Binder->getSubExpr();
869
Alexey Bataeve3727102018-04-18 15:57:46 +0000870 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000871 E = ICE->getSubExprAsWritten();
872 return E->IgnoreParens();
873}
874
Alexey Bataeve3727102018-04-18 15:57:46 +0000875static Expr *getExprAsWritten(Expr *E) {
876 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
877}
878
879static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
880 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
881 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000882 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000883 const auto *VD = dyn_cast<VarDecl>(D);
884 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000885 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000886 VD = VD->getCanonicalDecl();
887 D = VD;
888 } else {
889 assert(FD);
890 FD = FD->getCanonicalDecl();
891 D = FD;
892 }
893 return D;
894}
895
Alexey Bataeve3727102018-04-18 15:57:46 +0000896static ValueDecl *getCanonicalDecl(ValueDecl *D) {
897 return const_cast<ValueDecl *>(
898 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
899}
900
Richard Smith375dec52019-05-30 23:21:14 +0000901DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000902 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000903 D = getCanonicalDecl(D);
904 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000905 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000906 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000907 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000908 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
909 // in a region but not in construct]
910 // File-scope or namespace-scope variables referenced in called routines
911 // in the region are shared unless they appear in a threadprivate
912 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000914 DVar.CKind = OMPC_shared;
915
916 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
917 // in a region but not in construct]
918 // Variables with static storage duration that are declared in called
919 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000920 if (VD && VD->hasGlobalStorage())
921 DVar.CKind = OMPC_shared;
922
923 // Non-static data members are shared by default.
924 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000925 DVar.CKind = OMPC_shared;
926
Alexey Bataev758e55e2013-09-06 18:03:48 +0000927 return DVar;
928 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000929
Alexey Bataevec3da872014-01-31 05:15:34 +0000930 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
931 // in a Construct, C/C++, predetermined, p.1]
932 // Variables with automatic storage duration that are declared in a scope
933 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000934 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
935 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000936 DVar.CKind = OMPC_private;
937 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000938 }
939
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000940 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000941 // Explicitly specified attributes and local variables with predetermined
942 // attributes.
943 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000944 const DSAInfo &Data = Iter->SharingMap.lookup(D);
945 DVar.RefExpr = Data.RefExpr.getPointer();
946 DVar.PrivateCopy = Data.PrivateCopy;
947 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000948 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000949 return DVar;
950 }
951
952 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
953 // in a Construct, C/C++, implicitly determined, p.1]
954 // In a parallel or task construct, the data-sharing attributes of these
955 // variables are determined by the default clause, if present.
956 switch (Iter->DefaultAttr) {
957 case DSA_shared:
958 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000959 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960 return DVar;
961 case DSA_none:
962 return DVar;
963 case DSA_unspecified:
964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
965 // in a Construct, implicitly determined, p.2]
966 // In a parallel construct, if no default clause is present, these
967 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000968 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000969 if (isOpenMPParallelDirective(DVar.DKind) ||
970 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000971 DVar.CKind = OMPC_shared;
972 return DVar;
973 }
974
975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
976 // in a Construct, implicitly determined, p.4]
977 // In a task construct, if no default clause is present, a variable that in
978 // the enclosing context is determined to be shared by all implicit tasks
979 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000980 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +0000982 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000983 do {
984 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000985 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000986 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987 // In a task construct, if no default clause is present, a variable
988 // whose data-sharing attribute is not determined by the rules above is
989 // firstprivate.
990 DVarTemp = getDSA(I, D);
991 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000992 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000993 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000994 return DVar;
995 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000996 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000997 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000998 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
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, implicitly determined, p.3]
1004 // For constructs other than task, if no default clause is present, these
1005 // variables inherit their data-sharing attributes from the enclosing
1006 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001007 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001008}
1009
Alexey Bataeve3727102018-04-18 15:57:46 +00001010const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1011 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001012 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001013 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001014 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001015 auto It = StackElem.AlignedMap.find(D);
1016 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001017 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001018 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001019 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001020 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001021 assert(It->second && "Unexpected nullptr expr in the aligned map");
1022 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001023}
1024
Alexey Bataeve3727102018-04-18 15:57:46 +00001025void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001026 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001027 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001028 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001029 StackElem.LCVMap.try_emplace(
1030 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001031}
1032
Alexey Bataeve3727102018-04-18 15:57:46 +00001033const DSAStackTy::LCDeclInfo
1034DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001035 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001036 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001037 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001038 auto It = StackElem.LCVMap.find(D);
1039 if (It != StackElem.LCVMap.end())
1040 return It->second;
1041 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001042}
1043
Alexey Bataeve3727102018-04-18 15:57:46 +00001044const DSAStackTy::LCDeclInfo
1045DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001046 const SharingMapTy *Parent = getSecondOnStackOrNull();
1047 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001048 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001049 auto It = Parent->LCVMap.find(D);
1050 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001051 return It->second;
1052 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001053}
1054
Alexey Bataeve3727102018-04-18 15:57:46 +00001055const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001056 const SharingMapTy *Parent = getSecondOnStackOrNull();
1057 assert(Parent && "Data-sharing attributes stack is empty");
1058 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001059 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001060 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001061 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001062 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001063 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001064}
1065
Alexey Bataeve3727102018-04-18 15:57:46 +00001066void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001067 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001068 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001069 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001070 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001071 Data.Attributes = A;
1072 Data.RefExpr.setPointer(E);
1073 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001074 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001075 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001076 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1077 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1078 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1079 (isLoopControlVariable(D).first && A == OMPC_private));
1080 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1081 Data.RefExpr.setInt(/*IntVal=*/true);
1082 return;
1083 }
1084 const bool IsLastprivate =
1085 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1086 Data.Attributes = A;
1087 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1088 Data.PrivateCopy = PrivateCopy;
1089 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001090 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001091 Data.Attributes = A;
1092 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1093 Data.PrivateCopy = nullptr;
1094 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095 }
1096}
1097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001098/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001099static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001100 StringRef Name, const AttrVec *Attrs = nullptr,
1101 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001102 DeclContext *DC = SemaRef.CurContext;
1103 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1104 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001105 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001106 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1107 if (Attrs) {
1108 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1109 I != E; ++I)
1110 Decl->addAttr(*I);
1111 }
1112 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001113 if (OrigRef) {
1114 Decl->addAttr(
1115 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1116 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001117 return Decl;
1118}
1119
1120static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1121 SourceLocation Loc,
1122 bool RefersToCapture = false) {
1123 D->setReferenced();
1124 D->markUsed(S.Context);
1125 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1126 SourceLocation(), D, RefersToCapture, Loc, Ty,
1127 VK_LValue);
1128}
1129
Alexey Bataeve3727102018-04-18 15:57:46 +00001130void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001131 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001132 D = getCanonicalDecl(D);
1133 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001134 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001135 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001136 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001137 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001138 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001139 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001140 "Additional reduction info may be specified only once for reduction "
1141 "items.");
1142 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001143 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001144 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001145 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001146 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1147 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001148 TaskgroupReductionRef =
1149 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001150 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001151}
1152
Alexey Bataeve3727102018-04-18 15:57:46 +00001153void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001154 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001155 D = getCanonicalDecl(D);
1156 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001157 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001158 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001159 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001160 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001161 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001162 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001163 "Additional reduction info may be specified only once for reduction "
1164 "items.");
1165 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001166 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001167 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001168 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001169 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1170 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001171 TaskgroupReductionRef =
1172 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001173 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001174}
1175
Alexey Bataeve3727102018-04-18 15:57:46 +00001176const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1177 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1178 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001179 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001180 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001181 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001182 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001183 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001184 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001185 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001186 if (!ReductionData.ReductionOp ||
1187 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001188 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001189 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001190 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001191 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1192 "expression for the descriptor is not "
1193 "set.");
1194 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001195 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1196 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001197 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001198 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001199}
1200
Alexey Bataeve3727102018-04-18 15:57:46 +00001201const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1202 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1203 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001204 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001205 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001206 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001207 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001208 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001209 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001210 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001211 if (!ReductionData.ReductionOp ||
1212 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001213 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001214 SR = ReductionData.ReductionRange;
1215 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001216 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1217 "expression for the descriptor is not "
1218 "set.");
1219 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001220 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1221 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001222 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001223 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001224}
1225
Richard Smith375dec52019-05-30 23:21:14 +00001226bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001227 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001228 for (const_iterator E = end(); I != E; ++I) {
1229 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1230 isOpenMPTargetExecutionDirective(I->Directive)) {
1231 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1232 Scope *CurScope = getCurScope();
1233 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1234 CurScope = CurScope->getParent();
1235 return CurScope != TopScope;
1236 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001237 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001238 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001239}
1240
Joel E. Dennyd2649292019-01-04 22:11:56 +00001241static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1242 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001243 bool *IsClassType = nullptr) {
1244 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001245 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001246 bool IsConstant = Type.isConstant(Context);
1247 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001248 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1249 ? Type->getAsCXXRecordDecl()
1250 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001251 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1252 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1253 RD = CTD->getTemplatedDecl();
1254 if (IsClassType)
1255 *IsClassType = RD;
1256 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1257 RD->hasDefinition() && RD->hasMutableFields());
1258}
1259
Joel E. Dennyd2649292019-01-04 22:11:56 +00001260static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1261 QualType Type, OpenMPClauseKind CKind,
1262 SourceLocation ELoc,
1263 bool AcceptIfMutable = true,
1264 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001265 ASTContext &Context = SemaRef.getASTContext();
1266 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001267 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1268 unsigned Diag = ListItemNotVar
1269 ? diag::err_omp_const_list_item
1270 : IsClassType ? diag::err_omp_const_not_mutable_variable
1271 : diag::err_omp_const_variable;
1272 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1273 if (!ListItemNotVar && D) {
1274 const VarDecl *VD = dyn_cast<VarDecl>(D);
1275 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1276 VarDecl::DeclarationOnly;
1277 SemaRef.Diag(D->getLocation(),
1278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1279 << D;
1280 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001281 return true;
1282 }
1283 return false;
1284}
1285
Alexey Bataeve3727102018-04-18 15:57:46 +00001286const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1287 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001288 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001289 DSAVarData DVar;
1290
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001291 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001292 auto TI = Threadprivates.find(D);
1293 if (TI != Threadprivates.end()) {
1294 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001295 DVar.CKind = OMPC_threadprivate;
1296 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001297 }
1298 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001299 DVar.RefExpr = buildDeclRefExpr(
1300 SemaRef, VD, D->getType().getNonReferenceType(),
1301 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1302 DVar.CKind = OMPC_threadprivate;
1303 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001304 return DVar;
1305 }
1306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1307 // in a Construct, C/C++, predetermined, p.1]
1308 // Variables appearing in threadprivate directives are threadprivate.
1309 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1310 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1311 SemaRef.getLangOpts().OpenMPUseTLS &&
1312 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1313 (VD && VD->getStorageClass() == SC_Register &&
1314 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1315 DVar.RefExpr = buildDeclRefExpr(
1316 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1317 DVar.CKind = OMPC_threadprivate;
1318 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1319 return DVar;
1320 }
1321 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1322 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1323 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001324 const_iterator IterTarget =
1325 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1326 return isOpenMPTargetExecutionDirective(Data.Directive);
1327 });
1328 if (IterTarget != end()) {
1329 const_iterator ParentIterTarget = IterTarget + 1;
1330 for (const_iterator Iter = begin();
1331 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001332 if (isOpenMPLocal(VD, Iter)) {
1333 DVar.RefExpr =
1334 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1335 D->getLocation());
1336 DVar.CKind = OMPC_threadprivate;
1337 return DVar;
1338 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001339 }
Richard Smith375dec52019-05-30 23:21:14 +00001340 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001341 auto DSAIter = IterTarget->SharingMap.find(D);
1342 if (DSAIter != IterTarget->SharingMap.end() &&
1343 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1344 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1345 DVar.CKind = OMPC_threadprivate;
1346 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001347 }
Richard Smith375dec52019-05-30 23:21:14 +00001348 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001349 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001350 D, std::distance(ParentIterTarget, End),
1351 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001352 DVar.RefExpr =
1353 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1354 IterTarget->ConstructLoc);
1355 DVar.CKind = OMPC_threadprivate;
1356 return DVar;
1357 }
1358 }
1359 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001360 }
1361
Alexey Bataev4b465392017-04-26 15:06:24 +00001362 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001363 // Not in OpenMP execution region and top scope was already checked.
1364 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001365
Alexey Bataev758e55e2013-09-06 18:03:48 +00001366 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001367 // in a Construct, C/C++, predetermined, p.4]
1368 // Static data members are shared.
1369 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1370 // in a Construct, C/C++, predetermined, p.7]
1371 // Variables with static storage duration that are declared in a scope
1372 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001373 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001374 // Check for explicitly specified attributes.
1375 const_iterator I = begin();
1376 const_iterator EndI = end();
1377 if (FromParent && I != EndI)
1378 ++I;
1379 auto It = I->SharingMap.find(D);
1380 if (It != I->SharingMap.end()) {
1381 const DSAInfo &Data = It->getSecond();
1382 DVar.RefExpr = Data.RefExpr.getPointer();
1383 DVar.PrivateCopy = Data.PrivateCopy;
1384 DVar.CKind = Data.Attributes;
1385 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1386 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001387 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001388 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001389
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001390 DVar.CKind = OMPC_shared;
1391 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001392 }
1393
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001394 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001395 // The predetermined shared attribute for const-qualified types having no
1396 // mutable members was removed after OpenMP 3.1.
1397 if (SemaRef.LangOpts.OpenMP <= 31) {
1398 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1399 // in a Construct, C/C++, predetermined, p.6]
1400 // Variables with const qualified type having no mutable member are
1401 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001402 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001403 // Variables with const-qualified type having no mutable member may be
1404 // listed in a firstprivate clause, even if they are static data members.
1405 DSAVarData DVarTemp = hasInnermostDSA(
1406 D,
1407 [](OpenMPClauseKind C) {
1408 return C == OMPC_firstprivate || C == OMPC_shared;
1409 },
1410 MatchesAlways, FromParent);
1411 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1412 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001413
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001414 DVar.CKind = OMPC_shared;
1415 return DVar;
1416 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001417 }
1418
Alexey Bataev758e55e2013-09-06 18:03:48 +00001419 // Explicitly specified attributes and local variables with predetermined
1420 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001421 const_iterator I = begin();
1422 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001423 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001424 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001425 auto It = I->SharingMap.find(D);
1426 if (It != I->SharingMap.end()) {
1427 const DSAInfo &Data = It->getSecond();
1428 DVar.RefExpr = Data.RefExpr.getPointer();
1429 DVar.PrivateCopy = Data.PrivateCopy;
1430 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001431 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001432 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001433 }
1434
1435 return DVar;
1436}
1437
Alexey Bataeve3727102018-04-18 15:57:46 +00001438const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1439 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001440 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001441 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001442 return getDSA(I, D);
1443 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001445 const_iterator StartI = begin();
1446 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001447 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001448 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001450}
1451
Alexey Bataeve3727102018-04-18 15:57:46 +00001452const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001453DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001454 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1455 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001456 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001457 if (isStackEmpty())
1458 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001459 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001460 const_iterator I = begin();
1461 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001462 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001463 ++I;
1464 for (; I != EndI; ++I) {
1465 if (!DPred(I->Directive) &&
1466 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001467 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001468 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001469 DSAVarData DVar = getDSA(NewI, D);
1470 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001471 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001472 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001473 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001474}
1475
Alexey Bataeve3727102018-04-18 15:57:46 +00001476const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001477 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1478 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001479 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001480 if (isStackEmpty())
1481 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001482 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001483 const_iterator StartI = begin();
1484 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001485 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001486 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001487 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001488 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001489 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001490 DSAVarData DVar = getDSA(NewI, D);
1491 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001492}
1493
Alexey Bataevaac108a2015-06-23 04:51:00 +00001494bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001495 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1496 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001497 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001498 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001499 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001500 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1501 auto I = StackElem.SharingMap.find(D);
1502 if (I != StackElem.SharingMap.end() &&
1503 I->getSecond().RefExpr.getPointer() &&
1504 CPred(I->getSecond().Attributes) &&
1505 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001506 return true;
1507 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001508 auto LI = StackElem.LCVMap.find(D);
1509 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001510 return CPred(OMPC_private);
1511 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001512}
1513
Samuel Antao4be30e92015-10-02 17:14:03 +00001514bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001515 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1516 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001517 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001518 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001519 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1520 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001521}
1522
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001523bool DSAStackTy::hasDirective(
1524 const llvm::function_ref<bool(OpenMPDirectiveKind,
1525 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001526 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001527 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001528 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001529 size_t Skip = FromParent ? 2 : 1;
1530 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1531 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001532 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1533 return true;
1534 }
1535 return false;
1536}
1537
Alexey Bataev758e55e2013-09-06 18:03:48 +00001538void Sema::InitDataSharingAttributesStack() {
1539 VarDataSharingAttributesStack = new DSAStackTy(*this);
1540}
1541
1542#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1543
Alexey Bataev4b465392017-04-26 15:06:24 +00001544void Sema::pushOpenMPFunctionRegion() {
1545 DSAStack->pushFunction();
1546}
1547
1548void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1549 DSAStack->popFunction(OldFSI);
1550}
1551
Alexey Bataevc416e642019-02-08 18:02:25 +00001552static bool isOpenMPDeviceDelayedContext(Sema &S) {
1553 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1554 "Expected OpenMP device compilation.");
1555 return !S.isInOpenMPTargetExecutionDirective() &&
1556 !S.isInOpenMPDeclareTargetContext();
1557}
1558
Alexey Bataev729e2422019-08-23 16:11:14 +00001559namespace {
1560/// Status of the function emission on the host/device.
1561enum class FunctionEmissionStatus {
1562 Emitted,
1563 Discarded,
1564 Unknown,
1565};
1566} // anonymous namespace
1567
Alexey Bataevc416e642019-02-08 18:02:25 +00001568/// Do we know that we will eventually codegen the given function?
Alexey Bataev729e2422019-08-23 16:11:14 +00001569static FunctionEmissionStatus isKnownDeviceEmitted(Sema &S, FunctionDecl *FD) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001570 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1571 "Expected OpenMP device compilation.");
1572 // Templates are emitted when they're instantiated.
1573 if (FD->isDependentContext())
Alexey Bataev729e2422019-08-23 16:11:14 +00001574 return FunctionEmissionStatus::Discarded;
Alexey Bataevc416e642019-02-08 18:02:25 +00001575
Alexey Bataev729e2422019-08-23 16:11:14 +00001576 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
1577 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
1578 if (DevTy.hasValue())
1579 return (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
1580 ? FunctionEmissionStatus::Discarded
1581 : FunctionEmissionStatus::Emitted;
Alexey Bataevc416e642019-02-08 18:02:25 +00001582
1583 // Otherwise, the function is known-emitted if it's in our set of
1584 // known-emitted functions.
Alexey Bataev729e2422019-08-23 16:11:14 +00001585 return (S.DeviceKnownEmittedFns.count(FD) > 0)
1586 ? FunctionEmissionStatus::Emitted
1587 : FunctionEmissionStatus::Unknown;
Alexey Bataevc416e642019-02-08 18:02:25 +00001588}
1589
1590Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1591 unsigned DiagID) {
1592 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1593 "Expected OpenMP device compilation.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001594 FunctionEmissionStatus FES =
1595 isKnownDeviceEmitted(*this, getCurFunctionDecl());
1596 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1597 switch (FES) {
1598 case FunctionEmissionStatus::Emitted:
1599 Kind = DeviceDiagBuilder::K_Immediate;
1600 break;
1601 case FunctionEmissionStatus::Unknown:
1602 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1603 : DeviceDiagBuilder::K_Immediate;
1604 break;
1605 case FunctionEmissionStatus::Discarded:
1606 Kind = DeviceDiagBuilder::K_Nop;
1607 break;
1608 }
1609
1610 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1611}
1612
1613/// Do we know that we will eventually codegen the given function?
1614static FunctionEmissionStatus isKnownHostEmitted(Sema &S, FunctionDecl *FD) {
1615 assert(S.LangOpts.OpenMP && !S.LangOpts.OpenMPIsDevice &&
1616 "Expected OpenMP host compilation.");
1617 // In OpenMP 4.5 all the functions are host functions.
1618 if (S.LangOpts.OpenMP <= 45)
1619 return FunctionEmissionStatus::Emitted;
1620
1621 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
1622 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
1623 if (DevTy.hasValue())
1624 return (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
1625 ? FunctionEmissionStatus::Discarded
1626 : FunctionEmissionStatus::Emitted;
1627
1628 // Otherwise, the function is known-emitted if it's in our set of
1629 // known-emitted functions.
1630 return (S.DeviceKnownEmittedFns.count(FD) > 0)
1631 ? FunctionEmissionStatus::Emitted
1632 : FunctionEmissionStatus::Unknown;
1633}
1634
1635Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1636 unsigned DiagID) {
1637 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1638 "Expected OpenMP host compilation.");
1639 FunctionEmissionStatus FES =
1640 isKnownHostEmitted(*this, getCurFunctionDecl());
1641 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1642 switch (FES) {
1643 case FunctionEmissionStatus::Emitted:
1644 Kind = DeviceDiagBuilder::K_Immediate;
1645 break;
1646 case FunctionEmissionStatus::Unknown:
1647 Kind = DeviceDiagBuilder::K_Deferred;
1648 break;
1649 case FunctionEmissionStatus::Discarded:
1650 Kind = DeviceDiagBuilder::K_Nop;
1651 break;
1652 }
1653
1654 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001655}
1656
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001657void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1658 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001659 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1660 "Expected OpenMP device compilation.");
1661 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001662 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001663 FunctionDecl *Caller = getCurFunctionDecl();
1664
Alexey Bataev729e2422019-08-23 16:11:14 +00001665 // host only function are not available on the device.
1666 if (Caller &&
1667 (isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted ||
1668 (!isOpenMPDeviceDelayedContext(*this) &&
1669 isKnownDeviceEmitted(*this, Caller) ==
1670 FunctionEmissionStatus::Unknown)) &&
1671 isKnownDeviceEmitted(*this, Callee) ==
1672 FunctionEmissionStatus::Discarded) {
1673 StringRef HostDevTy =
1674 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
1675 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1676 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1677 diag::note_omp_marked_device_type_here)
1678 << HostDevTy;
1679 return;
1680 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001681 // If the caller is known-emitted, mark the callee as known-emitted.
1682 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001683 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1684 (!Caller && !CheckForDelayedContext) ||
Alexey Bataev729e2422019-08-23 16:11:14 +00001685 (Caller &&
1686 isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001687 markKnownEmitted(*this, Caller, Callee, Loc,
1688 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001689 return CheckForDelayedContext &&
1690 isKnownDeviceEmitted(S, FD) ==
1691 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001692 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001693 else if (Caller)
1694 DeviceCallGraph[Caller].insert({Callee, Loc});
1695}
1696
Alexey Bataev729e2422019-08-23 16:11:14 +00001697void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1698 bool CheckCaller) {
1699 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1700 "Expected OpenMP host compilation.");
1701 assert(Callee && "Callee may not be null.");
1702 Callee = Callee->getMostRecentDecl();
1703 FunctionDecl *Caller = getCurFunctionDecl();
1704
1705 // device only function are not available on the host.
1706 if (Caller &&
1707 isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted &&
1708 isKnownHostEmitted(*this, Callee) == FunctionEmissionStatus::Discarded) {
1709 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1710 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1711 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1712 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1713 diag::note_omp_marked_device_type_here)
1714 << NoHostDevTy;
1715 return;
1716 }
1717 // If the caller is known-emitted, mark the callee as known-emitted.
1718 // Otherwise, mark the call in our call graph so we can traverse it later.
1719 if ((!CheckCaller && !Caller) ||
1720 (Caller &&
1721 isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
1722 markKnownEmitted(
1723 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1724 return CheckCaller &&
1725 isKnownHostEmitted(S, FD) == FunctionEmissionStatus::Emitted;
1726 });
1727 else if (Caller)
1728 DeviceCallGraph[Caller].insert({Callee, Loc});
1729}
1730
Alexey Bataev123ad192019-02-27 20:29:45 +00001731void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1732 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1733 "OpenMP device compilation mode is expected.");
1734 QualType Ty = E->getType();
1735 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001736 ((Ty->isFloat128Type() ||
1737 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1738 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001739 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1740 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001741 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1742 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1743 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001744}
1745
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001746bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1747 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001748 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1749
Alexey Bataeve3727102018-04-18 15:57:46 +00001750 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001751 bool IsByRef = true;
1752
1753 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001754 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001755 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001756
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001757 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001758 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001759 // This table summarizes how a given variable should be passed to the device
1760 // given its type and the clauses where it appears. This table is based on
1761 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1762 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1763 //
1764 // =========================================================================
1765 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1766 // | |(tofrom:scalar)| | pvt | | | |
1767 // =========================================================================
1768 // | scl | | | | - | | bycopy|
1769 // | scl | | - | x | - | - | bycopy|
1770 // | scl | | x | - | - | - | null |
1771 // | scl | x | | | - | | byref |
1772 // | scl | x | - | x | - | - | bycopy|
1773 // | scl | x | x | - | - | - | null |
1774 // | scl | | - | - | - | x | byref |
1775 // | scl | x | - | - | - | x | byref |
1776 //
1777 // | agg | n.a. | | | - | | byref |
1778 // | agg | n.a. | - | x | - | - | byref |
1779 // | agg | n.a. | x | - | - | - | null |
1780 // | agg | n.a. | - | - | - | x | byref |
1781 // | agg | n.a. | - | - | - | x[] | byref |
1782 //
1783 // | ptr | n.a. | | | - | | bycopy|
1784 // | ptr | n.a. | - | x | - | - | bycopy|
1785 // | ptr | n.a. | x | - | - | - | null |
1786 // | ptr | n.a. | - | - | - | x | byref |
1787 // | ptr | n.a. | - | - | - | x[] | bycopy|
1788 // | ptr | n.a. | - | - | x | | bycopy|
1789 // | ptr | n.a. | - | - | x | x | bycopy|
1790 // | ptr | n.a. | - | - | x | x[] | bycopy|
1791 // =========================================================================
1792 // Legend:
1793 // scl - scalar
1794 // ptr - pointer
1795 // agg - aggregate
1796 // x - applies
1797 // - - invalid in this combination
1798 // [] - mapped with an array section
1799 // byref - should be mapped by reference
1800 // byval - should be mapped by value
1801 // null - initialize a local variable to null on the device
1802 //
1803 // Observations:
1804 // - All scalar declarations that show up in a map clause have to be passed
1805 // by reference, because they may have been mapped in the enclosing data
1806 // environment.
1807 // - If the scalar value does not fit the size of uintptr, it has to be
1808 // passed by reference, regardless the result in the table above.
1809 // - For pointers mapped by value that have either an implicit map or an
1810 // array section, the runtime library may pass the NULL value to the
1811 // device instead of the value passed to it by the compiler.
1812
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001813 if (Ty->isReferenceType())
1814 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001815
1816 // Locate map clauses and see if the variable being captured is referred to
1817 // in any of those clauses. Here we only care about variables, not fields,
1818 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001819 bool IsVariableAssociatedWithSection = false;
1820
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001821 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001822 D, Level,
1823 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1824 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001825 MapExprComponents,
1826 OpenMPClauseKind WhereFoundClauseKind) {
1827 // Only the map clause information influences how a variable is
1828 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001829 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001830 if (WhereFoundClauseKind != OMPC_map)
1831 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001832
1833 auto EI = MapExprComponents.rbegin();
1834 auto EE = MapExprComponents.rend();
1835
1836 assert(EI != EE && "Invalid map expression!");
1837
1838 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1839 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1840
1841 ++EI;
1842 if (EI == EE)
1843 return false;
1844
1845 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1846 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1847 isa<MemberExpr>(EI->getAssociatedExpression())) {
1848 IsVariableAssociatedWithSection = true;
1849 // There is nothing more we need to know about this variable.
1850 return true;
1851 }
1852
1853 // Keep looking for more map info.
1854 return false;
1855 });
1856
1857 if (IsVariableUsedInMapClause) {
1858 // If variable is identified in a map clause it is always captured by
1859 // reference except if it is a pointer that is dereferenced somehow.
1860 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1861 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001862 // By default, all the data that has a scalar type is mapped by copy
1863 // (except for reduction variables).
1864 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001865 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1866 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001867 !Ty->isScalarType() ||
1868 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1869 DSAStack->hasExplicitDSA(
1870 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001871 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001872 }
1873
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001874 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001875 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001876 ((IsVariableUsedInMapClause &&
1877 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1878 OMPD_target) ||
1879 !DSAStack->hasExplicitDSA(
1880 D,
1881 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1882 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001883 // If the variable is artificial and must be captured by value - try to
1884 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001885 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1886 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001887 }
1888
Samuel Antao86ace552016-04-27 22:40:57 +00001889 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001890 // and alignment, because the runtime library only deals with uintptr types.
1891 // If it does not fit the uintptr size, we need to pass the data by reference
1892 // instead.
1893 if (!IsByRef &&
1894 (Ctx.getTypeSizeInChars(Ty) >
1895 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001896 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001897 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001898 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001899
1900 return IsByRef;
1901}
1902
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001903unsigned Sema::getOpenMPNestingLevel() const {
1904 assert(getLangOpts().OpenMP);
1905 return DSAStack->getNestingLevel();
1906}
1907
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001908bool Sema::isInOpenMPTargetExecutionDirective() const {
1909 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1910 !DSAStack->isClauseParsingMode()) ||
1911 DSAStack->hasDirective(
1912 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1913 SourceLocation) -> bool {
1914 return isOpenMPTargetExecutionDirective(K);
1915 },
1916 false);
1917}
1918
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001919VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1920 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001921 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001922 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001923
Richard Smith0621a8f2019-05-31 00:45:10 +00001924 // If we want to determine whether the variable should be captured from the
1925 // perspective of the current capturing scope, and we've already left all the
1926 // capturing scopes of the top directive on the stack, check from the
1927 // perspective of its parent directive (if any) instead.
1928 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1929 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1930
Samuel Antao4be30e92015-10-02 17:14:03 +00001931 // If we are attempting to capture a global variable in a directive with
1932 // 'target' we return true so that this global is also mapped to the device.
1933 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001934 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001935 if (VD && !VD->hasLocalStorage() &&
1936 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1937 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001938 // Try to mark variable as declare target if it is used in capturing
1939 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001940 if (LangOpts.OpenMP <= 45 &&
1941 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001942 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001943 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001944 } else if (isInOpenMPTargetExecutionDirective()) {
1945 // If the declaration is enclosed in a 'declare target' directive,
1946 // then it should not be captured.
1947 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001948 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001949 return nullptr;
1950 return VD;
1951 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001952 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001953
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001954 if (CheckScopeInfo) {
1955 bool OpenMPFound = false;
1956 for (unsigned I = StopAt + 1; I > 0; --I) {
1957 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1958 if(!isa<CapturingScopeInfo>(FSI))
1959 return nullptr;
1960 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1961 if (RSI->CapRegionKind == CR_OpenMP) {
1962 OpenMPFound = true;
1963 break;
1964 }
1965 }
1966 if (!OpenMPFound)
1967 return nullptr;
1968 }
1969
Alexey Bataev48977c32015-08-04 08:10:48 +00001970 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1971 (!DSAStack->isClauseParsingMode() ||
1972 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001973 auto &&Info = DSAStack->isLoopControlVariable(D);
1974 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001975 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001976 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001977 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001978 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001979 DSAStackTy::DSAVarData DVarPrivate =
1980 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001981 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001982 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00001983 // Threadprivate variables must not be captured.
1984 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
1985 return nullptr;
1986 // The variable is not private or it is the variable in the directive with
1987 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001988 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1989 [](OpenMPDirectiveKind) { return true; },
1990 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001991 if (DVarPrivate.CKind != OMPC_unknown ||
1992 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001993 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001994 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001995 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001996}
1997
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001998void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1999 unsigned Level) const {
2000 SmallVector<OpenMPDirectiveKind, 4> Regions;
2001 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2002 FunctionScopesIndex -= Regions.size();
2003}
2004
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002005void Sema::startOpenMPLoop() {
2006 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2007 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2008 DSAStack->loopInit();
2009}
2010
Alexey Bataeve3727102018-04-18 15:57:46 +00002011bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002012 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002013 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2014 if (DSAStack->getAssociatedLoops() > 0 &&
2015 !DSAStack->isLoopStarted()) {
2016 DSAStack->resetPossibleLoopCounter(D);
2017 DSAStack->loopStart();
2018 return true;
2019 }
2020 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2021 DSAStack->isLoopControlVariable(D).first) &&
2022 !DSAStack->hasExplicitDSA(
2023 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2024 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2025 return true;
2026 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002027 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2028 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2029 DSAStack->isForceVarCapturing() &&
2030 !DSAStack->hasExplicitDSA(
2031 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2032 return true;
2033 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002034 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002035 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002036 (DSAStack->isClauseParsingMode() &&
2037 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002038 // Consider taskgroup reduction descriptor variable a private to avoid
2039 // possible capture in the region.
2040 (DSAStack->hasExplicitDirective(
2041 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2042 Level) &&
2043 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002044}
2045
Alexey Bataeve3727102018-04-18 15:57:46 +00002046void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2047 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002048 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2049 D = getCanonicalDecl(D);
2050 OpenMPClauseKind OMPC = OMPC_unknown;
2051 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2052 const unsigned NewLevel = I - 1;
2053 if (DSAStack->hasExplicitDSA(D,
2054 [&OMPC](const OpenMPClauseKind K) {
2055 if (isOpenMPPrivate(K)) {
2056 OMPC = K;
2057 return true;
2058 }
2059 return false;
2060 },
2061 NewLevel))
2062 break;
2063 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2064 D, NewLevel,
2065 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2066 OpenMPClauseKind) { return true; })) {
2067 OMPC = OMPC_map;
2068 break;
2069 }
2070 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2071 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002072 OMPC = OMPC_map;
2073 if (D->getType()->isScalarType() &&
2074 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
2075 DefaultMapAttributes::DMA_tofrom_scalar)
2076 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002077 break;
2078 }
2079 }
2080 if (OMPC != OMPC_unknown)
2081 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2082}
2083
Alexey Bataeve3727102018-04-18 15:57:46 +00002084bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2085 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002086 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2087 // Return true if the current level is no longer enclosed in a target region.
2088
Alexey Bataeve3727102018-04-18 15:57:46 +00002089 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002090 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002091 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2092 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002093}
2094
Alexey Bataeved09d242014-05-28 05:53:51 +00002095void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002096
Alexey Bataev729e2422019-08-23 16:11:14 +00002097void Sema::finalizeOpenMPDelayedAnalysis() {
2098 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2099 // Diagnose implicit declare target functions and their callees.
2100 for (const auto &CallerCallees : DeviceCallGraph) {
2101 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2102 OMPDeclareTargetDeclAttr::getDeviceType(
2103 CallerCallees.getFirst()->getMostRecentDecl());
2104 // Ignore host functions during device analyzis.
2105 if (LangOpts.OpenMPIsDevice && DevTy &&
2106 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2107 continue;
2108 // Ignore nohost functions during host analyzis.
2109 if (!LangOpts.OpenMPIsDevice && DevTy &&
2110 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2111 continue;
2112 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2113 &Callee : CallerCallees.getSecond()) {
2114 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2115 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2116 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2117 if (LangOpts.OpenMPIsDevice && DevTy &&
2118 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2119 // Diagnose host function called during device codegen.
2120 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2121 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2122 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2123 << HostDevTy << 0;
2124 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2125 diag::note_omp_marked_device_type_here)
2126 << HostDevTy;
2127 continue;
2128 }
2129 if (!LangOpts.OpenMPIsDevice && DevTy &&
2130 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2131 // Diagnose nohost function called during host codegen.
2132 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2133 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2134 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2135 << NoHostDevTy << 1;
2136 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2137 diag::note_omp_marked_device_type_here)
2138 << NoHostDevTy;
2139 continue;
2140 }
2141 }
2142 }
2143}
2144
Alexey Bataev758e55e2013-09-06 18:03:48 +00002145void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2146 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002147 Scope *CurScope, SourceLocation Loc) {
2148 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002149 PushExpressionEvaluationContext(
2150 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002151}
2152
Alexey Bataevaac108a2015-06-23 04:51:00 +00002153void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2154 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002155}
2156
Alexey Bataevaac108a2015-06-23 04:51:00 +00002157void Sema::EndOpenMPClause() {
2158 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002159}
2160
Alexey Bataeve106f252019-04-01 14:25:31 +00002161static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2162 ArrayRef<OMPClause *> Clauses);
2163
Alexey Bataev758e55e2013-09-06 18:03:48 +00002164void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002165 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2166 // A variable of class type (or array thereof) that appears in a lastprivate
2167 // clause requires an accessible, unambiguous default constructor for the
2168 // class type, unless the list item is also specified in a firstprivate
2169 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002170 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2171 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002172 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2173 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002174 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002175 if (DE->isValueDependent() || DE->isTypeDependent()) {
2176 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002177 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002178 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002179 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002180 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002181 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002182 const DSAStackTy::DSAVarData DVar =
2183 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002184 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002185 // Generate helper private variable and initialize it with the
2186 // default value. The address of the original variable is replaced
2187 // by the address of the new private variable in CodeGen. This new
2188 // variable is not added to IdResolver, so the code in the OpenMP
2189 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002190 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002191 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002192 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002193 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002194 if (VDPrivate->isInvalidDecl()) {
2195 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002196 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002197 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002198 PrivateCopies.push_back(buildDeclRefExpr(
2199 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002200 } else {
2201 // The variable is also a firstprivate, so initialization sequence
2202 // for private copy is generated already.
2203 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002204 }
2205 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002206 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002207 }
2208 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002209 // Check allocate clauses.
2210 if (!CurContext->isDependentContext())
2211 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002212 }
2213
Alexey Bataev758e55e2013-09-06 18:03:48 +00002214 DSAStack->pop();
2215 DiscardCleanupsInEvaluationContext();
2216 PopExpressionEvaluationContext();
2217}
2218
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002219static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2220 Expr *NumIterations, Sema &SemaRef,
2221 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002222
Alexey Bataeva769e072013-03-22 06:34:35 +00002223namespace {
2224
Alexey Bataeve3727102018-04-18 15:57:46 +00002225class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002226private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002227 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002228
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002229public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002230 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002231 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002232 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002233 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002234 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002235 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2236 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002237 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002238 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002239 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002240
2241 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002242 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002243 }
2244
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002245};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002246
Alexey Bataeve3727102018-04-18 15:57:46 +00002247class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002248private:
2249 Sema &SemaRef;
2250
2251public:
2252 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2253 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2254 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002255 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2256 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002257 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2258 SemaRef.getCurScope());
2259 }
2260 return false;
2261 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002262
2263 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002264 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002265 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002266};
2267
Alexey Bataeved09d242014-05-28 05:53:51 +00002268} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002269
2270ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2271 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002272 const DeclarationNameInfo &Id,
2273 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002274 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2275 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2276
2277 if (Lookup.isAmbiguous())
2278 return ExprError();
2279
2280 VarDecl *VD;
2281 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002282 VarDeclFilterCCC CCC(*this);
2283 if (TypoCorrection Corrected =
2284 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2285 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002286 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002287 PDiag(Lookup.empty()
2288 ? diag::err_undeclared_var_use_suggest
2289 : diag::err_omp_expected_var_arg_suggest)
2290 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002291 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002292 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002293 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2294 : diag::err_omp_expected_var_arg)
2295 << Id.getName();
2296 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002297 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002298 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2299 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2300 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2301 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002302 }
2303 Lookup.suppressDiagnostics();
2304
2305 // OpenMP [2.9.2, Syntax, C/C++]
2306 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002307 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002308 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002309 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002310 bool IsDecl =
2311 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002312 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002313 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2314 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315 return ExprError();
2316 }
2317
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002318 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002319 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002320 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2321 // A threadprivate directive for file-scope variables must appear outside
2322 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002323 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2324 !getCurLexicalContext()->isTranslationUnit()) {
2325 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002326 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002327 bool IsDecl =
2328 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2329 Diag(VD->getLocation(),
2330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2331 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002332 return ExprError();
2333 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002334 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2335 // A threadprivate directive for static class member variables must appear
2336 // in the class definition, in the same scope in which the member
2337 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002338 if (CanonicalVD->isStaticDataMember() &&
2339 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2340 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002341 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002342 bool IsDecl =
2343 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2344 Diag(VD->getLocation(),
2345 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2346 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002347 return ExprError();
2348 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002349 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2350 // A threadprivate directive for namespace-scope variables must appear
2351 // outside any definition or declaration other than the namespace
2352 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002353 if (CanonicalVD->getDeclContext()->isNamespace() &&
2354 (!getCurLexicalContext()->isFileContext() ||
2355 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2356 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002357 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002358 bool IsDecl =
2359 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2360 Diag(VD->getLocation(),
2361 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2362 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002363 return ExprError();
2364 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002365 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2366 // A threadprivate directive for static block-scope variables must appear
2367 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002368 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002369 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002370 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002371 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002372 bool IsDecl =
2373 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2374 Diag(VD->getLocation(),
2375 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2376 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002377 return ExprError();
2378 }
2379
2380 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2381 // A threadprivate directive must lexically precede all references to any
2382 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002383 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2384 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002385 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002386 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002387 return ExprError();
2388 }
2389
2390 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002391 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2392 SourceLocation(), VD,
2393 /*RefersToEnclosingVariableOrCapture=*/false,
2394 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002395}
2396
Alexey Bataeved09d242014-05-28 05:53:51 +00002397Sema::DeclGroupPtrTy
2398Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2399 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002400 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002401 CurContext->addDecl(D);
2402 return DeclGroupPtrTy::make(DeclGroupRef(D));
2403 }
David Blaikie0403cb12016-01-15 23:43:25 +00002404 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002405}
2406
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002407namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002408class LocalVarRefChecker final
2409 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002410 Sema &SemaRef;
2411
2412public:
2413 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002414 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002415 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002416 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002417 diag::err_omp_local_var_in_threadprivate_init)
2418 << E->getSourceRange();
2419 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2420 << VD << VD->getSourceRange();
2421 return true;
2422 }
2423 }
2424 return false;
2425 }
2426 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002427 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002428 if (Child && Visit(Child))
2429 return true;
2430 }
2431 return false;
2432 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002433 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002434};
2435} // namespace
2436
Alexey Bataeved09d242014-05-28 05:53:51 +00002437OMPThreadPrivateDecl *
2438Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002439 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002440 for (Expr *RefExpr : VarList) {
2441 auto *DE = cast<DeclRefExpr>(RefExpr);
2442 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002443 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002444
Alexey Bataev376b4a42016-02-09 09:41:09 +00002445 // Mark variable as used.
2446 VD->setReferenced();
2447 VD->markUsed(Context);
2448
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002449 QualType QType = VD->getType();
2450 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2451 // It will be analyzed later.
2452 Vars.push_back(DE);
2453 continue;
2454 }
2455
Alexey Bataeva769e072013-03-22 06:34:35 +00002456 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2457 // A threadprivate variable must not have an incomplete type.
2458 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002459 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002460 continue;
2461 }
2462
2463 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2464 // A threadprivate variable must not have a reference type.
2465 if (VD->getType()->isReferenceType()) {
2466 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002467 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2468 bool IsDecl =
2469 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2470 Diag(VD->getLocation(),
2471 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2472 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002473 continue;
2474 }
2475
Samuel Antaof8b50122015-07-13 22:54:53 +00002476 // Check if this is a TLS variable. If TLS is not being supported, produce
2477 // the corresponding diagnostic.
2478 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2479 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2480 getLangOpts().OpenMPUseTLS &&
2481 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002482 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2483 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002484 Diag(ILoc, diag::err_omp_var_thread_local)
2485 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002486 bool IsDecl =
2487 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2488 Diag(VD->getLocation(),
2489 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2490 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002491 continue;
2492 }
2493
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002494 // Check if initial value of threadprivate variable reference variable with
2495 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002496 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002497 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002498 if (Checker.Visit(Init))
2499 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002500 }
2501
Alexey Bataeved09d242014-05-28 05:53:51 +00002502 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002503 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002504 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2505 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002506 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002507 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002508 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002509 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002510 if (!Vars.empty()) {
2511 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2512 Vars);
2513 D->setAccess(AS_public);
2514 }
2515 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002516}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002517
Alexey Bataev27ef9512019-03-20 20:14:22 +00002518static OMPAllocateDeclAttr::AllocatorTypeTy
2519getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2520 if (!Allocator)
2521 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2522 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2523 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002524 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002525 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002526 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002527 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002528 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2529 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2530 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002531 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002532 llvm::FoldingSetNodeID AEId, DAEId;
2533 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2534 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2535 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002536 AllocatorKindRes = AllocatorKind;
2537 break;
2538 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002539 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002540 return AllocatorKindRes;
2541}
2542
Alexey Bataeve106f252019-04-01 14:25:31 +00002543static bool checkPreviousOMPAllocateAttribute(
2544 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2545 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2546 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2547 return false;
2548 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2549 Expr *PrevAllocator = A->getAllocator();
2550 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2551 getAllocatorKind(S, Stack, PrevAllocator);
2552 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2553 if (AllocatorsMatch &&
2554 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2555 Allocator && PrevAllocator) {
2556 const Expr *AE = Allocator->IgnoreParenImpCasts();
2557 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2558 llvm::FoldingSetNodeID AEId, PAEId;
2559 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2560 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2561 AllocatorsMatch = AEId == PAEId;
2562 }
2563 if (!AllocatorsMatch) {
2564 SmallString<256> AllocatorBuffer;
2565 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2566 if (Allocator)
2567 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2568 SmallString<256> PrevAllocatorBuffer;
2569 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2570 if (PrevAllocator)
2571 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2572 S.getPrintingPolicy());
2573
2574 SourceLocation AllocatorLoc =
2575 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2576 SourceRange AllocatorRange =
2577 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2578 SourceLocation PrevAllocatorLoc =
2579 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2580 SourceRange PrevAllocatorRange =
2581 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2582 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2583 << (Allocator ? 1 : 0) << AllocatorStream.str()
2584 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2585 << AllocatorRange;
2586 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2587 << PrevAllocatorRange;
2588 return true;
2589 }
2590 return false;
2591}
2592
2593static void
2594applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2595 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2596 Expr *Allocator, SourceRange SR) {
2597 if (VD->hasAttr<OMPAllocateDeclAttr>())
2598 return;
2599 if (Allocator &&
2600 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2601 Allocator->isInstantiationDependent() ||
2602 Allocator->containsUnexpandedParameterPack()))
2603 return;
2604 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2605 Allocator, SR);
2606 VD->addAttr(A);
2607 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2608 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2609}
2610
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002611Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2612 SourceLocation Loc, ArrayRef<Expr *> VarList,
2613 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2614 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2615 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002616 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002617 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2618 // allocate directives that appear in a target region must specify an
2619 // allocator clause unless a requires directive with the dynamic_allocators
2620 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002621 if (LangOpts.OpenMPIsDevice &&
2622 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002623 targetDiag(Loc, diag::err_expected_allocator_clause);
2624 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002625 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002626 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002627 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2628 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002629 SmallVector<Expr *, 8> Vars;
2630 for (Expr *RefExpr : VarList) {
2631 auto *DE = cast<DeclRefExpr>(RefExpr);
2632 auto *VD = cast<VarDecl>(DE->getDecl());
2633
2634 // Check if this is a TLS variable or global register.
2635 if (VD->getTLSKind() != VarDecl::TLS_None ||
2636 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2637 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2638 !VD->isLocalVarDecl()))
2639 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002640
Alexey Bataev282555a2019-03-19 20:33:44 +00002641 // If the used several times in the allocate directive, the same allocator
2642 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002643 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2644 AllocatorKind, Allocator))
2645 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002646
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002647 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2648 // If a list item has a static storage type, the allocator expression in the
2649 // allocator clause must be a constant expression that evaluates to one of
2650 // the predefined memory allocator values.
2651 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002652 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002653 Diag(Allocator->getExprLoc(),
2654 diag::err_omp_expected_predefined_allocator)
2655 << Allocator->getSourceRange();
2656 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2657 VarDecl::DeclarationOnly;
2658 Diag(VD->getLocation(),
2659 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2660 << VD;
2661 continue;
2662 }
2663 }
2664
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002665 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002666 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2667 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002668 }
2669 if (Vars.empty())
2670 return nullptr;
2671 if (!Owner)
2672 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002673 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002674 D->setAccess(AS_public);
2675 Owner->addDecl(D);
2676 return DeclGroupPtrTy::make(DeclGroupRef(D));
2677}
2678
2679Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002680Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2681 ArrayRef<OMPClause *> ClauseList) {
2682 OMPRequiresDecl *D = nullptr;
2683 if (!CurContext->isFileContext()) {
2684 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2685 } else {
2686 D = CheckOMPRequiresDecl(Loc, ClauseList);
2687 if (D) {
2688 CurContext->addDecl(D);
2689 DSAStack->addRequiresDecl(D);
2690 }
2691 }
2692 return DeclGroupPtrTy::make(DeclGroupRef(D));
2693}
2694
2695OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2696 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002697 /// For target specific clauses, the requires directive cannot be
2698 /// specified after the handling of any of the target regions in the
2699 /// current compilation unit.
2700 ArrayRef<SourceLocation> TargetLocations =
2701 DSAStack->getEncounteredTargetLocs();
2702 if (!TargetLocations.empty()) {
2703 for (const OMPClause *CNew : ClauseList) {
2704 // Check if any of the requires clauses affect target regions.
2705 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2706 isa<OMPUnifiedAddressClause>(CNew) ||
2707 isa<OMPReverseOffloadClause>(CNew) ||
2708 isa<OMPDynamicAllocatorsClause>(CNew)) {
2709 Diag(Loc, diag::err_omp_target_before_requires)
2710 << getOpenMPClauseName(CNew->getClauseKind());
2711 for (SourceLocation TargetLoc : TargetLocations) {
2712 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2713 }
2714 }
2715 }
2716 }
2717
Kelvin Li1408f912018-09-26 04:28:39 +00002718 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2719 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2720 ClauseList);
2721 return nullptr;
2722}
2723
Alexey Bataeve3727102018-04-18 15:57:46 +00002724static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2725 const ValueDecl *D,
2726 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002727 bool IsLoopIterVar = false) {
2728 if (DVar.RefExpr) {
2729 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2730 << getOpenMPClauseName(DVar.CKind);
2731 return;
2732 }
2733 enum {
2734 PDSA_StaticMemberShared,
2735 PDSA_StaticLocalVarShared,
2736 PDSA_LoopIterVarPrivate,
2737 PDSA_LoopIterVarLinear,
2738 PDSA_LoopIterVarLastprivate,
2739 PDSA_ConstVarShared,
2740 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002741 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002742 PDSA_LocalVarPrivate,
2743 PDSA_Implicit
2744 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002745 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002746 auto ReportLoc = D->getLocation();
2747 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002748 if (IsLoopIterVar) {
2749 if (DVar.CKind == OMPC_private)
2750 Reason = PDSA_LoopIterVarPrivate;
2751 else if (DVar.CKind == OMPC_lastprivate)
2752 Reason = PDSA_LoopIterVarLastprivate;
2753 else
2754 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002755 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2756 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002757 Reason = PDSA_TaskVarFirstprivate;
2758 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002759 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002760 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002761 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002762 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002763 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002764 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002765 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002766 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002767 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002768 ReportHint = true;
2769 Reason = PDSA_LocalVarPrivate;
2770 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002771 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002772 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002773 << Reason << ReportHint
2774 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2775 } else if (DVar.ImplicitDSALoc.isValid()) {
2776 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2777 << getOpenMPClauseName(DVar.CKind);
2778 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002779}
2780
Alexey Bataev758e55e2013-09-06 18:03:48 +00002781namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002782class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002783 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002784 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002785 bool ErrorFound = false;
2786 CapturedStmt *CS = nullptr;
2787 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2788 llvm::SmallVector<Expr *, 4> ImplicitMap;
2789 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2790 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002791
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002792 void VisitSubCaptures(OMPExecutableDirective *S) {
2793 // Check implicitly captured variables.
2794 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2795 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002796 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002797 }
2798
Alexey Bataev758e55e2013-09-06 18:03:48 +00002799public:
2800 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002801 if (E->isTypeDependent() || E->isValueDependent() ||
2802 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2803 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002804 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002805 // Check the datasharing rules for the expressions in the clauses.
2806 if (!CS) {
2807 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2808 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2809 Visit(CED->getInit());
2810 return;
2811 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002812 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2813 // Do not analyze internal variables and do not enclose them into
2814 // implicit clauses.
2815 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002816 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002817 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002818 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002819 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002820
Alexey Bataeve3727102018-04-18 15:57:46 +00002821 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002822 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002823 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002824 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825
Alexey Bataevafe50572017-10-06 17:00:28 +00002826 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002827 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002828 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002829 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002830 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2831 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002832 return;
2833
Alexey Bataeve3727102018-04-18 15:57:46 +00002834 SourceLocation ELoc = E->getExprLoc();
2835 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002836 // The default(none) clause requires that each variable that is referenced
2837 // in the construct, and does not have a predetermined data-sharing
2838 // attribute, must have its data-sharing attribute explicitly determined
2839 // by being listed in a data-sharing attribute clause.
2840 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002841 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002842 VarsWithInheritedDSA.count(VD) == 0) {
2843 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002844 return;
2845 }
2846
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002847 if (isOpenMPTargetExecutionDirective(DKind) &&
2848 !Stack->isLoopControlVariable(VD).first) {
2849 if (!Stack->checkMappableExprComponentListsForDecl(
2850 VD, /*CurrentRegionOnly=*/true,
2851 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2852 StackComponents,
2853 OpenMPClauseKind) {
2854 // Variable is used if it has been marked as an array, array
2855 // section or the variable iself.
2856 return StackComponents.size() == 1 ||
2857 std::all_of(
2858 std::next(StackComponents.rbegin()),
2859 StackComponents.rend(),
2860 [](const OMPClauseMappableExprCommon::
2861 MappableComponent &MC) {
2862 return MC.getAssociatedDeclaration() ==
2863 nullptr &&
2864 (isa<OMPArraySectionExpr>(
2865 MC.getAssociatedExpression()) ||
2866 isa<ArraySubscriptExpr>(
2867 MC.getAssociatedExpression()));
2868 });
2869 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002870 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002871 // By default lambdas are captured as firstprivates.
2872 if (const auto *RD =
2873 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002874 IsFirstprivate = RD->isLambda();
2875 IsFirstprivate =
2876 IsFirstprivate ||
2877 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002878 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002879 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002880 ImplicitFirstprivate.emplace_back(E);
2881 else
2882 ImplicitMap.emplace_back(E);
2883 return;
2884 }
2885 }
2886
Alexey Bataev758e55e2013-09-06 18:03:48 +00002887 // OpenMP [2.9.3.6, Restrictions, p.2]
2888 // A list item that appears in a reduction clause of the innermost
2889 // enclosing worksharing or parallel construct may not be accessed in an
2890 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002891 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002892 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2893 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002894 return isOpenMPParallelDirective(K) ||
2895 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2896 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002897 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002898 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002899 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002900 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002902 return;
2903 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002904
2905 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002906 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002907 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002908 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002909 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002910 return;
2911 }
2912
2913 // Store implicitly used globals with declare target link for parent
2914 // target.
2915 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2916 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2917 Stack->addToParentTargetRegionLinkGlobals(E);
2918 return;
2919 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002920 }
2921 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002922 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002923 if (E->isTypeDependent() || E->isValueDependent() ||
2924 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2925 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002926 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002927 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002928 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002929 if (!FD)
2930 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002931 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002932 // Check if the variable has explicit DSA set and stop analysis if it
2933 // so.
2934 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2935 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002936
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002937 if (isOpenMPTargetExecutionDirective(DKind) &&
2938 !Stack->isLoopControlVariable(FD).first &&
2939 !Stack->checkMappableExprComponentListsForDecl(
2940 FD, /*CurrentRegionOnly=*/true,
2941 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2942 StackComponents,
2943 OpenMPClauseKind) {
2944 return isa<CXXThisExpr>(
2945 cast<MemberExpr>(
2946 StackComponents.back().getAssociatedExpression())
2947 ->getBase()
2948 ->IgnoreParens());
2949 })) {
2950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2951 // A bit-field cannot appear in a map clause.
2952 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002953 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002954 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002955
2956 // Check to see if the member expression is referencing a class that
2957 // has already been explicitly mapped
2958 if (Stack->isClassPreviouslyMapped(TE->getType()))
2959 return;
2960
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002961 ImplicitMap.emplace_back(E);
2962 return;
2963 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002964
Alexey Bataeve3727102018-04-18 15:57:46 +00002965 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002966 // OpenMP [2.9.3.6, Restrictions, p.2]
2967 // A list item that appears in a reduction clause of the innermost
2968 // enclosing worksharing or parallel construct may not be accessed in
2969 // an explicit task.
2970 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002971 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2972 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002973 return isOpenMPParallelDirective(K) ||
2974 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2975 },
2976 /*FromParent=*/true);
2977 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2978 ErrorFound = true;
2979 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002980 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002981 return;
2982 }
2983
2984 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002985 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002986 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002987 !Stack->isLoopControlVariable(FD).first) {
2988 // Check if there is a captured expression for the current field in the
2989 // region. Do not mark it as firstprivate unless there is no captured
2990 // expression.
2991 // TODO: try to make it firstprivate.
2992 if (DVar.CKind != OMPC_unknown)
2993 ImplicitFirstprivate.push_back(E);
2994 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002995 return;
2996 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002997 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002999 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003000 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003001 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003002 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003003 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3004 if (!Stack->checkMappableExprComponentListsForDecl(
3005 VD, /*CurrentRegionOnly=*/true,
3006 [&CurComponents](
3007 OMPClauseMappableExprCommon::MappableExprComponentListRef
3008 StackComponents,
3009 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003010 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003011 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003012 for (const auto &SC : llvm::reverse(StackComponents)) {
3013 // Do both expressions have the same kind?
3014 if (CCI->getAssociatedExpression()->getStmtClass() !=
3015 SC.getAssociatedExpression()->getStmtClass())
3016 if (!(isa<OMPArraySectionExpr>(
3017 SC.getAssociatedExpression()) &&
3018 isa<ArraySubscriptExpr>(
3019 CCI->getAssociatedExpression())))
3020 return false;
3021
Alexey Bataeve3727102018-04-18 15:57:46 +00003022 const Decl *CCD = CCI->getAssociatedDeclaration();
3023 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003024 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3025 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3026 if (SCD != CCD)
3027 return false;
3028 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003029 if (CCI == CCE)
3030 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003031 }
3032 return true;
3033 })) {
3034 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003035 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003036 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003037 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003038 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003039 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003040 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003041 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003042 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003043 // for task|target directives.
3044 // Skip analysis of arguments of implicitly defined map clause for target
3045 // directives.
3046 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3047 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003048 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003049 if (CC)
3050 Visit(CC);
3051 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003052 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003053 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003054 // Check implicitly captured variables.
3055 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003056 }
3057 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003058 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003059 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003060 // Check implicitly captured variables in the task-based directives to
3061 // check if they must be firstprivatized.
3062 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003063 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003064 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003065 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003066
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003067 void visitSubCaptures(CapturedStmt *S) {
3068 for (const CapturedStmt::Capture &Cap : S->captures()) {
3069 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3070 continue;
3071 VarDecl *VD = Cap.getCapturedVar();
3072 // Do not try to map the variable if it or its sub-component was mapped
3073 // already.
3074 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3075 Stack->checkMappableExprComponentListsForDecl(
3076 VD, /*CurrentRegionOnly=*/true,
3077 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3078 OpenMPClauseKind) { return true; }))
3079 continue;
3080 DeclRefExpr *DRE = buildDeclRefExpr(
3081 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3082 Cap.getLocation(), /*RefersToCapture=*/true);
3083 Visit(DRE);
3084 }
3085 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003086 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003087 ArrayRef<Expr *> getImplicitFirstprivate() const {
3088 return ImplicitFirstprivate;
3089 }
3090 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00003091 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003092 return VarsWithInheritedDSA;
3093 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003094
Alexey Bataev7ff55242014-06-19 09:13:45 +00003095 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003096 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3097 // Process declare target link variables for the target directives.
3098 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3099 for (DeclRefExpr *E : Stack->getLinkGlobals())
3100 Visit(E);
3101 }
3102 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003103};
Alexey Bataeved09d242014-05-28 05:53:51 +00003104} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003105
Alexey Bataevbae9a792014-06-27 10:37:06 +00003106void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003107 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003108 case OMPD_parallel:
3109 case OMPD_parallel_for:
3110 case OMPD_parallel_for_simd:
3111 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003112 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003113 case OMPD_teams_distribute:
3114 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003115 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003118 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003119 std::make_pair(".global_tid.", KmpInt32PtrTy),
3120 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3121 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003122 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003123 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3124 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003125 break;
3126 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003127 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003128 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003129 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003130 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003131 case OMPD_target_teams_distribute:
3132 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003133 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3134 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3135 QualType KmpInt32PtrTy =
3136 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3137 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003138 FunctionProtoType::ExtProtoInfo EPI;
3139 EPI.Variadic = true;
3140 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3141 Sema::CapturedParamNameType Params[] = {
3142 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003143 std::make_pair(".part_id.", KmpInt32PtrTy),
3144 std::make_pair(".privates.", VoidPtrTy),
3145 std::make_pair(
3146 ".copy_fn.",
3147 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003148 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
3151 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003152 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003153 // Mark this captured region as inlined, because we don't use outlined
3154 // function directly.
3155 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3156 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003157 Context, {}, AttributeCommonInfo::AS_Keyword,
3158 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003159 Sema::CapturedParamNameType ParamsTarget[] = {
3160 std::make_pair(StringRef(), QualType()) // __context with shared vars
3161 };
3162 // Start a captured region for 'target' with no implicit parameters.
3163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003164 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003165 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003166 std::make_pair(".global_tid.", KmpInt32PtrTy),
3167 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3168 std::make_pair(StringRef(), QualType()) // __context with shared vars
3169 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003170 // Start a captured region for 'teams' or 'parallel'. Both regions have
3171 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003173 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003174 break;
3175 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003176 case OMPD_target:
3177 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003178 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3179 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3180 QualType KmpInt32PtrTy =
3181 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3182 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003183 FunctionProtoType::ExtProtoInfo EPI;
3184 EPI.Variadic = true;
3185 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3186 Sema::CapturedParamNameType Params[] = {
3187 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003188 std::make_pair(".part_id.", KmpInt32PtrTy),
3189 std::make_pair(".privates.", VoidPtrTy),
3190 std::make_pair(
3191 ".copy_fn.",
3192 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003193 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3194 std::make_pair(StringRef(), QualType()) // __context with shared vars
3195 };
3196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003197 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003198 // Mark this captured region as inlined, because we don't use outlined
3199 // function directly.
3200 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3201 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003202 Context, {}, AttributeCommonInfo::AS_Keyword,
3203 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003204 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003205 std::make_pair(StringRef(), QualType()),
3206 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003207 break;
3208 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003209 case OMPD_simd:
3210 case OMPD_for:
3211 case OMPD_for_simd:
3212 case OMPD_sections:
3213 case OMPD_section:
3214 case OMPD_single:
3215 case OMPD_master:
3216 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003217 case OMPD_taskgroup:
3218 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003219 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003220 case OMPD_ordered:
3221 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003222 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003223 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003224 std::make_pair(StringRef(), QualType()) // __context with shared vars
3225 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3227 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003228 break;
3229 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003230 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3232 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3233 QualType KmpInt32PtrTy =
3234 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3235 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003236 FunctionProtoType::ExtProtoInfo EPI;
3237 EPI.Variadic = true;
3238 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003239 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003240 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003241 std::make_pair(".part_id.", KmpInt32PtrTy),
3242 std::make_pair(".privates.", VoidPtrTy),
3243 std::make_pair(
3244 ".copy_fn.",
3245 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003246 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003247 std::make_pair(StringRef(), QualType()) // __context with shared vars
3248 };
3249 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3250 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003251 // Mark this captured region as inlined, because we don't use outlined
3252 // function directly.
3253 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3254 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003255 Context, {}, AttributeCommonInfo::AS_Keyword,
3256 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003257 break;
3258 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003259 case OMPD_taskloop:
3260 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003261 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003262 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3263 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003264 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003265 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3266 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003267 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003268 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3269 .withConst();
3270 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3271 QualType KmpInt32PtrTy =
3272 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3273 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003274 FunctionProtoType::ExtProtoInfo EPI;
3275 EPI.Variadic = true;
3276 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003277 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003278 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003279 std::make_pair(".part_id.", KmpInt32PtrTy),
3280 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003281 std::make_pair(
3282 ".copy_fn.",
3283 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3284 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3285 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003286 std::make_pair(".ub.", KmpUInt64Ty),
3287 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003288 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003289 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003290 std::make_pair(StringRef(), QualType()) // __context with shared vars
3291 };
3292 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3293 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003294 // Mark this captured region as inlined, because we don't use outlined
3295 // function directly.
3296 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3297 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003298 Context, {}, AttributeCommonInfo::AS_Keyword,
3299 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003300 break;
3301 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003302 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003303 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003304 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003305 QualType KmpInt32PtrTy =
3306 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3307 Sema::CapturedParamNameType Params[] = {
3308 std::make_pair(".global_tid.", KmpInt32PtrTy),
3309 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003310 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3311 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003312 std::make_pair(StringRef(), QualType()) // __context with shared vars
3313 };
3314 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3315 Params);
3316 break;
3317 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003318 case OMPD_target_teams_distribute_parallel_for:
3319 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003320 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003321 QualType KmpInt32PtrTy =
3322 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003323 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003324
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003325 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003326 FunctionProtoType::ExtProtoInfo EPI;
3327 EPI.Variadic = true;
3328 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3329 Sema::CapturedParamNameType Params[] = {
3330 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003331 std::make_pair(".part_id.", KmpInt32PtrTy),
3332 std::make_pair(".privates.", VoidPtrTy),
3333 std::make_pair(
3334 ".copy_fn.",
3335 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003336 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3337 std::make_pair(StringRef(), QualType()) // __context with shared vars
3338 };
3339 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003340 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003341 // Mark this captured region as inlined, because we don't use outlined
3342 // function directly.
3343 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3344 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003345 Context, {}, AttributeCommonInfo::AS_Keyword,
3346 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003347 Sema::CapturedParamNameType ParamsTarget[] = {
3348 std::make_pair(StringRef(), QualType()) // __context with shared vars
3349 };
3350 // Start a captured region for 'target' with no implicit parameters.
3351 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003352 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003353
3354 Sema::CapturedParamNameType ParamsTeams[] = {
3355 std::make_pair(".global_tid.", KmpInt32PtrTy),
3356 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3357 std::make_pair(StringRef(), QualType()) // __context with shared vars
3358 };
3359 // Start a captured region for 'target' with no implicit parameters.
3360 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003361 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003362
3363 Sema::CapturedParamNameType ParamsParallel[] = {
3364 std::make_pair(".global_tid.", KmpInt32PtrTy),
3365 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003366 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3367 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003368 std::make_pair(StringRef(), QualType()) // __context with shared vars
3369 };
3370 // Start a captured region for 'teams' or 'parallel'. Both regions have
3371 // the same implicit parameters.
3372 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003373 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003374 break;
3375 }
3376
Alexey Bataev46506272017-12-05 17:41:34 +00003377 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003378 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003379 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003380 QualType KmpInt32PtrTy =
3381 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3382
3383 Sema::CapturedParamNameType ParamsTeams[] = {
3384 std::make_pair(".global_tid.", KmpInt32PtrTy),
3385 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3386 std::make_pair(StringRef(), QualType()) // __context with shared vars
3387 };
3388 // Start a captured region for 'target' with no implicit parameters.
3389 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003390 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003391
3392 Sema::CapturedParamNameType ParamsParallel[] = {
3393 std::make_pair(".global_tid.", KmpInt32PtrTy),
3394 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003395 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3396 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003397 std::make_pair(StringRef(), QualType()) // __context with shared vars
3398 };
3399 // Start a captured region for 'teams' or 'parallel'. Both regions have
3400 // the same implicit parameters.
3401 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003402 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003403 break;
3404 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003405 case OMPD_target_update:
3406 case OMPD_target_enter_data:
3407 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003408 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3409 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3410 QualType KmpInt32PtrTy =
3411 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3412 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003413 FunctionProtoType::ExtProtoInfo EPI;
3414 EPI.Variadic = true;
3415 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3416 Sema::CapturedParamNameType Params[] = {
3417 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003418 std::make_pair(".part_id.", KmpInt32PtrTy),
3419 std::make_pair(".privates.", VoidPtrTy),
3420 std::make_pair(
3421 ".copy_fn.",
3422 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003423 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3424 std::make_pair(StringRef(), QualType()) // __context with shared vars
3425 };
3426 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3427 Params);
3428 // Mark this captured region as inlined, because we don't use outlined
3429 // function directly.
3430 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3431 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003432 Context, {}, AttributeCommonInfo::AS_Keyword,
3433 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003434 break;
3435 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003436 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003437 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003438 case OMPD_taskyield:
3439 case OMPD_barrier:
3440 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003441 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003442 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003443 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003444 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003445 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003446 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003447 case OMPD_declare_target:
3448 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003449 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003450 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003451 llvm_unreachable("OpenMP Directive is not allowed");
3452 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003453 llvm_unreachable("Unknown OpenMP directive");
3454 }
3455}
3456
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003457int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3458 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3459 getOpenMPCaptureRegions(CaptureRegions, DKind);
3460 return CaptureRegions.size();
3461}
3462
Alexey Bataev3392d762016-02-16 11:18:12 +00003463static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003464 Expr *CaptureExpr, bool WithInit,
3465 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003466 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003467 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003468 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003469 QualType Ty = Init->getType();
3470 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003471 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003472 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003473 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003474 Ty = C.getPointerType(Ty);
3475 ExprResult Res =
3476 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3477 if (!Res.isUsable())
3478 return nullptr;
3479 Init = Res.get();
3480 }
Alexey Bataev61205072016-03-02 04:57:40 +00003481 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003482 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003483 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003484 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003485 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003486 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003487 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003488 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003489 return CED;
3490}
3491
Alexey Bataev61205072016-03-02 04:57:40 +00003492static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3493 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003494 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003495 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003496 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003497 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003498 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3499 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003500 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003501 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003502}
3503
Alexey Bataev5a3af132016-03-29 08:58:54 +00003504static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003505 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003506 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003507 OMPCapturedExprDecl *CD = buildCaptureDecl(
3508 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3509 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003510 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3511 CaptureExpr->getExprLoc());
3512 }
3513 ExprResult Res = Ref;
3514 if (!S.getLangOpts().CPlusPlus &&
3515 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003516 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003517 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003518 if (!Res.isUsable())
3519 return ExprError();
3520 }
3521 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003522}
3523
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003524namespace {
3525// OpenMP directives parsed in this section are represented as a
3526// CapturedStatement with an associated statement. If a syntax error
3527// is detected during the parsing of the associated statement, the
3528// compiler must abort processing and close the CapturedStatement.
3529//
3530// Combined directives such as 'target parallel' have more than one
3531// nested CapturedStatements. This RAII ensures that we unwind out
3532// of all the nested CapturedStatements when an error is found.
3533class CaptureRegionUnwinderRAII {
3534private:
3535 Sema &S;
3536 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003537 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003538
3539public:
3540 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3541 OpenMPDirectiveKind DKind)
3542 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3543 ~CaptureRegionUnwinderRAII() {
3544 if (ErrorFound) {
3545 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3546 while (--ThisCaptureLevel >= 0)
3547 S.ActOnCapturedRegionError();
3548 }
3549 }
3550};
3551} // namespace
3552
Alexey Bataevb600ae32019-07-01 17:46:52 +00003553void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3554 // Capture variables captured by reference in lambdas for target-based
3555 // directives.
3556 if (!CurContext->isDependentContext() &&
3557 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3558 isOpenMPTargetDataManagementDirective(
3559 DSAStack->getCurrentDirective()))) {
3560 QualType Type = V->getType();
3561 if (const auto *RD = Type.getCanonicalType()
3562 .getNonReferenceType()
3563 ->getAsCXXRecordDecl()) {
3564 bool SavedForceCaptureByReferenceInTargetExecutable =
3565 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3566 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3567 /*V=*/true);
3568 if (RD->isLambda()) {
3569 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3570 FieldDecl *ThisCapture;
3571 RD->getCaptureFields(Captures, ThisCapture);
3572 for (const LambdaCapture &LC : RD->captures()) {
3573 if (LC.getCaptureKind() == LCK_ByRef) {
3574 VarDecl *VD = LC.getCapturedVar();
3575 DeclContext *VDC = VD->getDeclContext();
3576 if (!VDC->Encloses(CurContext))
3577 continue;
3578 MarkVariableReferenced(LC.getLocation(), VD);
3579 } else if (LC.getCaptureKind() == LCK_This) {
3580 QualType ThisTy = getCurrentThisType();
3581 if (!ThisTy.isNull() &&
3582 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3583 CheckCXXThisCapture(LC.getLocation());
3584 }
3585 }
3586 }
3587 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3588 SavedForceCaptureByReferenceInTargetExecutable);
3589 }
3590 }
3591}
3592
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003593StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3594 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003595 bool ErrorFound = false;
3596 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3597 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003598 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003599 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003600 return StmtError();
3601 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003602
Alexey Bataev2ba67042017-11-28 21:11:44 +00003603 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3604 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003605 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003606 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003607 SmallVector<const OMPLinearClause *, 4> LCs;
3608 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003609 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003610 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003611 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3612 Clause->getClauseKind() == OMPC_in_reduction) {
3613 // Capture taskgroup task_reduction descriptors inside the tasking regions
3614 // with the corresponding in_reduction items.
3615 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003616 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003617 if (E)
3618 MarkDeclarationsReferencedInExpr(E);
3619 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003620 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003621 Clause->getClauseKind() == OMPC_copyprivate ||
3622 (getLangOpts().OpenMPUseTLS &&
3623 getASTContext().getTargetInfo().isTLSSupported() &&
3624 Clause->getClauseKind() == OMPC_copyin)) {
3625 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003626 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003627 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003628 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003629 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003630 }
3631 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003632 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003633 } else if (CaptureRegions.size() > 1 ||
3634 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003635 if (auto *C = OMPClauseWithPreInit::get(Clause))
3636 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003637 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003638 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003639 MarkDeclarationsReferencedInExpr(E);
3640 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003641 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003642 if (Clause->getClauseKind() == OMPC_schedule)
3643 SC = cast<OMPScheduleClause>(Clause);
3644 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003645 OC = cast<OMPOrderedClause>(Clause);
3646 else if (Clause->getClauseKind() == OMPC_linear)
3647 LCs.push_back(cast<OMPLinearClause>(Clause));
3648 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003649 // OpenMP, 2.7.1 Loop Construct, Restrictions
3650 // The nonmonotonic modifier cannot be specified if an ordered clause is
3651 // specified.
3652 if (SC &&
3653 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3654 SC->getSecondScheduleModifier() ==
3655 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3656 OC) {
3657 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3658 ? SC->getFirstScheduleModifierLoc()
3659 : SC->getSecondScheduleModifierLoc(),
3660 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003661 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003662 ErrorFound = true;
3663 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003664 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003665 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003666 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003667 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003668 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003669 ErrorFound = true;
3670 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003671 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3672 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3673 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003674 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003675 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3676 ErrorFound = true;
3677 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003678 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003679 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003680 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003681 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003682 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003683 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003684 // Mark all variables in private list clauses as used in inner region.
3685 // Required for proper codegen of combined directives.
3686 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003687 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003688 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003689 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3690 // Find the particular capture region for the clause if the
3691 // directive is a combined one with multiple capture regions.
3692 // If the directive is not a combined one, the capture region
3693 // associated with the clause is OMPD_unknown and is generated
3694 // only once.
3695 if (CaptureRegion == ThisCaptureRegion ||
3696 CaptureRegion == OMPD_unknown) {
3697 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003698 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003699 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3700 }
3701 }
3702 }
3703 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003704 if (++CompletedRegions == CaptureRegions.size())
3705 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003706 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003707 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003708 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003709}
3710
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003711static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3712 OpenMPDirectiveKind CancelRegion,
3713 SourceLocation StartLoc) {
3714 // CancelRegion is only needed for cancel and cancellation_point.
3715 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3716 return false;
3717
3718 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3719 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3720 return false;
3721
3722 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3723 << getOpenMPDirectiveName(CancelRegion);
3724 return true;
3725}
3726
Alexey Bataeve3727102018-04-18 15:57:46 +00003727static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003728 OpenMPDirectiveKind CurrentRegion,
3729 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003730 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003731 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003732 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003733 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3734 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003735 bool NestingProhibited = false;
3736 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003737 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003738 enum {
3739 NoRecommend,
3740 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003741 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003742 ShouldBeInTargetRegion,
3743 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003744 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003745 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003746 // OpenMP [2.16, Nesting of Regions]
3747 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003748 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003749 // An ordered construct with the simd clause is the only OpenMP
3750 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003751 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003752 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3753 // message.
3754 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3755 ? diag::err_omp_prohibited_region_simd
3756 : diag::warn_omp_nesting_simd);
3757 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003758 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003759 if (ParentRegion == OMPD_atomic) {
3760 // OpenMP [2.16, Nesting of Regions]
3761 // OpenMP constructs may not be nested inside an atomic region.
3762 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3763 return true;
3764 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003765 if (CurrentRegion == OMPD_section) {
3766 // OpenMP [2.7.2, sections Construct, Restrictions]
3767 // Orphaned section directives are prohibited. That is, the section
3768 // directives must appear within the sections construct and must not be
3769 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003770 if (ParentRegion != OMPD_sections &&
3771 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003772 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3773 << (ParentRegion != OMPD_unknown)
3774 << getOpenMPDirectiveName(ParentRegion);
3775 return true;
3776 }
3777 return false;
3778 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003779 // Allow some constructs (except teams and cancellation constructs) to be
3780 // orphaned (they could be used in functions, called from OpenMP regions
3781 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003782 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003783 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3784 CurrentRegion != OMPD_cancellation_point &&
3785 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003786 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003787 if (CurrentRegion == OMPD_cancellation_point ||
3788 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003789 // OpenMP [2.16, Nesting of Regions]
3790 // A cancellation point construct for which construct-type-clause is
3791 // taskgroup must be nested inside a task construct. A cancellation
3792 // point construct for which construct-type-clause is not taskgroup must
3793 // be closely nested inside an OpenMP construct that matches the type
3794 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003795 // A cancel construct for which construct-type-clause is taskgroup must be
3796 // nested inside a task construct. A cancel construct for which
3797 // construct-type-clause is not taskgroup must be closely nested inside an
3798 // OpenMP construct that matches the type specified in
3799 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003800 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003801 !((CancelRegion == OMPD_parallel &&
3802 (ParentRegion == OMPD_parallel ||
3803 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003804 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003805 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003806 ParentRegion == OMPD_target_parallel_for ||
3807 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003808 ParentRegion == OMPD_teams_distribute_parallel_for ||
3809 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003810 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3811 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003812 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3813 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003814 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003815 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003816 // OpenMP [2.16, Nesting of Regions]
3817 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003818 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003819 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003820 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003821 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3822 // OpenMP [2.16, Nesting of Regions]
3823 // A critical region may not be nested (closely or otherwise) inside a
3824 // critical region with the same name. Note that this restriction is not
3825 // sufficient to prevent deadlock.
3826 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003827 bool DeadLock = Stack->hasDirective(
3828 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3829 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003830 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003831 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3832 PreviousCriticalLoc = Loc;
3833 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003834 }
3835 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003836 },
3837 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003838 if (DeadLock) {
3839 SemaRef.Diag(StartLoc,
3840 diag::err_omp_prohibited_region_critical_same_name)
3841 << CurrentName.getName();
3842 if (PreviousCriticalLoc.isValid())
3843 SemaRef.Diag(PreviousCriticalLoc,
3844 diag::note_omp_previous_critical_region);
3845 return true;
3846 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003847 } else if (CurrentRegion == OMPD_barrier) {
3848 // OpenMP [2.16, Nesting of Regions]
3849 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003850 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003851 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3852 isOpenMPTaskingDirective(ParentRegion) ||
3853 ParentRegion == OMPD_master ||
3854 ParentRegion == OMPD_critical ||
3855 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003856 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003857 !isOpenMPParallelDirective(CurrentRegion) &&
3858 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003859 // OpenMP [2.16, Nesting of Regions]
3860 // A worksharing region may not be closely nested inside a worksharing,
3861 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003862 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3863 isOpenMPTaskingDirective(ParentRegion) ||
3864 ParentRegion == OMPD_master ||
3865 ParentRegion == OMPD_critical ||
3866 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003867 Recommend = ShouldBeInParallelRegion;
3868 } else if (CurrentRegion == OMPD_ordered) {
3869 // OpenMP [2.16, Nesting of Regions]
3870 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003871 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003872 // An ordered region must be closely nested inside a loop region (or
3873 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003874 // OpenMP [2.8.1,simd Construct, Restrictions]
3875 // An ordered construct with the simd clause is the only OpenMP construct
3876 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003877 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003878 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003879 !(isOpenMPSimdDirective(ParentRegion) ||
3880 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003881 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003882 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003883 // OpenMP [2.16, Nesting of Regions]
3884 // If specified, a teams construct must be contained within a target
3885 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00003886 NestingProhibited =
3887 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3888 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3889 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00003890 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003891 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003892 }
Kelvin Libf594a52016-12-17 05:48:59 +00003893 if (!NestingProhibited &&
3894 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3895 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3896 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003897 // OpenMP [2.16, Nesting of Regions]
3898 // distribute, parallel, parallel sections, parallel workshare, and the
3899 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3900 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003901 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3902 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003903 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003904 }
David Majnemer9d168222016-08-05 17:44:54 +00003905 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003906 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003907 // OpenMP 4.5 [2.17 Nesting of Regions]
3908 // The region associated with the distribute construct must be strictly
3909 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003910 NestingProhibited =
3911 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003912 Recommend = ShouldBeInTeamsRegion;
3913 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003914 if (!NestingProhibited &&
3915 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3916 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3917 // OpenMP 4.5 [2.17 Nesting of Regions]
3918 // If a target, target update, target data, target enter data, or
3919 // target exit data construct is encountered during execution of a
3920 // target region, the behavior is unspecified.
3921 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003922 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003923 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003924 if (isOpenMPTargetExecutionDirective(K)) {
3925 OffendingRegion = K;
3926 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003927 }
3928 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003929 },
3930 false /* don't skip top directive */);
3931 CloseNesting = false;
3932 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003933 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003934 if (OrphanSeen) {
3935 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3936 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3937 } else {
3938 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3939 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3940 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3941 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003942 return true;
3943 }
3944 }
3945 return false;
3946}
3947
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003948static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3949 ArrayRef<OMPClause *> Clauses,
3950 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3951 bool ErrorFound = false;
3952 unsigned NamedModifiersNumber = 0;
3953 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3954 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003955 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003956 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003957 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3958 // At most one if clause without a directive-name-modifier can appear on
3959 // the directive.
3960 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3961 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003962 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003963 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3964 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3965 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003966 } else if (CurNM != OMPD_unknown) {
3967 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003968 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003969 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003970 FoundNameModifiers[CurNM] = IC;
3971 if (CurNM == OMPD_unknown)
3972 continue;
3973 // Check if the specified name modifier is allowed for the current
3974 // directive.
3975 // At most one if clause with the particular directive-name-modifier can
3976 // appear on the directive.
3977 bool MatchFound = false;
3978 for (auto NM : AllowedNameModifiers) {
3979 if (CurNM == NM) {
3980 MatchFound = true;
3981 break;
3982 }
3983 }
3984 if (!MatchFound) {
3985 S.Diag(IC->getNameModifierLoc(),
3986 diag::err_omp_wrong_if_directive_name_modifier)
3987 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3988 ErrorFound = true;
3989 }
3990 }
3991 }
3992 // If any if clause on the directive includes a directive-name-modifier then
3993 // all if clauses on the directive must include a directive-name-modifier.
3994 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3995 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003996 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003997 diag::err_omp_no_more_if_clause);
3998 } else {
3999 std::string Values;
4000 std::string Sep(", ");
4001 unsigned AllowedCnt = 0;
4002 unsigned TotalAllowedNum =
4003 AllowedNameModifiers.size() - NamedModifiersNumber;
4004 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4005 ++Cnt) {
4006 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4007 if (!FoundNameModifiers[NM]) {
4008 Values += "'";
4009 Values += getOpenMPDirectiveName(NM);
4010 Values += "'";
4011 if (AllowedCnt + 2 == TotalAllowedNum)
4012 Values += " or ";
4013 else if (AllowedCnt + 1 != TotalAllowedNum)
4014 Values += Sep;
4015 ++AllowedCnt;
4016 }
4017 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004018 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004019 diag::err_omp_unnamed_if_clause)
4020 << (TotalAllowedNum > 1) << Values;
4021 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004022 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004023 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4024 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004025 ErrorFound = true;
4026 }
4027 return ErrorFound;
4028}
4029
Alexey Bataeve106f252019-04-01 14:25:31 +00004030static std::pair<ValueDecl *, bool>
4031getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4032 SourceRange &ERange, bool AllowArraySection = false) {
4033 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4034 RefExpr->containsUnexpandedParameterPack())
4035 return std::make_pair(nullptr, true);
4036
4037 // OpenMP [3.1, C/C++]
4038 // A list item is a variable name.
4039 // OpenMP [2.9.3.3, Restrictions, p.1]
4040 // A variable that is part of another variable (as an array or
4041 // structure element) cannot appear in a private clause.
4042 RefExpr = RefExpr->IgnoreParens();
4043 enum {
4044 NoArrayExpr = -1,
4045 ArraySubscript = 0,
4046 OMPArraySection = 1
4047 } IsArrayExpr = NoArrayExpr;
4048 if (AllowArraySection) {
4049 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4050 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4051 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4052 Base = TempASE->getBase()->IgnoreParenImpCasts();
4053 RefExpr = Base;
4054 IsArrayExpr = ArraySubscript;
4055 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4056 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4057 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4058 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4059 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4060 Base = TempASE->getBase()->IgnoreParenImpCasts();
4061 RefExpr = Base;
4062 IsArrayExpr = OMPArraySection;
4063 }
4064 }
4065 ELoc = RefExpr->getExprLoc();
4066 ERange = RefExpr->getSourceRange();
4067 RefExpr = RefExpr->IgnoreParenImpCasts();
4068 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4069 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4070 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4071 (S.getCurrentThisType().isNull() || !ME ||
4072 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4073 !isa<FieldDecl>(ME->getMemberDecl()))) {
4074 if (IsArrayExpr != NoArrayExpr) {
4075 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4076 << ERange;
4077 } else {
4078 S.Diag(ELoc,
4079 AllowArraySection
4080 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4081 : diag::err_omp_expected_var_name_member_expr)
4082 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4083 }
4084 return std::make_pair(nullptr, false);
4085 }
4086 return std::make_pair(
4087 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4088}
4089
4090static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004091 ArrayRef<OMPClause *> Clauses) {
4092 assert(!S.CurContext->isDependentContext() &&
4093 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004094 auto AllocateRange =
4095 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004096 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4097 DeclToCopy;
4098 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4099 return isOpenMPPrivate(C->getClauseKind());
4100 });
4101 for (OMPClause *Cl : PrivateRange) {
4102 MutableArrayRef<Expr *>::iterator I, It, Et;
4103 if (Cl->getClauseKind() == OMPC_private) {
4104 auto *PC = cast<OMPPrivateClause>(Cl);
4105 I = PC->private_copies().begin();
4106 It = PC->varlist_begin();
4107 Et = PC->varlist_end();
4108 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4109 auto *PC = cast<OMPFirstprivateClause>(Cl);
4110 I = PC->private_copies().begin();
4111 It = PC->varlist_begin();
4112 Et = PC->varlist_end();
4113 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4114 auto *PC = cast<OMPLastprivateClause>(Cl);
4115 I = PC->private_copies().begin();
4116 It = PC->varlist_begin();
4117 Et = PC->varlist_end();
4118 } else if (Cl->getClauseKind() == OMPC_linear) {
4119 auto *PC = cast<OMPLinearClause>(Cl);
4120 I = PC->privates().begin();
4121 It = PC->varlist_begin();
4122 Et = PC->varlist_end();
4123 } else if (Cl->getClauseKind() == OMPC_reduction) {
4124 auto *PC = cast<OMPReductionClause>(Cl);
4125 I = PC->privates().begin();
4126 It = PC->varlist_begin();
4127 Et = PC->varlist_end();
4128 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4129 auto *PC = cast<OMPTaskReductionClause>(Cl);
4130 I = PC->privates().begin();
4131 It = PC->varlist_begin();
4132 Et = PC->varlist_end();
4133 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4134 auto *PC = cast<OMPInReductionClause>(Cl);
4135 I = PC->privates().begin();
4136 It = PC->varlist_begin();
4137 Et = PC->varlist_end();
4138 } else {
4139 llvm_unreachable("Expected private clause.");
4140 }
4141 for (Expr *E : llvm::make_range(It, Et)) {
4142 if (!*I) {
4143 ++I;
4144 continue;
4145 }
4146 SourceLocation ELoc;
4147 SourceRange ERange;
4148 Expr *SimpleRefExpr = E;
4149 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4150 /*AllowArraySection=*/true);
4151 DeclToCopy.try_emplace(Res.first,
4152 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4153 ++I;
4154 }
4155 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004156 for (OMPClause *C : AllocateRange) {
4157 auto *AC = cast<OMPAllocateClause>(C);
4158 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4159 getAllocatorKind(S, Stack, AC->getAllocator());
4160 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4161 // For task, taskloop or target directives, allocation requests to memory
4162 // allocators with the trait access set to thread result in unspecified
4163 // behavior.
4164 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4165 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4166 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4167 S.Diag(AC->getAllocator()->getExprLoc(),
4168 diag::warn_omp_allocate_thread_on_task_target_directive)
4169 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004170 }
4171 for (Expr *E : AC->varlists()) {
4172 SourceLocation ELoc;
4173 SourceRange ERange;
4174 Expr *SimpleRefExpr = E;
4175 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4176 ValueDecl *VD = Res.first;
4177 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4178 if (!isOpenMPPrivate(Data.CKind)) {
4179 S.Diag(E->getExprLoc(),
4180 diag::err_omp_expected_private_copy_for_allocate);
4181 continue;
4182 }
4183 VarDecl *PrivateVD = DeclToCopy[VD];
4184 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4185 AllocatorKind, AC->getAllocator()))
4186 continue;
4187 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4188 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004189 }
4190 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004191}
4192
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004193StmtResult Sema::ActOnOpenMPExecutableDirective(
4194 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4195 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4196 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004197 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004198 // First check CancelRegion which is then used in checkNestingOfRegions.
4199 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4200 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004201 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004202 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004203
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004204 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004205 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004206 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004207 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004208 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004209 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4210
4211 // Check default data sharing attributes for referenced variables.
4212 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004213 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4214 Stmt *S = AStmt;
4215 while (--ThisCaptureLevel >= 0)
4216 S = cast<CapturedStmt>(S)->getCapturedStmt();
4217 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004218 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4219 !isOpenMPTaskingDirective(Kind)) {
4220 // Visit subcaptures to generate implicit clauses for captured vars.
4221 auto *CS = cast<CapturedStmt>(AStmt);
4222 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4223 getOpenMPCaptureRegions(CaptureRegions, Kind);
4224 // Ignore outer tasking regions for target directives.
4225 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4226 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4227 DSAChecker.visitSubCaptures(CS);
4228 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004229 if (DSAChecker.isErrorFound())
4230 return StmtError();
4231 // Generate list of implicitly defined firstprivate variables.
4232 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004233
Alexey Bataev88202be2017-07-27 13:20:36 +00004234 SmallVector<Expr *, 4> ImplicitFirstprivates(
4235 DSAChecker.getImplicitFirstprivate().begin(),
4236 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004237 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4238 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004239 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004240 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004241 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004242 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004243 if (E)
4244 ImplicitFirstprivates.emplace_back(E);
4245 }
4246 }
4247 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004248 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004249 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4250 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004251 ClausesWithImplicit.push_back(Implicit);
4252 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004253 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004254 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004255 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004256 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004257 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004258 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004259 CXXScopeSpec MapperIdScopeSpec;
4260 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004261 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004262 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4263 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4264 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004265 ClausesWithImplicit.emplace_back(Implicit);
4266 ErrorFound |=
4267 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004268 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004269 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004270 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004271 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004273
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004274 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004275 switch (Kind) {
4276 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004277 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4278 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004279 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004280 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004281 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004282 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4283 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004284 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004285 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004286 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4287 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004288 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004289 case OMPD_for_simd:
4290 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4291 EndLoc, VarsWithInheritedDSA);
4292 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004293 case OMPD_sections:
4294 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4295 EndLoc);
4296 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004297 case OMPD_section:
4298 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004299 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004300 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4301 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004302 case OMPD_single:
4303 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4304 EndLoc);
4305 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004306 case OMPD_master:
4307 assert(ClausesWithImplicit.empty() &&
4308 "No clauses are allowed for 'omp master' directive");
4309 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4310 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004311 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004312 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4313 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004314 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004315 case OMPD_parallel_for:
4316 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4317 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004318 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004319 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004320 case OMPD_parallel_for_simd:
4321 Res = ActOnOpenMPParallelForSimdDirective(
4322 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004323 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004324 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004325 case OMPD_parallel_sections:
4326 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4327 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004328 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004329 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004330 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004331 Res =
4332 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004333 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004334 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004335 case OMPD_taskyield:
4336 assert(ClausesWithImplicit.empty() &&
4337 "No clauses are allowed for 'omp taskyield' directive");
4338 assert(AStmt == nullptr &&
4339 "No associated statement allowed for 'omp taskyield' directive");
4340 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4341 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004342 case OMPD_barrier:
4343 assert(ClausesWithImplicit.empty() &&
4344 "No clauses are allowed for 'omp barrier' directive");
4345 assert(AStmt == nullptr &&
4346 "No associated statement allowed for 'omp barrier' directive");
4347 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4348 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004349 case OMPD_taskwait:
4350 assert(ClausesWithImplicit.empty() &&
4351 "No clauses are allowed for 'omp taskwait' directive");
4352 assert(AStmt == nullptr &&
4353 "No associated statement allowed for 'omp taskwait' directive");
4354 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4355 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004356 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004357 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4358 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004359 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004360 case OMPD_flush:
4361 assert(AStmt == nullptr &&
4362 "No associated statement allowed for 'omp flush' directive");
4363 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4364 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004365 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004366 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4367 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004368 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004369 case OMPD_atomic:
4370 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4371 EndLoc);
4372 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004373 case OMPD_teams:
4374 Res =
4375 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4376 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004377 case OMPD_target:
4378 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4379 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004380 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004381 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004382 case OMPD_target_parallel:
4383 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4384 StartLoc, EndLoc);
4385 AllowedNameModifiers.push_back(OMPD_target);
4386 AllowedNameModifiers.push_back(OMPD_parallel);
4387 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004388 case OMPD_target_parallel_for:
4389 Res = ActOnOpenMPTargetParallelForDirective(
4390 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4391 AllowedNameModifiers.push_back(OMPD_target);
4392 AllowedNameModifiers.push_back(OMPD_parallel);
4393 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004394 case OMPD_cancellation_point:
4395 assert(ClausesWithImplicit.empty() &&
4396 "No clauses are allowed for 'omp cancellation point' directive");
4397 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4398 "cancellation point' directive");
4399 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4400 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004401 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004402 assert(AStmt == nullptr &&
4403 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004404 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4405 CancelRegion);
4406 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004407 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004408 case OMPD_target_data:
4409 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4410 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004411 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004412 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004413 case OMPD_target_enter_data:
4414 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004415 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004416 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4417 break;
Samuel Antao72590762016-01-19 20:04:50 +00004418 case OMPD_target_exit_data:
4419 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004420 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004421 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4422 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004423 case OMPD_taskloop:
4424 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4425 EndLoc, VarsWithInheritedDSA);
4426 AllowedNameModifiers.push_back(OMPD_taskloop);
4427 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004428 case OMPD_taskloop_simd:
4429 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4430 EndLoc, VarsWithInheritedDSA);
4431 AllowedNameModifiers.push_back(OMPD_taskloop);
4432 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004433 case OMPD_distribute:
4434 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4435 EndLoc, VarsWithInheritedDSA);
4436 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004437 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004438 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4439 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004440 AllowedNameModifiers.push_back(OMPD_target_update);
4441 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004442 case OMPD_distribute_parallel_for:
4443 Res = ActOnOpenMPDistributeParallelForDirective(
4444 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4445 AllowedNameModifiers.push_back(OMPD_parallel);
4446 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004447 case OMPD_distribute_parallel_for_simd:
4448 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4449 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4450 AllowedNameModifiers.push_back(OMPD_parallel);
4451 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004452 case OMPD_distribute_simd:
4453 Res = ActOnOpenMPDistributeSimdDirective(
4454 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4455 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004456 case OMPD_target_parallel_for_simd:
4457 Res = ActOnOpenMPTargetParallelForSimdDirective(
4458 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4459 AllowedNameModifiers.push_back(OMPD_target);
4460 AllowedNameModifiers.push_back(OMPD_parallel);
4461 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004462 case OMPD_target_simd:
4463 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4464 EndLoc, VarsWithInheritedDSA);
4465 AllowedNameModifiers.push_back(OMPD_target);
4466 break;
Kelvin Li02532872016-08-05 14:37:37 +00004467 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004468 Res = ActOnOpenMPTeamsDistributeDirective(
4469 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004470 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004471 case OMPD_teams_distribute_simd:
4472 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4473 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4474 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004475 case OMPD_teams_distribute_parallel_for_simd:
4476 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4477 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4478 AllowedNameModifiers.push_back(OMPD_parallel);
4479 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004480 case OMPD_teams_distribute_parallel_for:
4481 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4482 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4483 AllowedNameModifiers.push_back(OMPD_parallel);
4484 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004485 case OMPD_target_teams:
4486 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4487 EndLoc);
4488 AllowedNameModifiers.push_back(OMPD_target);
4489 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004490 case OMPD_target_teams_distribute:
4491 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4492 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4493 AllowedNameModifiers.push_back(OMPD_target);
4494 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004495 case OMPD_target_teams_distribute_parallel_for:
4496 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4497 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4498 AllowedNameModifiers.push_back(OMPD_target);
4499 AllowedNameModifiers.push_back(OMPD_parallel);
4500 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004501 case OMPD_target_teams_distribute_parallel_for_simd:
4502 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4503 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4504 AllowedNameModifiers.push_back(OMPD_target);
4505 AllowedNameModifiers.push_back(OMPD_parallel);
4506 break;
Kelvin Lida681182017-01-10 18:08:18 +00004507 case OMPD_target_teams_distribute_simd:
4508 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4510 AllowedNameModifiers.push_back(OMPD_target);
4511 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004512 case OMPD_declare_target:
4513 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004514 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004515 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004516 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004517 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004518 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004519 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004520 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004521 llvm_unreachable("OpenMP Directive is not allowed");
4522 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004523 llvm_unreachable("Unknown OpenMP directive");
4524 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004525
Roman Lebedevb5700602019-03-20 16:32:36 +00004526 ErrorFound = Res.isInvalid() || ErrorFound;
4527
Alexey Bataev412254a2019-05-09 18:44:53 +00004528 // Check variables in the clauses if default(none) was specified.
4529 if (DSAStack->getDefaultDSA() == DSA_none) {
4530 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4531 for (OMPClause *C : Clauses) {
4532 switch (C->getClauseKind()) {
4533 case OMPC_num_threads:
4534 case OMPC_dist_schedule:
4535 // Do not analyse if no parent teams directive.
4536 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4537 break;
4538 continue;
4539 case OMPC_if:
4540 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4541 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4542 break;
4543 continue;
4544 case OMPC_schedule:
4545 break;
4546 case OMPC_ordered:
4547 case OMPC_device:
4548 case OMPC_num_teams:
4549 case OMPC_thread_limit:
4550 case OMPC_priority:
4551 case OMPC_grainsize:
4552 case OMPC_num_tasks:
4553 case OMPC_hint:
4554 case OMPC_collapse:
4555 case OMPC_safelen:
4556 case OMPC_simdlen:
4557 case OMPC_final:
4558 case OMPC_default:
4559 case OMPC_proc_bind:
4560 case OMPC_private:
4561 case OMPC_firstprivate:
4562 case OMPC_lastprivate:
4563 case OMPC_shared:
4564 case OMPC_reduction:
4565 case OMPC_task_reduction:
4566 case OMPC_in_reduction:
4567 case OMPC_linear:
4568 case OMPC_aligned:
4569 case OMPC_copyin:
4570 case OMPC_copyprivate:
4571 case OMPC_nowait:
4572 case OMPC_untied:
4573 case OMPC_mergeable:
4574 case OMPC_allocate:
4575 case OMPC_read:
4576 case OMPC_write:
4577 case OMPC_update:
4578 case OMPC_capture:
4579 case OMPC_seq_cst:
4580 case OMPC_depend:
4581 case OMPC_threads:
4582 case OMPC_simd:
4583 case OMPC_map:
4584 case OMPC_nogroup:
4585 case OMPC_defaultmap:
4586 case OMPC_to:
4587 case OMPC_from:
4588 case OMPC_use_device_ptr:
4589 case OMPC_is_device_ptr:
4590 continue;
4591 case OMPC_allocator:
4592 case OMPC_flush:
4593 case OMPC_threadprivate:
4594 case OMPC_uniform:
4595 case OMPC_unknown:
4596 case OMPC_unified_address:
4597 case OMPC_unified_shared_memory:
4598 case OMPC_reverse_offload:
4599 case OMPC_dynamic_allocators:
4600 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004601 case OMPC_device_type:
Alexey Bataev412254a2019-05-09 18:44:53 +00004602 llvm_unreachable("Unexpected clause");
4603 }
4604 for (Stmt *CC : C->children()) {
4605 if (CC)
4606 DSAChecker.Visit(CC);
4607 }
4608 }
4609 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4610 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4611 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004612 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004613 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4614 continue;
4615 ErrorFound = true;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004616 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4617 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004618 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004619 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004620
4621 if (!AllowedNameModifiers.empty())
4622 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4623 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004624
Alexey Bataeved09d242014-05-28 05:53:51 +00004625 if (ErrorFound)
4626 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004627
4628 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4629 Res.getAs<OMPExecutableDirective>()
4630 ->getStructuredBlock()
4631 ->setIsOMPStructuredBlock(true);
4632 }
4633
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004634 if (!CurContext->isDependentContext() &&
4635 isOpenMPTargetExecutionDirective(Kind) &&
4636 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4637 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4638 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4639 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4640 // Register target to DSA Stack.
4641 DSAStack->addTargetDirLocation(StartLoc);
4642 }
4643
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004644 return Res;
4645}
4646
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004647Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4648 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004649 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004650 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4651 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004652 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004653 assert(Linears.size() == LinModifiers.size());
4654 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004655 if (!DG || DG.get().isNull())
4656 return DeclGroupPtrTy();
4657
Alexey Bataevd158cf62019-09-13 20:18:17 +00004658 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004659 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004660 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4661 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004662 return DG;
4663 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004664 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004665 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4666 ADecl = FTD->getTemplatedDecl();
4667
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004668 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4669 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004670 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004671 return DeclGroupPtrTy();
4672 }
4673
Alexey Bataev2af33e32016-04-07 12:45:37 +00004674 // OpenMP [2.8.2, declare simd construct, Description]
4675 // The parameter of the simdlen clause must be a constant positive integer
4676 // expression.
4677 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004678 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004679 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004680 // OpenMP [2.8.2, declare simd construct, Description]
4681 // The special this pointer can be used as if was one of the arguments to the
4682 // function in any of the linear, aligned, or uniform clauses.
4683 // The uniform clause declares one or more arguments to have an invariant
4684 // value for all concurrent invocations of the function in the execution of a
4685 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004686 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4687 const Expr *UniformedLinearThis = nullptr;
4688 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004689 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004690 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4691 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004692 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4693 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004694 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004695 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004696 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004697 }
4698 if (isa<CXXThisExpr>(E)) {
4699 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004700 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004701 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004702 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4703 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004704 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004705 // OpenMP [2.8.2, declare simd construct, Description]
4706 // The aligned clause declares that the object to which each list item points
4707 // is aligned to the number of bytes expressed in the optional parameter of
4708 // the aligned clause.
4709 // The special this pointer can be used as if was one of the arguments to the
4710 // function in any of the linear, aligned, or uniform clauses.
4711 // The type of list items appearing in the aligned clause must be array,
4712 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004713 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4714 const Expr *AlignedThis = nullptr;
4715 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004716 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004717 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4718 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4719 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004720 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4721 FD->getParamDecl(PVD->getFunctionScopeIndex())
4722 ->getCanonicalDecl() == CanonPVD) {
4723 // OpenMP [2.8.1, simd construct, Restrictions]
4724 // A list-item cannot appear in more than one aligned clause.
4725 if (AlignedArgs.count(CanonPVD) > 0) {
4726 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4727 << 1 << E->getSourceRange();
4728 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4729 diag::note_omp_explicit_dsa)
4730 << getOpenMPClauseName(OMPC_aligned);
4731 continue;
4732 }
4733 AlignedArgs[CanonPVD] = E;
4734 QualType QTy = PVD->getType()
4735 .getNonReferenceType()
4736 .getUnqualifiedType()
4737 .getCanonicalType();
4738 const Type *Ty = QTy.getTypePtrOrNull();
4739 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4740 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4741 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4742 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4743 }
4744 continue;
4745 }
4746 }
4747 if (isa<CXXThisExpr>(E)) {
4748 if (AlignedThis) {
4749 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4750 << 2 << E->getSourceRange();
4751 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4752 << getOpenMPClauseName(OMPC_aligned);
4753 }
4754 AlignedThis = E;
4755 continue;
4756 }
4757 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4758 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4759 }
4760 // The optional parameter of the aligned clause, alignment, must be a constant
4761 // positive integer expression. If no optional parameter is specified,
4762 // implementation-defined default alignments for SIMD instructions on the
4763 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004764 SmallVector<const Expr *, 4> NewAligns;
4765 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004766 ExprResult Align;
4767 if (E)
4768 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4769 NewAligns.push_back(Align.get());
4770 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004771 // OpenMP [2.8.2, declare simd construct, Description]
4772 // The linear clause declares one or more list items to be private to a SIMD
4773 // lane and to have a linear relationship with respect to the iteration space
4774 // of a loop.
4775 // The special this pointer can be used as if was one of the arguments to the
4776 // function in any of the linear, aligned, or uniform clauses.
4777 // When a linear-step expression is specified in a linear clause it must be
4778 // either a constant integer expression or an integer-typed parameter that is
4779 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004780 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004781 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4782 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004783 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004784 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4785 ++MI;
4786 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004787 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4788 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4789 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004790 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4791 FD->getParamDecl(PVD->getFunctionScopeIndex())
4792 ->getCanonicalDecl() == CanonPVD) {
4793 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4794 // A list-item cannot appear in more than one linear clause.
4795 if (LinearArgs.count(CanonPVD) > 0) {
4796 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4797 << getOpenMPClauseName(OMPC_linear)
4798 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4799 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4800 diag::note_omp_explicit_dsa)
4801 << getOpenMPClauseName(OMPC_linear);
4802 continue;
4803 }
4804 // Each argument can appear in at most one uniform or linear clause.
4805 if (UniformedArgs.count(CanonPVD) > 0) {
4806 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4807 << getOpenMPClauseName(OMPC_linear)
4808 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4809 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4810 diag::note_omp_explicit_dsa)
4811 << getOpenMPClauseName(OMPC_uniform);
4812 continue;
4813 }
4814 LinearArgs[CanonPVD] = E;
4815 if (E->isValueDependent() || E->isTypeDependent() ||
4816 E->isInstantiationDependent() ||
4817 E->containsUnexpandedParameterPack())
4818 continue;
4819 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4820 PVD->getOriginalType());
4821 continue;
4822 }
4823 }
4824 if (isa<CXXThisExpr>(E)) {
4825 if (UniformedLinearThis) {
4826 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4827 << getOpenMPClauseName(OMPC_linear)
4828 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4829 << E->getSourceRange();
4830 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4831 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4832 : OMPC_linear);
4833 continue;
4834 }
4835 UniformedLinearThis = E;
4836 if (E->isValueDependent() || E->isTypeDependent() ||
4837 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4838 continue;
4839 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4840 E->getType());
4841 continue;
4842 }
4843 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4844 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4845 }
4846 Expr *Step = nullptr;
4847 Expr *NewStep = nullptr;
4848 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004849 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004850 // Skip the same step expression, it was checked already.
4851 if (Step == E || !E) {
4852 NewSteps.push_back(E ? NewStep : nullptr);
4853 continue;
4854 }
4855 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004856 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4857 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4858 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004859 if (UniformedArgs.count(CanonPVD) == 0) {
4860 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4861 << Step->getSourceRange();
4862 } else if (E->isValueDependent() || E->isTypeDependent() ||
4863 E->isInstantiationDependent() ||
4864 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004865 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004866 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004867 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004868 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4869 << Step->getSourceRange();
4870 }
4871 continue;
4872 }
4873 NewStep = Step;
4874 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4875 !Step->isInstantiationDependent() &&
4876 !Step->containsUnexpandedParameterPack()) {
4877 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4878 .get();
4879 if (NewStep)
4880 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4881 }
4882 NewSteps.push_back(NewStep);
4883 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004884 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4885 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004886 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004887 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4888 const_cast<Expr **>(Linears.data()), Linears.size(),
4889 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4890 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004891 ADecl->addAttr(NewAttr);
4892 return ConvertDeclToDeclGroup(ADecl);
4893}
4894
Alexey Bataevd158cf62019-09-13 20:18:17 +00004895Sema::DeclGroupPtrTy
4896Sema::ActOnOpenMPDeclareVariantDirective(Sema::DeclGroupPtrTy DG,
4897 Expr *VariantRef, SourceRange SR) {
4898 if (!DG || DG.get().isNull())
4899 return DeclGroupPtrTy();
4900
4901 const int VariantId = 1;
4902 // Must be applied only to single decl.
4903 if (!DG.get().isSingleDecl()) {
4904 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4905 << VariantId << SR;
4906 return DG;
4907 }
4908 Decl *ADecl = DG.get().getSingleDecl();
4909 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4910 ADecl = FTD->getTemplatedDecl();
4911
4912 // Decl must be a function.
4913 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4914 if (!FD) {
4915 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
4916 << VariantId << SR;
4917 return DeclGroupPtrTy();
4918 }
4919
4920 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
4921 return FD->hasAttrs() &&
4922 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
4923 FD->hasAttr<TargetAttr>());
4924 };
4925 // OpenMP is not compatible with CPU-specific attributes.
4926 if (HasMultiVersionAttributes(FD)) {
4927 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
4928 << SR;
4929 return DG;
4930 }
4931
4932 // Allow #pragma omp declare variant only if the function is not used.
4933 if (FD->isUsed(false)) {
4934 Diag(SR.getBegin(), diag::err_omp_declare_variant_after_used)
4935 << FD->getLocation();
4936 return DG;
4937 }
4938
4939 // The VariantRef must point to function.
4940 if (!VariantRef) {
4941 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
4942 return DG;
4943 }
4944
4945 // Do not check templates, wait until instantiation.
4946 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
4947 VariantRef->containsUnexpandedParameterPack() ||
4948 VariantRef->isInstantiationDependent() || FD->isDependentContext())
4949 return DG;
4950
4951 // Convert VariantRef expression to the type of the original function to
4952 // resolve possible conflicts.
4953 ExprResult VariantRefCast;
4954 if (LangOpts.CPlusPlus) {
4955 QualType FnPtrType;
4956 auto *Method = dyn_cast<CXXMethodDecl>(FD);
4957 if (Method && !Method->isStatic()) {
4958 const Type *ClassType =
4959 Context.getTypeDeclType(Method->getParent()).getTypePtr();
4960 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
4961 ExprResult ER;
4962 {
4963 // Build adrr_of unary op to correctly handle type checks for member
4964 // functions.
4965 Sema::TentativeAnalysisScope Trap(*this);
4966 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
4967 VariantRef);
4968 }
4969 if (!ER.isUsable()) {
4970 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
4971 << VariantId << VariantRef->getSourceRange();
4972 return DG;
4973 }
4974 VariantRef = ER.get();
4975 } else {
4976 FnPtrType = Context.getPointerType(FD->getType());
4977 }
4978 ImplicitConversionSequence ICS =
4979 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
4980 /*SuppressUserConversions=*/false,
4981 /*AllowExplicit=*/false,
4982 /*InOverloadResolution=*/false,
4983 /*CStyle=*/false,
4984 /*AllowObjCWritebackConversion=*/false);
4985 if (ICS.isFailure()) {
4986 Diag(VariantRef->getExprLoc(),
4987 diag::err_omp_declare_variant_incompat_types)
4988 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
4989 return DG;
4990 }
4991 VariantRefCast = PerformImplicitConversion(
4992 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
4993 if (!VariantRefCast.isUsable())
4994 return DG;
4995 // Drop previously built artificial addr_of unary op for member functions.
4996 if (Method && !Method->isStatic()) {
4997 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
4998 if (auto *UO = dyn_cast<UnaryOperator>(
4999 PossibleAddrOfVariantRef->IgnoreImplicit()))
5000 VariantRefCast = UO->getSubExpr();
5001 }
5002 } else {
5003 VariantRefCast = VariantRef;
5004 }
5005
5006 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5007 if (!ER.isUsable() ||
5008 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5009 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5010 << VariantId << VariantRef->getSourceRange();
5011 return DG;
5012 }
5013
5014 // The VariantRef must point to function.
5015 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5016 if (!DRE) {
5017 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5018 << VariantId << VariantRef->getSourceRange();
5019 return DG;
5020 }
5021 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5022 if (!NewFD) {
5023 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5024 << VariantId << VariantRef->getSourceRange();
5025 return DG;
5026 }
5027
5028 enum DoesntSupport {
5029 VirtFuncs = 1,
5030 Constructors = 3,
5031 Destructors = 4,
5032 DeletedFuncs = 5,
5033 DefaultedFuncs = 6,
5034 ConstexprFuncs = 7,
5035 ConstevalFuncs = 8,
5036 };
5037 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5038 if (CXXFD->isVirtual()) {
5039 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5040 << VirtFuncs;
5041 return DG;
5042 }
5043
5044 if (isa<CXXConstructorDecl>(FD)) {
5045 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5046 << Constructors;
5047 return DG;
5048 }
5049
5050 if (isa<CXXDestructorDecl>(FD)) {
5051 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5052 << Destructors;
5053 return DG;
5054 }
5055 }
5056
5057 if (FD->isDeleted()) {
5058 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5059 << DeletedFuncs;
5060 return DG;
5061 }
5062
5063 if (FD->isDefaulted()) {
5064 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5065 << DefaultedFuncs;
5066 return DG;
5067 }
5068
5069 if (FD->isConstexpr()) {
5070 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5071 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
5072 return DG;
5073 }
5074
5075 // Check general compatibility.
5076 if (areMultiversionVariantFunctionsCompatible(
5077 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5078 PartialDiagnosticAt(
5079 SR.getBegin(),
5080 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5081 PartialDiagnosticAt(
5082 VariantRef->getExprLoc(),
5083 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5084 PartialDiagnosticAt(VariantRef->getExprLoc(),
5085 PDiag(diag::err_omp_declare_variant_diff)
5086 << FD->getLocation()),
5087 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false))
5088 return DG;
5089
5090 return DG;
5091}
5092
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005093StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5094 Stmt *AStmt,
5095 SourceLocation StartLoc,
5096 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005097 if (!AStmt)
5098 return StmtError();
5099
Alexey Bataeve3727102018-04-18 15:57:46 +00005100 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005101 // 1.2.2 OpenMP Language Terminology
5102 // Structured block - An executable statement with a single entry at the
5103 // top and a single exit at the bottom.
5104 // The point of exit cannot be a branch out of the structured block.
5105 // longjmp() and throw() must not violate the entry/exit criteria.
5106 CS->getCapturedDecl()->setNothrow();
5107
Reid Kleckner87a31802018-03-12 21:43:02 +00005108 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005109
Alexey Bataev25e5b442015-09-15 12:52:43 +00005110 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5111 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005112}
5113
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005114namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005115/// Iteration space of a single for loop.
5116struct LoopIterationSpace final {
5117 /// True if the condition operator is the strict compare operator (<, > or
5118 /// !=).
5119 bool IsStrictCompare = false;
5120 /// Condition of the loop.
5121 Expr *PreCond = nullptr;
5122 /// This expression calculates the number of iterations in the loop.
5123 /// It is always possible to calculate it before starting the loop.
5124 Expr *NumIterations = nullptr;
5125 /// The loop counter variable.
5126 Expr *CounterVar = nullptr;
5127 /// Private loop counter variable.
5128 Expr *PrivateCounterVar = nullptr;
5129 /// This is initializer for the initial value of #CounterVar.
5130 Expr *CounterInit = nullptr;
5131 /// This is step for the #CounterVar used to generate its update:
5132 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5133 Expr *CounterStep = nullptr;
5134 /// Should step be subtracted?
5135 bool Subtract = false;
5136 /// Source range of the loop init.
5137 SourceRange InitSrcRange;
5138 /// Source range of the loop condition.
5139 SourceRange CondSrcRange;
5140 /// Source range of the loop increment.
5141 SourceRange IncSrcRange;
5142 /// Minimum value that can have the loop control variable. Used to support
5143 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5144 /// since only such variables can be used in non-loop invariant expressions.
5145 Expr *MinValue = nullptr;
5146 /// Maximum value that can have the loop control variable. Used to support
5147 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5148 /// since only such variables can be used in non-loop invariant expressions.
5149 Expr *MaxValue = nullptr;
5150 /// true, if the lower bound depends on the outer loop control var.
5151 bool IsNonRectangularLB = false;
5152 /// true, if the upper bound depends on the outer loop control var.
5153 bool IsNonRectangularUB = false;
5154 /// Index of the loop this loop depends on and forms non-rectangular loop
5155 /// nest.
5156 unsigned LoopDependentIdx = 0;
5157 /// Final condition for the non-rectangular loop nest support. It is used to
5158 /// check that the number of iterations for this particular counter must be
5159 /// finished.
5160 Expr *FinalCondition = nullptr;
5161};
5162
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005163/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005164/// extracting iteration space of each loop in the loop nest, that will be used
5165/// for IR generation.
5166class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005167 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005168 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005169 /// Data-sharing stack.
5170 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005171 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005172 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005173 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005174 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005175 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005176 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005177 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005178 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005179 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005180 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005181 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005182 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005183 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005184 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005185 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005186 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005187 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005188 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005189 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005190 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005191 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005192 /// Var < UB
5193 /// Var <= UB
5194 /// UB > Var
5195 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005196 /// This will have no value when the condition is !=
5197 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005198 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005199 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005200 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005201 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005202 /// The outer loop counter this loop depends on (if any).
5203 const ValueDecl *DepDecl = nullptr;
5204 /// Contains number of loop (starts from 1) on which loop counter init
5205 /// expression of this loop depends on.
5206 Optional<unsigned> InitDependOnLC;
5207 /// Contains number of loop (starts from 1) on which loop counter condition
5208 /// expression of this loop depends on.
5209 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005210 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005211 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005212 /// Original condition required for checking of the exit condition for
5213 /// non-rectangular loop.
5214 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005215
5216public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005217 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5218 SourceLocation DefaultLoc)
5219 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5220 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005221 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005222 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005223 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005224 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005225 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005226 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005227 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005228 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005229 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005230 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005231 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005232 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005233 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005234 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005235 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005236 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005237 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005238 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005239 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005240 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005241 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005242 /// True, if the compare operator is strict (<, > or !=).
5243 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005244 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005245 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005246 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005247 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005248 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005249 Expr *
5250 buildPreCond(Scope *S, Expr *Cond,
5251 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005252 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005253 DeclRefExpr *
5254 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5255 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005256 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005257 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005258 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005259 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005260 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005261 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005262 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005263 /// Build loop data with counter value for depend clauses in ordered
5264 /// directives.
5265 Expr *
5266 buildOrderedLoopData(Scope *S, Expr *Counter,
5267 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5268 SourceLocation Loc, Expr *Inc = nullptr,
5269 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005270 /// Builds the minimum value for the loop counter.
5271 std::pair<Expr *, Expr *> buildMinMaxValues(
5272 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5273 /// Builds final condition for the non-rectangular loops.
5274 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005275 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005276 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005277 /// Returns true if the initializer forms non-rectangular loop.
5278 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5279 /// Returns true if the condition forms non-rectangular loop.
5280 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5281 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5282 unsigned getLoopDependentIdx() const {
5283 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5284 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005285
5286private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005287 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005288 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005289 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005290 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005291 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5292 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005293 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005294 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5295 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005296 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005297 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005298};
5299
Alexey Bataeve3727102018-04-18 15:57:46 +00005300bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005301 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005302 assert(!LB && !UB && !Step);
5303 return false;
5304 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005305 return LCDecl->getType()->isDependentType() ||
5306 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5307 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005308}
5309
Alexey Bataeve3727102018-04-18 15:57:46 +00005310bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005311 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005312 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005313 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005314 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005315 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005316 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005317 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005318 LCDecl = getCanonicalDecl(NewLCDecl);
5319 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005320 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5321 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005322 if ((Ctor->isCopyOrMoveConstructor() ||
5323 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5324 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005325 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005326 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005327 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005328 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005329 return false;
5330}
5331
Alexey Bataev316ccf62019-01-29 18:51:58 +00005332bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5333 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005334 bool StrictOp, SourceRange SR,
5335 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005336 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005337 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5338 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005339 if (!NewUB)
5340 return true;
5341 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005342 if (LessOp)
5343 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005344 TestIsStrictOp = StrictOp;
5345 ConditionSrcRange = SR;
5346 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005347 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005348 return false;
5349}
5350
Alexey Bataeve3727102018-04-18 15:57:46 +00005351bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005352 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005353 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005354 if (!NewStep)
5355 return true;
5356 if (!NewStep->isValueDependent()) {
5357 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005358 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005359 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5360 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005361 if (Val.isInvalid())
5362 return true;
5363 NewStep = Val.get();
5364
5365 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5366 // If test-expr is of form var relational-op b and relational-op is < or
5367 // <= then incr-expr must cause var to increase on each iteration of the
5368 // loop. If test-expr is of form var relational-op b and relational-op is
5369 // > or >= then incr-expr must cause var to decrease on each iteration of
5370 // the loop.
5371 // If test-expr is of form b relational-op var and relational-op is < or
5372 // <= then incr-expr must cause var to decrease on each iteration of the
5373 // loop. If test-expr is of form b relational-op var and relational-op is
5374 // > or >= then incr-expr must cause var to increase on each iteration of
5375 // the loop.
5376 llvm::APSInt Result;
5377 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5378 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5379 bool IsConstNeg =
5380 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005381 bool IsConstPos =
5382 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005383 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005384
5385 // != with increment is treated as <; != with decrement is treated as >
5386 if (!TestIsLessOp.hasValue())
5387 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005388 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005389 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005390 (IsConstNeg || (IsUnsigned && Subtract)) :
5391 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005392 SemaRef.Diag(NewStep->getExprLoc(),
5393 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005394 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005395 SemaRef.Diag(ConditionLoc,
5396 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005397 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005398 return true;
5399 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005400 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005401 NewStep =
5402 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5403 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005404 Subtract = !Subtract;
5405 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005406 }
5407
5408 Step = NewStep;
5409 SubtractStep = Subtract;
5410 return false;
5411}
5412
Alexey Bataev622af1d2019-04-24 19:58:30 +00005413namespace {
5414/// Checker for the non-rectangular loops. Checks if the initializer or
5415/// condition expression references loop counter variable.
5416class LoopCounterRefChecker final
5417 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5418 Sema &SemaRef;
5419 DSAStackTy &Stack;
5420 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005421 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005422 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005423 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005424 unsigned BaseLoopId = 0;
5425 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5426 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5427 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5428 << (IsInitializer ? 0 : 1);
5429 return false;
5430 }
5431 const auto &&Data = Stack.isLoopControlVariable(VD);
5432 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5433 // The type of the loop iterator on which we depend may not have a random
5434 // access iterator type.
5435 if (Data.first && VD->getType()->isRecordType()) {
5436 SmallString<128> Name;
5437 llvm::raw_svector_ostream OS(Name);
5438 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5439 /*Qualified=*/true);
5440 SemaRef.Diag(E->getExprLoc(),
5441 diag::err_omp_wrong_dependency_iterator_type)
5442 << OS.str();
5443 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5444 return false;
5445 }
5446 if (Data.first &&
5447 (DepDecl || (PrevDepDecl &&
5448 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5449 if (!DepDecl && PrevDepDecl)
5450 DepDecl = PrevDepDecl;
5451 SmallString<128> Name;
5452 llvm::raw_svector_ostream OS(Name);
5453 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5454 /*Qualified=*/true);
5455 SemaRef.Diag(E->getExprLoc(),
5456 diag::err_omp_invariant_or_linear_dependency)
5457 << OS.str();
5458 return false;
5459 }
5460 if (Data.first) {
5461 DepDecl = VD;
5462 BaseLoopId = Data.first;
5463 }
5464 return Data.first;
5465 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005466
5467public:
5468 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5469 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005470 if (isa<VarDecl>(VD))
5471 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005472 return false;
5473 }
5474 bool VisitMemberExpr(const MemberExpr *E) {
5475 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5476 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005477 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5478 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005479 }
5480 return false;
5481 }
5482 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005483 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005484 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005485 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005486 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005487 }
5488 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005489 const ValueDecl *CurLCDecl, bool IsInitializer,
5490 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005491 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005492 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5493 unsigned getBaseLoopId() const {
5494 assert(CurLCDecl && "Expected loop dependency.");
5495 return BaseLoopId;
5496 }
5497 const ValueDecl *getDepDecl() const {
5498 assert(CurLCDecl && "Expected loop dependency.");
5499 return DepDecl;
5500 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005501};
5502} // namespace
5503
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005504Optional<unsigned>
5505OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5506 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005507 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005508 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5509 DepDecl);
5510 if (LoopStmtChecker.Visit(S)) {
5511 DepDecl = LoopStmtChecker.getDepDecl();
5512 return LoopStmtChecker.getBaseLoopId();
5513 }
5514 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005515}
5516
Alexey Bataeve3727102018-04-18 15:57:46 +00005517bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005518 // Check init-expr for canonical loop form and save loop counter
5519 // variable - #Var and its initialization value - #LB.
5520 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5521 // var = lb
5522 // integer-type var = lb
5523 // random-access-iterator-type var = lb
5524 // pointer-type var = lb
5525 //
5526 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005527 if (EmitDiags) {
5528 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5529 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005530 return true;
5531 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005532 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5533 if (!ExprTemp->cleanupsHaveSideEffects())
5534 S = ExprTemp->getSubExpr();
5535
Alexander Musmana5f070a2014-10-01 06:03:56 +00005536 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005537 if (Expr *E = dyn_cast<Expr>(S))
5538 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005539 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005540 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005541 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005542 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5543 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5544 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005545 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5546 EmitDiags);
5547 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005548 }
5549 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5550 if (ME->isArrow() &&
5551 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005552 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5553 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005554 }
5555 }
David Majnemer9d168222016-08-05 17:44:54 +00005556 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005557 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005558 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005559 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005560 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005561 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005562 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005563 diag::ext_omp_loop_not_canonical_init)
5564 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005565 return setLCDeclAndLB(
5566 Var,
5567 buildDeclRefExpr(SemaRef, Var,
5568 Var->getType().getNonReferenceType(),
5569 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005570 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005571 }
5572 }
5573 }
David Majnemer9d168222016-08-05 17:44:54 +00005574 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005575 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005576 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005577 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005578 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5579 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005580 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5581 EmitDiags);
5582 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005583 }
5584 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5585 if (ME->isArrow() &&
5586 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005587 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5588 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005589 }
5590 }
5591 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005592
Alexey Bataeve3727102018-04-18 15:57:46 +00005593 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005594 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005595 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005596 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005597 << S->getSourceRange();
5598 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005599 return true;
5600}
5601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005602/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005603/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005604static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005605 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005606 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005607 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005608 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005609 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005610 if ((Ctor->isCopyOrMoveConstructor() ||
5611 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5612 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005613 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005614 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5615 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005616 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005617 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005618 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005619 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5620 return getCanonicalDecl(ME->getMemberDecl());
5621 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005622}
5623
Alexey Bataeve3727102018-04-18 15:57:46 +00005624bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005625 // Check test-expr for canonical form, save upper-bound UB, flags for
5626 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005627 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005628 // var relational-op b
5629 // b relational-op var
5630 //
Alexey Bataev1be63402019-09-11 15:44:06 +00005631 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005632 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00005633 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
5634 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005635 return true;
5636 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00005637 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005638 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005639 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005640 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005641 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005642 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5643 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005644 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5645 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5646 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005647 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5648 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005649 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5650 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5651 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00005652 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
5653 return setUB(
5654 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
5655 /*LessOp=*/llvm::None,
5656 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005657 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005658 if (CE->getNumArgs() == 2) {
5659 auto Op = CE->getOperator();
5660 switch (Op) {
5661 case OO_Greater:
5662 case OO_GreaterEqual:
5663 case OO_Less:
5664 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005665 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5666 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005667 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5668 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005669 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5670 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005671 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5672 CE->getOperatorLoc());
5673 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005674 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00005675 if (IneqCondIsCanonical)
5676 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
5677 : CE->getArg(0),
5678 /*LessOp=*/llvm::None,
5679 /*StrictOp=*/true, CE->getSourceRange(),
5680 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005681 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005682 default:
5683 break;
5684 }
5685 }
5686 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005687 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005688 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005689 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00005690 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005691 return true;
5692}
5693
Alexey Bataeve3727102018-04-18 15:57:46 +00005694bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005695 // RHS of canonical loop form increment can be:
5696 // var + incr
5697 // incr + var
5698 // var - incr
5699 //
5700 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005701 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005702 if (BO->isAdditiveOp()) {
5703 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005704 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5705 return setStep(BO->getRHS(), !IsAdd);
5706 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5707 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005708 }
David Majnemer9d168222016-08-05 17:44:54 +00005709 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005710 bool IsAdd = CE->getOperator() == OO_Plus;
5711 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005712 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5713 return setStep(CE->getArg(1), !IsAdd);
5714 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5715 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005716 }
5717 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005718 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005719 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005720 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005721 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005722 return true;
5723}
5724
Alexey Bataeve3727102018-04-18 15:57:46 +00005725bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005726 // Check incr-expr for canonical loop form and return true if it
5727 // does not conform.
5728 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5729 // ++var
5730 // var++
5731 // --var
5732 // var--
5733 // var += incr
5734 // var -= incr
5735 // var = var + incr
5736 // var = incr + var
5737 // var = var - incr
5738 //
5739 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005740 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005741 return true;
5742 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005743 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5744 if (!ExprTemp->cleanupsHaveSideEffects())
5745 S = ExprTemp->getSubExpr();
5746
Alexander Musmana5f070a2014-10-01 06:03:56 +00005747 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005748 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005749 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005750 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005751 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5752 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005753 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005754 (UO->isDecrementOp() ? -1 : 1))
5755 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005756 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005757 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005758 switch (BO->getOpcode()) {
5759 case BO_AddAssign:
5760 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005761 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5762 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005763 break;
5764 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005765 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5766 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005767 break;
5768 default:
5769 break;
5770 }
David Majnemer9d168222016-08-05 17:44:54 +00005771 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005772 switch (CE->getOperator()) {
5773 case OO_PlusPlus:
5774 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005775 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5776 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005777 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005778 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005779 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5780 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005781 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005782 break;
5783 case OO_PlusEqual:
5784 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005785 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5786 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005787 break;
5788 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005789 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5790 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005791 break;
5792 default:
5793 break;
5794 }
5795 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005796 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005797 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005798 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005799 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005800 return true;
5801}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005802
Alexey Bataev5a3af132016-03-29 08:58:54 +00005803static ExprResult
5804tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005805 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005806 if (SemaRef.CurContext->isDependentContext())
5807 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005808 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5809 return SemaRef.PerformImplicitConversion(
5810 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5811 /*AllowExplicit=*/true);
5812 auto I = Captures.find(Capture);
5813 if (I != Captures.end())
5814 return buildCapture(SemaRef, Capture, I->second);
5815 DeclRefExpr *Ref = nullptr;
5816 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5817 Captures[Capture] = Ref;
5818 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005819}
5820
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005821/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005822Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005823 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005824 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005825 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005826 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005827 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005828 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005829 Expr *LBVal = LB;
5830 Expr *UBVal = UB;
5831 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
5832 // max(LB(MinVal), LB(MaxVal))
5833 if (InitDependOnLC) {
5834 const LoopIterationSpace &IS =
5835 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5836 InitDependOnLC.getValueOr(
5837 CondDependOnLC.getValueOr(0))];
5838 if (!IS.MinValue || !IS.MaxValue)
5839 return nullptr;
5840 // OuterVar = Min
5841 ExprResult MinValue =
5842 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5843 if (!MinValue.isUsable())
5844 return nullptr;
5845
5846 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5847 IS.CounterVar, MinValue.get());
5848 if (!LBMinVal.isUsable())
5849 return nullptr;
5850 // OuterVar = Min, LBVal
5851 LBMinVal =
5852 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
5853 if (!LBMinVal.isUsable())
5854 return nullptr;
5855 // (OuterVar = Min, LBVal)
5856 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
5857 if (!LBMinVal.isUsable())
5858 return nullptr;
5859
5860 // OuterVar = Max
5861 ExprResult MaxValue =
5862 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5863 if (!MaxValue.isUsable())
5864 return nullptr;
5865
5866 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5867 IS.CounterVar, MaxValue.get());
5868 if (!LBMaxVal.isUsable())
5869 return nullptr;
5870 // OuterVar = Max, LBVal
5871 LBMaxVal =
5872 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
5873 if (!LBMaxVal.isUsable())
5874 return nullptr;
5875 // (OuterVar = Max, LBVal)
5876 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
5877 if (!LBMaxVal.isUsable())
5878 return nullptr;
5879
5880 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
5881 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
5882 if (!LBMin || !LBMax)
5883 return nullptr;
5884 // LB(MinVal) < LB(MaxVal)
5885 ExprResult MinLessMaxRes =
5886 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
5887 if (!MinLessMaxRes.isUsable())
5888 return nullptr;
5889 Expr *MinLessMax =
5890 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
5891 if (!MinLessMax)
5892 return nullptr;
5893 if (TestIsLessOp.getValue()) {
5894 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
5895 // LB(MaxVal))
5896 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
5897 MinLessMax, LBMin, LBMax);
5898 if (!MinLB.isUsable())
5899 return nullptr;
5900 LBVal = MinLB.get();
5901 } else {
5902 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
5903 // LB(MaxVal))
5904 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
5905 MinLessMax, LBMax, LBMin);
5906 if (!MaxLB.isUsable())
5907 return nullptr;
5908 LBVal = MaxLB.get();
5909 }
5910 }
5911 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
5912 // min(UB(MinVal), UB(MaxVal))
5913 if (CondDependOnLC) {
5914 const LoopIterationSpace &IS =
5915 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5916 InitDependOnLC.getValueOr(
5917 CondDependOnLC.getValueOr(0))];
5918 if (!IS.MinValue || !IS.MaxValue)
5919 return nullptr;
5920 // OuterVar = Min
5921 ExprResult MinValue =
5922 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5923 if (!MinValue.isUsable())
5924 return nullptr;
5925
5926 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5927 IS.CounterVar, MinValue.get());
5928 if (!UBMinVal.isUsable())
5929 return nullptr;
5930 // OuterVar = Min, UBVal
5931 UBMinVal =
5932 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
5933 if (!UBMinVal.isUsable())
5934 return nullptr;
5935 // (OuterVar = Min, UBVal)
5936 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
5937 if (!UBMinVal.isUsable())
5938 return nullptr;
5939
5940 // OuterVar = Max
5941 ExprResult MaxValue =
5942 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5943 if (!MaxValue.isUsable())
5944 return nullptr;
5945
5946 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5947 IS.CounterVar, MaxValue.get());
5948 if (!UBMaxVal.isUsable())
5949 return nullptr;
5950 // OuterVar = Max, UBVal
5951 UBMaxVal =
5952 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
5953 if (!UBMaxVal.isUsable())
5954 return nullptr;
5955 // (OuterVar = Max, UBVal)
5956 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
5957 if (!UBMaxVal.isUsable())
5958 return nullptr;
5959
5960 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
5961 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
5962 if (!UBMin || !UBMax)
5963 return nullptr;
5964 // UB(MinVal) > UB(MaxVal)
5965 ExprResult MinGreaterMaxRes =
5966 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
5967 if (!MinGreaterMaxRes.isUsable())
5968 return nullptr;
5969 Expr *MinGreaterMax =
5970 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
5971 if (!MinGreaterMax)
5972 return nullptr;
5973 if (TestIsLessOp.getValue()) {
5974 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
5975 // UB(MaxVal))
5976 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
5977 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
5978 if (!MaxUB.isUsable())
5979 return nullptr;
5980 UBVal = MaxUB.get();
5981 } else {
5982 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
5983 // UB(MaxVal))
5984 ExprResult MinUB = SemaRef.ActOnConditionalOp(
5985 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
5986 if (!MinUB.isUsable())
5987 return nullptr;
5988 UBVal = MinUB.get();
5989 }
5990 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005991 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00005992 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
5993 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00005994 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
5995 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005996 if (!Upper || !Lower)
5997 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005998
5999 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6000
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006001 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006002 // BuildBinOp already emitted error, this one is to point user to upper
6003 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006004 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006005 << Upper->getSourceRange() << Lower->getSourceRange();
6006 return nullptr;
6007 }
6008 }
6009
6010 if (!Diff.isUsable())
6011 return nullptr;
6012
6013 // Upper - Lower [- 1]
6014 if (TestIsStrictOp)
6015 Diff = SemaRef.BuildBinOp(
6016 S, DefaultLoc, BO_Sub, Diff.get(),
6017 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6018 if (!Diff.isUsable())
6019 return nullptr;
6020
6021 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006022 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006023 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006024 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006025 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006026 if (!Diff.isUsable())
6027 return nullptr;
6028
6029 // Parentheses (for dumping/debugging purposes only).
6030 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6031 if (!Diff.isUsable())
6032 return nullptr;
6033
6034 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006035 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006036 if (!Diff.isUsable())
6037 return nullptr;
6038
Alexander Musman174b3ca2014-10-06 11:16:29 +00006039 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006040 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006041 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006042 bool UseVarType = VarType->hasIntegerRepresentation() &&
6043 C.getTypeSize(Type) > C.getTypeSize(VarType);
6044 if (!Type->isIntegerType() || UseVarType) {
6045 unsigned NewSize =
6046 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6047 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6048 : Type->hasSignedIntegerRepresentation();
6049 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006050 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6051 Diff = SemaRef.PerformImplicitConversion(
6052 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6053 if (!Diff.isUsable())
6054 return nullptr;
6055 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006056 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006057 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006058 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6059 if (NewSize != C.getTypeSize(Type)) {
6060 if (NewSize < C.getTypeSize(Type)) {
6061 assert(NewSize == 64 && "incorrect loop var size");
6062 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6063 << InitSrcRange << ConditionSrcRange;
6064 }
6065 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006066 NewSize, Type->hasSignedIntegerRepresentation() ||
6067 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006068 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6069 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6070 Sema::AA_Converting, true);
6071 if (!Diff.isUsable())
6072 return nullptr;
6073 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006074 }
6075 }
6076
Alexander Musmana5f070a2014-10-01 06:03:56 +00006077 return Diff.get();
6078}
6079
Alexey Bataevf8be4762019-08-14 19:30:06 +00006080std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6081 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6082 // Do not build for iterators, they cannot be used in non-rectangular loop
6083 // nests.
6084 if (LCDecl->getType()->isRecordType())
6085 return std::make_pair(nullptr, nullptr);
6086 // If we subtract, the min is in the condition, otherwise the min is in the
6087 // init value.
6088 Expr *MinExpr = nullptr;
6089 Expr *MaxExpr = nullptr;
6090 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6091 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6092 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6093 : CondDependOnLC.hasValue();
6094 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6095 : InitDependOnLC.hasValue();
6096 Expr *Lower =
6097 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6098 Expr *Upper =
6099 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6100 if (!Upper || !Lower)
6101 return std::make_pair(nullptr, nullptr);
6102
6103 if (TestIsLessOp.getValue())
6104 MinExpr = Lower;
6105 else
6106 MaxExpr = Upper;
6107
6108 // Build minimum/maximum value based on number of iterations.
6109 ExprResult Diff;
6110 QualType VarType = LCDecl->getType().getNonReferenceType();
6111
6112 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6113 if (!Diff.isUsable())
6114 return std::make_pair(nullptr, nullptr);
6115
6116 // Upper - Lower [- 1]
6117 if (TestIsStrictOp)
6118 Diff = SemaRef.BuildBinOp(
6119 S, DefaultLoc, BO_Sub, Diff.get(),
6120 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6121 if (!Diff.isUsable())
6122 return std::make_pair(nullptr, nullptr);
6123
6124 // Upper - Lower [- 1] + Step
6125 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6126 if (!NewStep.isUsable())
6127 return std::make_pair(nullptr, nullptr);
6128
6129 // Parentheses (for dumping/debugging purposes only).
6130 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6131 if (!Diff.isUsable())
6132 return std::make_pair(nullptr, nullptr);
6133
6134 // (Upper - Lower [- 1]) / Step
6135 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6136 if (!Diff.isUsable())
6137 return std::make_pair(nullptr, nullptr);
6138
6139 // ((Upper - Lower [- 1]) / Step) * Step
6140 // Parentheses (for dumping/debugging purposes only).
6141 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6142 if (!Diff.isUsable())
6143 return std::make_pair(nullptr, nullptr);
6144
6145 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6146 if (!Diff.isUsable())
6147 return std::make_pair(nullptr, nullptr);
6148
6149 // Convert to the original type or ptrdiff_t, if original type is pointer.
6150 if (!VarType->isAnyPointerType() &&
6151 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6152 Diff = SemaRef.PerformImplicitConversion(
6153 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6154 } else if (VarType->isAnyPointerType() &&
6155 !SemaRef.Context.hasSameType(
6156 Diff.get()->getType(),
6157 SemaRef.Context.getUnsignedPointerDiffType())) {
6158 Diff = SemaRef.PerformImplicitConversion(
6159 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6160 Sema::AA_Converting, /*AllowExplicit=*/true);
6161 }
6162 if (!Diff.isUsable())
6163 return std::make_pair(nullptr, nullptr);
6164
6165 // Parentheses (for dumping/debugging purposes only).
6166 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6167 if (!Diff.isUsable())
6168 return std::make_pair(nullptr, nullptr);
6169
6170 if (TestIsLessOp.getValue()) {
6171 // MinExpr = Lower;
6172 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6173 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6174 if (!Diff.isUsable())
6175 return std::make_pair(nullptr, nullptr);
6176 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6177 if (!Diff.isUsable())
6178 return std::make_pair(nullptr, nullptr);
6179 MaxExpr = Diff.get();
6180 } else {
6181 // MaxExpr = Upper;
6182 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6183 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6184 if (!Diff.isUsable())
6185 return std::make_pair(nullptr, nullptr);
6186 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6187 if (!Diff.isUsable())
6188 return std::make_pair(nullptr, nullptr);
6189 MinExpr = Diff.get();
6190 }
6191
6192 return std::make_pair(MinExpr, MaxExpr);
6193}
6194
6195Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6196 if (InitDependOnLC || CondDependOnLC)
6197 return Condition;
6198 return nullptr;
6199}
6200
Alexey Bataeve3727102018-04-18 15:57:46 +00006201Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006202 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006203 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006204 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006205 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006206
Alexey Bataevf8be4762019-08-14 19:30:06 +00006207 ExprResult NewLB =
6208 InitDependOnLC ? LB : tryBuildCapture(SemaRef, LB, Captures);
6209 ExprResult NewUB =
6210 CondDependOnLC ? UB : tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006211 if (!NewLB.isUsable() || !NewUB.isUsable())
6212 return nullptr;
6213
Alexey Bataeve3727102018-04-18 15:57:46 +00006214 ExprResult CondExpr =
6215 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006216 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006217 (TestIsStrictOp ? BO_LT : BO_LE) :
6218 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006219 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006220 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006221 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6222 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006223 CondExpr = SemaRef.PerformImplicitConversion(
6224 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6225 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006226 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006227
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006228 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006229 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6230}
6231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006232/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006233DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006234 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6235 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006236 auto *VD = dyn_cast<VarDecl>(LCDecl);
6237 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006238 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6239 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006240 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006241 const DSAStackTy::DSAVarData Data =
6242 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006243 // If the loop control decl is explicitly marked as private, do not mark it
6244 // as captured again.
6245 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6246 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006247 return Ref;
6248 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006249 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006250}
6251
Alexey Bataeve3727102018-04-18 15:57:46 +00006252Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006253 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006254 QualType Type = LCDecl->getType().getNonReferenceType();
6255 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006256 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6257 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6258 isa<VarDecl>(LCDecl)
6259 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6260 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006261 if (PrivateVar->isInvalidDecl())
6262 return nullptr;
6263 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6264 }
6265 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006266}
6267
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006268/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006269Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006270
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006271/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006272Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006273
Alexey Bataevf138fda2018-08-13 19:04:24 +00006274Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6275 Scope *S, Expr *Counter,
6276 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6277 Expr *Inc, OverloadedOperatorKind OOK) {
6278 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6279 if (!Cnt)
6280 return nullptr;
6281 if (Inc) {
6282 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6283 "Expected only + or - operations for depend clauses.");
6284 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6285 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6286 if (!Cnt)
6287 return nullptr;
6288 }
6289 ExprResult Diff;
6290 QualType VarType = LCDecl->getType().getNonReferenceType();
6291 if (VarType->isIntegerType() || VarType->isPointerType() ||
6292 SemaRef.getLangOpts().CPlusPlus) {
6293 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006294 Expr *Upper = TestIsLessOp.getValue()
6295 ? Cnt
6296 : tryBuildCapture(SemaRef, UB, Captures).get();
6297 Expr *Lower = TestIsLessOp.getValue()
6298 ? tryBuildCapture(SemaRef, LB, Captures).get()
6299 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006300 if (!Upper || !Lower)
6301 return nullptr;
6302
6303 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6304
6305 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6306 // BuildBinOp already emitted error, this one is to point user to upper
6307 // and lower bound, and to tell what is passed to 'operator-'.
6308 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6309 << Upper->getSourceRange() << Lower->getSourceRange();
6310 return nullptr;
6311 }
6312 }
6313
6314 if (!Diff.isUsable())
6315 return nullptr;
6316
6317 // Parentheses (for dumping/debugging purposes only).
6318 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6319 if (!Diff.isUsable())
6320 return nullptr;
6321
6322 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6323 if (!NewStep.isUsable())
6324 return nullptr;
6325 // (Upper - Lower) / Step
6326 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6327 if (!Diff.isUsable())
6328 return nullptr;
6329
6330 return Diff.get();
6331}
Alexey Bataev23b69422014-06-18 07:08:49 +00006332} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006333
Alexey Bataev9c821032015-04-30 04:23:23 +00006334void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6335 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6336 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006337 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6338 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006339 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006340 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006341 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006342 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6343 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006344 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006345 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006346 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006347 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006348 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006349 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006350 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6351 /*WithInit=*/false);
6352 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006353 }
6354 }
6355 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006356 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6357 if (LD != D->getCanonicalDecl()) {
6358 DSAStack->resetPossibleLoopCounter();
6359 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6360 MarkDeclarationsReferencedInExpr(
6361 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6362 Var->getType().getNonLValueExprType(Context),
6363 ForLoc, /*RefersToCapture=*/true));
6364 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006365 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6366 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6367 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6368 // associated for-loop of a simd construct with just one associated
6369 // for-loop may be listed in a linear clause with a constant-linear-step
6370 // that is the increment of the associated for-loop. The loop iteration
6371 // variable(s) in the associated for-loop(s) of a for or parallel for
6372 // construct may be listed in a private or lastprivate clause.
6373 DSAStackTy::DSAVarData DVar =
6374 DSAStack->getTopDSA(D, /*FromParent=*/false);
6375 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6376 // is declared in the loop and it is predetermined as a private.
6377 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6378 OpenMPClauseKind PredeterminedCKind =
6379 isOpenMPSimdDirective(DKind)
6380 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6381 : OMPC_private;
6382 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6383 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6384 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6385 DVar.CKind != OMPC_private))) ||
6386 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
6387 isOpenMPDistributeDirective(DKind)) &&
6388 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6389 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6390 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6391 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6392 << getOpenMPClauseName(DVar.CKind)
6393 << getOpenMPDirectiveName(DKind)
6394 << getOpenMPClauseName(PredeterminedCKind);
6395 if (DVar.RefExpr == nullptr)
6396 DVar.CKind = PredeterminedCKind;
6397 reportOriginalDsa(*this, DSAStack, D, DVar,
6398 /*IsLoopIterVar=*/true);
6399 } else if (LoopDeclRefExpr) {
6400 // Make the loop iteration variable private (for worksharing
6401 // constructs), linear (for simd directives with the only one
6402 // associated loop) or lastprivate (for simd directives with several
6403 // collapsed or ordered loops).
6404 if (DVar.CKind == OMPC_unknown)
6405 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6406 PrivateRef);
6407 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006408 }
6409 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006410 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006411 }
6412}
6413
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006414/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006415/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006416static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006417 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6418 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006419 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6420 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006421 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006422 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006423 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006424 // OpenMP [2.6, Canonical Loop Form]
6425 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006426 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006427 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006428 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006429 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006430 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006431 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006432 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006433 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6434 SemaRef.Diag(DSA.getConstructLoc(),
6435 diag::note_omp_collapse_ordered_expr)
6436 << 2 << CollapseLoopCountExpr->getSourceRange()
6437 << OrderedLoopCountExpr->getSourceRange();
6438 else if (CollapseLoopCountExpr)
6439 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6440 diag::note_omp_collapse_ordered_expr)
6441 << 0 << CollapseLoopCountExpr->getSourceRange();
6442 else
6443 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6444 diag::note_omp_collapse_ordered_expr)
6445 << 1 << OrderedLoopCountExpr->getSourceRange();
6446 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006447 return true;
6448 }
6449 assert(For->getBody());
6450
Alexey Bataev622af1d2019-04-24 19:58:30 +00006451 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006452
6453 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00006454 Stmt *Init = For->getInit();
6455 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006456 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006457
6458 bool HasErrors = false;
6459
6460 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006461 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006462 // OpenMP [2.6, Canonical Loop Form]
6463 // Var is one of the following:
6464 // A variable of signed or unsigned integer type.
6465 // For C++, a variable of a random access iterator type.
6466 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006467 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006468 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6469 !VarType->isPointerType() &&
6470 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006471 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006472 << SemaRef.getLangOpts().CPlusPlus;
6473 HasErrors = true;
6474 }
6475
6476 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6477 // a Construct
6478 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6479 // parallel for construct is (are) private.
6480 // The loop iteration variable in the associated for-loop of a simd
6481 // construct with just one associated for-loop is linear with a
6482 // constant-linear-step that is the increment of the associated for-loop.
6483 // Exclude loop var from the list of variables with implicitly defined data
6484 // sharing attributes.
6485 VarsWithImplicitDSA.erase(LCDecl);
6486
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006487 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6488
6489 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00006490 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006491
6492 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00006493 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006494 }
6495
Alexey Bataeve3727102018-04-18 15:57:46 +00006496 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006497 return HasErrors;
6498
Alexander Musmana5f070a2014-10-01 06:03:56 +00006499 // Build the loop's iteration space representation.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006500 ResultIterSpaces[CurrentNestedLoopCount].PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00006501 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006502 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6503 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6504 (isOpenMPWorksharingDirective(DKind) ||
6505 isOpenMPTaskLoopDirective(DKind) ||
6506 isOpenMPDistributeDirective(DKind)),
6507 Captures);
6508 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6509 ISC.buildCounterVar(Captures, DSA);
6510 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6511 ISC.buildPrivateCounterVar();
6512 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6513 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6514 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6515 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6516 ISC.getConditionSrcRange();
6517 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6518 ISC.getIncrementSrcRange();
6519 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6520 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6521 ISC.isStrictTestOp();
6522 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6523 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6524 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6525 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6526 ISC.buildFinalCondition(DSA.getCurScope());
6527 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6528 ISC.doesInitDependOnLC();
6529 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6530 ISC.doesCondDependOnLC();
6531 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6532 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006533
Alexey Bataevf8be4762019-08-14 19:30:06 +00006534 HasErrors |=
6535 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6536 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6537 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6538 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6539 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6540 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006541 if (!HasErrors && DSA.isOrderedRegion()) {
6542 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6543 if (CurrentNestedLoopCount <
6544 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6545 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006546 CurrentNestedLoopCount,
6547 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006548 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006549 CurrentNestedLoopCount,
6550 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006551 }
6552 }
6553 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6554 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6555 // Erroneous case - clause has some problems.
6556 continue;
6557 }
6558 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6559 Pair.second.size() <= CurrentNestedLoopCount) {
6560 // Erroneous case - clause has some problems.
6561 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6562 continue;
6563 }
6564 Expr *CntValue;
6565 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6566 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006567 DSA.getCurScope(),
6568 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006569 Pair.first->getDependencyLoc());
6570 else
6571 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006572 DSA.getCurScope(),
6573 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006574 Pair.first->getDependencyLoc(),
6575 Pair.second[CurrentNestedLoopCount].first,
6576 Pair.second[CurrentNestedLoopCount].second);
6577 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6578 }
6579 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006580
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006581 return HasErrors;
6582}
6583
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006584/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006585static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006586buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006587 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006588 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006589 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006590 ExprResult NewStart = IsNonRectangularLB
6591 ? Start.get()
6592 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006593 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006594 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006595 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006596 VarRef.get()->getType())) {
6597 NewStart = SemaRef.PerformImplicitConversion(
6598 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6599 /*AllowExplicit=*/true);
6600 if (!NewStart.isUsable())
6601 return ExprError();
6602 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006603
Alexey Bataeve3727102018-04-18 15:57:46 +00006604 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006605 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6606 return Init;
6607}
6608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006609/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006610static ExprResult buildCounterUpdate(
6611 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6612 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006613 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006614 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006615 // Add parentheses (for debugging purposes only).
6616 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
6617 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
6618 !Step.isUsable())
6619 return ExprError();
6620
Alexey Bataev5a3af132016-03-29 08:58:54 +00006621 ExprResult NewStep = Step;
6622 if (Captures)
6623 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006624 if (NewStep.isInvalid())
6625 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006626 ExprResult Update =
6627 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006628 if (!Update.isUsable())
6629 return ExprError();
6630
Alexey Bataevc0214e02016-02-16 12:13:49 +00006631 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
6632 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006633 if (!Start.isUsable())
6634 return ExprError();
6635 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
6636 if (!NewStart.isUsable())
6637 return ExprError();
6638 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006639 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006640 if (NewStart.isInvalid())
6641 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006642
Alexey Bataevc0214e02016-02-16 12:13:49 +00006643 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
6644 ExprResult SavedUpdate = Update;
6645 ExprResult UpdateVal;
6646 if (VarRef.get()->getType()->isOverloadableType() ||
6647 NewStart.get()->getType()->isOverloadableType() ||
6648 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006649 Sema::TentativeAnalysisScope Trap(SemaRef);
6650
Alexey Bataevc0214e02016-02-16 12:13:49 +00006651 Update =
6652 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6653 if (Update.isUsable()) {
6654 UpdateVal =
6655 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
6656 VarRef.get(), SavedUpdate.get());
6657 if (UpdateVal.isUsable()) {
6658 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
6659 UpdateVal.get());
6660 }
6661 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006662 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006663
Alexey Bataevc0214e02016-02-16 12:13:49 +00006664 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
6665 if (!Update.isUsable() || !UpdateVal.isUsable()) {
6666 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
6667 NewStart.get(), SavedUpdate.get());
6668 if (!Update.isUsable())
6669 return ExprError();
6670
Alexey Bataev11481f52016-02-17 10:29:05 +00006671 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
6672 VarRef.get()->getType())) {
6673 Update = SemaRef.PerformImplicitConversion(
6674 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
6675 if (!Update.isUsable())
6676 return ExprError();
6677 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006678
6679 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
6680 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006681 return Update;
6682}
6683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006684/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006685/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006686static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006687 if (E == nullptr)
6688 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006689 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006690 QualType OldType = E->getType();
6691 unsigned HasBits = C.getTypeSize(OldType);
6692 if (HasBits >= Bits)
6693 return ExprResult(E);
6694 // OK to convert to signed, because new type has more bits than old.
6695 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
6696 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
6697 true);
6698}
6699
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006700/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006701/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006702static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006703 if (E == nullptr)
6704 return false;
6705 llvm::APSInt Result;
6706 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
6707 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
6708 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006709}
6710
Alexey Bataev5a3af132016-03-29 08:58:54 +00006711/// Build preinits statement for the given declarations.
6712static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00006713 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006714 if (!PreInits.empty()) {
6715 return new (Context) DeclStmt(
6716 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
6717 SourceLocation(), SourceLocation());
6718 }
6719 return nullptr;
6720}
6721
6722/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00006723static Stmt *
6724buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00006725 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006726 if (!Captures.empty()) {
6727 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00006728 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006729 PreInits.push_back(Pair.second->getDecl());
6730 return buildPreInits(Context, PreInits);
6731 }
6732 return nullptr;
6733}
6734
6735/// Build postupdate expression for the given list of postupdates expressions.
6736static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
6737 Expr *PostUpdate = nullptr;
6738 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006739 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006740 Expr *ConvE = S.BuildCStyleCastExpr(
6741 E->getExprLoc(),
6742 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
6743 E->getExprLoc(), E)
6744 .get();
6745 PostUpdate = PostUpdate
6746 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
6747 PostUpdate, ConvE)
6748 .get()
6749 : ConvE;
6750 }
6751 }
6752 return PostUpdate;
6753}
6754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006755/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00006756/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6757/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006758static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00006759checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00006760 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6761 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00006762 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00006763 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006764 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006765 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006766 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006767 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006768 if (!CollapseLoopCountExpr->isValueDependent() &&
6769 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006770 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006771 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006772 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006773 return 1;
6774 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00006775 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006776 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006777 if (OrderedLoopCountExpr) {
6778 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006779 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006780 if (!OrderedLoopCountExpr->isValueDependent() &&
6781 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6782 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006783 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006784 if (Result.getLimitedValue() < NestedLoopCount) {
6785 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6786 diag::err_omp_wrong_ordered_loop_count)
6787 << OrderedLoopCountExpr->getSourceRange();
6788 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6789 diag::note_collapse_loop_count)
6790 << CollapseLoopCountExpr->getSourceRange();
6791 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006792 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006793 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006794 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006795 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006796 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006797 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006798 // This is helper routine for loop directives (e.g., 'for', 'simd',
6799 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006800 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006801 SmallVector<LoopIterationSpace, 4> IterSpaces(
6802 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006803 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006804 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006805 if (checkOpenMPIterationSpace(
6806 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6807 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006808 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006809 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006810 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006811 // OpenMP [2.8.1, simd construct, Restrictions]
6812 // All loops associated with the construct must be perfectly nested; that
6813 // is, there must be no intervening code nor any OpenMP directive between
6814 // any two loops.
6815 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006816 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006817 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6818 if (checkOpenMPIterationSpace(
6819 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6820 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006821 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00006822 return 0;
6823 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6824 // Handle initialization of captured loop iterator variables.
6825 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6826 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6827 Captures[DRE] = DRE;
6828 }
6829 }
6830 // Move on to the next nested for loop, or to the loop body.
6831 // OpenMP [2.8.1, simd construct, Restrictions]
6832 // All loops associated with the construct must be perfectly nested; that
6833 // is, there must be no intervening code nor any OpenMP directive between
6834 // any two loops.
6835 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
6836 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006837
Alexander Musmana5f070a2014-10-01 06:03:56 +00006838 Built.clear(/* size */ NestedLoopCount);
6839
6840 if (SemaRef.CurContext->isDependentContext())
6841 return NestedLoopCount;
6842
6843 // An example of what is generated for the following code:
6844 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006845 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006846 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006847 // for (k = 0; k < NK; ++k)
6848 // for (j = J0; j < NJ; j+=2) {
6849 // <loop body>
6850 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006851 //
6852 // We generate the code below.
6853 // Note: the loop body may be outlined in CodeGen.
6854 // Note: some counters may be C++ classes, operator- is used to find number of
6855 // iterations and operator+= to calculate counter value.
6856 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
6857 // or i64 is currently supported).
6858 //
6859 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
6860 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
6861 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
6862 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
6863 // // similar updates for vars in clauses (e.g. 'linear')
6864 // <loop body (using local i and j)>
6865 // }
6866 // i = NI; // assign final values of counters
6867 // j = NJ;
6868 //
6869
6870 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
6871 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006872 // Precondition tests if there is at least one iteration (all conditions are
6873 // true).
6874 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00006875 Expr *N0 = IterSpaces[0].NumIterations;
6876 ExprResult LastIteration32 =
6877 widenIterationCount(/*Bits=*/32,
6878 SemaRef
6879 .PerformImplicitConversion(
6880 N0->IgnoreImpCasts(), N0->getType(),
6881 Sema::AA_Converting, /*AllowExplicit=*/true)
6882 .get(),
6883 SemaRef);
6884 ExprResult LastIteration64 = widenIterationCount(
6885 /*Bits=*/64,
6886 SemaRef
6887 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
6888 Sema::AA_Converting,
6889 /*AllowExplicit=*/true)
6890 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006891 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006892
6893 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
6894 return NestedLoopCount;
6895
Alexey Bataeve3727102018-04-18 15:57:46 +00006896 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006897 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
6898
6899 Scope *CurScope = DSA.getCurScope();
6900 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006901 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00006902 PreCond =
6903 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
6904 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00006905 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006906 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00006907 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006908 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
6909 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006910 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006911 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006912 SemaRef
6913 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6914 Sema::AA_Converting,
6915 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006916 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006917 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006918 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006919 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006920 SemaRef
6921 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6922 Sema::AA_Converting,
6923 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006924 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006925 }
6926
6927 // Choose either the 32-bit or 64-bit version.
6928 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006929 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
6930 (LastIteration32.isUsable() &&
6931 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
6932 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
6933 fitsInto(
6934 /*Bits=*/32,
6935 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
6936 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00006937 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00006938 QualType VType = LastIteration.get()->getType();
6939 QualType RealVType = VType;
6940 QualType StrideVType = VType;
6941 if (isOpenMPTaskLoopDirective(DKind)) {
6942 VType =
6943 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
6944 StrideVType =
6945 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6946 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006947
6948 if (!LastIteration.isUsable())
6949 return 0;
6950
6951 // Save the number of iterations.
6952 ExprResult NumIterations = LastIteration;
6953 {
6954 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006955 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
6956 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006957 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6958 if (!LastIteration.isUsable())
6959 return 0;
6960 }
6961
6962 // Calculate the last iteration number beforehand instead of doing this on
6963 // each iteration. Do not do this if the number of iterations may be kfold-ed.
6964 llvm::APSInt Result;
6965 bool IsConstant =
6966 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
6967 ExprResult CalcLastIteration;
6968 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006969 ExprResult SaveRef =
6970 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006971 LastIteration = SaveRef;
6972
6973 // Prepare SaveRef + 1.
6974 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006975 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006976 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6977 if (!NumIterations.isUsable())
6978 return 0;
6979 }
6980
6981 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
6982
David Majnemer9d168222016-08-05 17:44:54 +00006983 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006984 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006985 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6986 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006987 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006988 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
6989 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006990 SemaRef.AddInitializerToDecl(LBDecl,
6991 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6992 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006993
6994 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006995 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
6996 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00006997 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00006998 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006999
7000 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7001 // This will be used to implement clause 'lastprivate'.
7002 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007003 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7004 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007005 SemaRef.AddInitializerToDecl(ILDecl,
7006 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7007 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007008
7009 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007010 VarDecl *STDecl =
7011 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7012 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007013 SemaRef.AddInitializerToDecl(STDecl,
7014 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7015 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007016
7017 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007018 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007019 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7020 UB.get(), LastIteration.get());
7021 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007022 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7023 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007024 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7025 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007026 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007027
7028 // If we have a combined directive that combines 'distribute', 'for' or
7029 // 'simd' we need to be able to access the bounds of the schedule of the
7030 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7031 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7032 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007033 // Lower bound variable, initialized with zero.
7034 VarDecl *CombLBDecl =
7035 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7036 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7037 SemaRef.AddInitializerToDecl(
7038 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7039 /*DirectInit*/ false);
7040
7041 // Upper bound variable, initialized with last iteration number.
7042 VarDecl *CombUBDecl =
7043 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7044 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7045 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7046 /*DirectInit*/ false);
7047
7048 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7049 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7050 ExprResult CombCondOp =
7051 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7052 LastIteration.get(), CombUB.get());
7053 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7054 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007055 CombEUB =
7056 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007057
Alexey Bataeve3727102018-04-18 15:57:46 +00007058 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007059 // We expect to have at least 2 more parameters than the 'parallel'
7060 // directive does - the lower and upper bounds of the previous schedule.
7061 assert(CD->getNumParams() >= 4 &&
7062 "Unexpected number of parameters in loop combined directive");
7063
7064 // Set the proper type for the bounds given what we learned from the
7065 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007066 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7067 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007068
7069 // Previous lower and upper bounds are obtained from the region
7070 // parameters.
7071 PrevLB =
7072 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7073 PrevUB =
7074 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7075 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007076 }
7077
7078 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007079 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007080 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007081 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007082 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7083 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007084 Expr *RHS =
7085 (isOpenMPWorksharingDirective(DKind) ||
7086 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7087 ? LB.get()
7088 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007089 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007090 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007091
7092 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7093 Expr *CombRHS =
7094 (isOpenMPWorksharingDirective(DKind) ||
7095 isOpenMPTaskLoopDirective(DKind) ||
7096 isOpenMPDistributeDirective(DKind))
7097 ? CombLB.get()
7098 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7099 CombInit =
7100 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007101 CombInit =
7102 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007103 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007104 }
7105
Alexey Bataev316ccf62019-01-29 18:51:58 +00007106 bool UseStrictCompare =
7107 RealVType->hasUnsignedIntegerRepresentation() &&
7108 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7109 return LIS.IsStrictCompare;
7110 });
7111 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7112 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007113 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007114 Expr *BoundUB = UB.get();
7115 if (UseStrictCompare) {
7116 BoundUB =
7117 SemaRef
7118 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7119 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7120 .get();
7121 BoundUB =
7122 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7123 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007124 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007125 (isOpenMPWorksharingDirective(DKind) ||
7126 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007127 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7128 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7129 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007130 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7131 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007132 ExprResult CombDistCond;
7133 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007134 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7135 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007136 }
7137
Carlo Bertolliffafe102017-04-20 00:39:39 +00007138 ExprResult CombCond;
7139 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007140 Expr *BoundCombUB = CombUB.get();
7141 if (UseStrictCompare) {
7142 BoundCombUB =
7143 SemaRef
7144 .BuildBinOp(
7145 CurScope, CondLoc, BO_Add, BoundCombUB,
7146 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7147 .get();
7148 BoundCombUB =
7149 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7150 .get();
7151 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007152 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007153 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7154 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007155 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007156 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007157 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007158 ExprResult Inc =
7159 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7160 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7161 if (!Inc.isUsable())
7162 return 0;
7163 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007164 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007165 if (!Inc.isUsable())
7166 return 0;
7167
7168 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7169 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007170 // In combined construct, add combined version that use CombLB and CombUB
7171 // base variables for the update
7172 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007173 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7174 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007175 // LB + ST
7176 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7177 if (!NextLB.isUsable())
7178 return 0;
7179 // LB = LB + ST
7180 NextLB =
7181 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007182 NextLB =
7183 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007184 if (!NextLB.isUsable())
7185 return 0;
7186 // UB + ST
7187 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7188 if (!NextUB.isUsable())
7189 return 0;
7190 // UB = UB + ST
7191 NextUB =
7192 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007193 NextUB =
7194 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007195 if (!NextUB.isUsable())
7196 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007197 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7198 CombNextLB =
7199 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7200 if (!NextLB.isUsable())
7201 return 0;
7202 // LB = LB + ST
7203 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7204 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007205 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7206 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007207 if (!CombNextLB.isUsable())
7208 return 0;
7209 // UB + ST
7210 CombNextUB =
7211 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7212 if (!CombNextUB.isUsable())
7213 return 0;
7214 // UB = UB + ST
7215 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7216 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007217 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7218 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007219 if (!CombNextUB.isUsable())
7220 return 0;
7221 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007222 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007223
Carlo Bertolliffafe102017-04-20 00:39:39 +00007224 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007225 // directive with for as IV = IV + ST; ensure upper bound expression based
7226 // on PrevUB instead of NumIterations - used to implement 'for' when found
7227 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007228 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007229 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007230 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007231 DistCond = SemaRef.BuildBinOp(
7232 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007233 assert(DistCond.isUsable() && "distribute cond expr was not built");
7234
7235 DistInc =
7236 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7237 assert(DistInc.isUsable() && "distribute inc expr was not built");
7238 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7239 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007240 DistInc =
7241 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007242 assert(DistInc.isUsable() && "distribute inc expr was not built");
7243
7244 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7245 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007246 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007247 ExprResult IsUBGreater =
7248 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7249 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7250 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7251 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7252 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007253 PrevEUB =
7254 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007255
Alexey Bataev316ccf62019-01-29 18:51:58 +00007256 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7257 // parallel for is in combination with a distribute directive with
7258 // schedule(static, 1)
7259 Expr *BoundPrevUB = PrevUB.get();
7260 if (UseStrictCompare) {
7261 BoundPrevUB =
7262 SemaRef
7263 .BuildBinOp(
7264 CurScope, CondLoc, BO_Add, BoundPrevUB,
7265 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7266 .get();
7267 BoundPrevUB =
7268 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7269 .get();
7270 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007271 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007272 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7273 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007274 }
7275
Alexander Musmana5f070a2014-10-01 06:03:56 +00007276 // Build updates and final values of the loop counters.
7277 bool HasErrors = false;
7278 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007279 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007280 Built.Updates.resize(NestedLoopCount);
7281 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007282 Built.DependentCounters.resize(NestedLoopCount);
7283 Built.DependentInits.resize(NestedLoopCount);
7284 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007285 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007286 // We implement the following algorithm for obtaining the
7287 // original loop iteration variable values based on the
7288 // value of the collapsed loop iteration variable IV.
7289 //
7290 // Let n+1 be the number of collapsed loops in the nest.
7291 // Iteration variables (I0, I1, .... In)
7292 // Iteration counts (N0, N1, ... Nn)
7293 //
7294 // Acc = IV;
7295 //
7296 // To compute Ik for loop k, 0 <= k <= n, generate:
7297 // Prod = N(k+1) * N(k+2) * ... * Nn;
7298 // Ik = Acc / Prod;
7299 // Acc -= Ik * Prod;
7300 //
7301 ExprResult Acc = IV;
7302 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007303 LoopIterationSpace &IS = IterSpaces[Cnt];
7304 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007305 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007306
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007307 // Compute prod
7308 ExprResult Prod =
7309 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7310 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7311 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7312 IterSpaces[K].NumIterations);
7313
7314 // Iter = Acc / Prod
7315 // If there is at least one more inner loop to avoid
7316 // multiplication by 1.
7317 if (Cnt + 1 < NestedLoopCount)
7318 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7319 Acc.get(), Prod.get());
7320 else
7321 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007322 if (!Iter.isUsable()) {
7323 HasErrors = true;
7324 break;
7325 }
7326
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007327 // Update Acc:
7328 // Acc -= Iter * Prod
7329 // Check if there is at least one more inner loop to avoid
7330 // multiplication by 1.
7331 if (Cnt + 1 < NestedLoopCount)
7332 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7333 Iter.get(), Prod.get());
7334 else
7335 Prod = Iter;
7336 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7337 Acc.get(), Prod.get());
7338
Alexey Bataev39f915b82015-05-08 10:41:21 +00007339 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007340 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007341 DeclRefExpr *CounterVar = buildDeclRefExpr(
7342 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7343 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007344 ExprResult Init =
7345 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7346 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007347 if (!Init.isUsable()) {
7348 HasErrors = true;
7349 break;
7350 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007351 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007352 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007353 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007354 if (!Update.isUsable()) {
7355 HasErrors = true;
7356 break;
7357 }
7358
7359 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007360 ExprResult Final =
7361 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7362 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7363 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007364 if (!Final.isUsable()) {
7365 HasErrors = true;
7366 break;
7367 }
7368
Alexander Musmana5f070a2014-10-01 06:03:56 +00007369 if (!Update.isUsable() || !Final.isUsable()) {
7370 HasErrors = true;
7371 break;
7372 }
7373 // Save results
7374 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007375 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007376 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007377 Built.Updates[Cnt] = Update.get();
7378 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007379 Built.DependentCounters[Cnt] = nullptr;
7380 Built.DependentInits[Cnt] = nullptr;
7381 Built.FinalsConditions[Cnt] = nullptr;
7382 if (IS.IsNonRectangularLB) {
7383 Built.DependentCounters[Cnt] =
7384 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7385 Built.DependentInits[Cnt] =
7386 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7387 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7388 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007389 }
7390 }
7391
7392 if (HasErrors)
7393 return 0;
7394
7395 // Save results
7396 Built.IterationVarRef = IV.get();
7397 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007398 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007399 Built.CalcLastIteration = SemaRef
7400 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007401 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007402 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007403 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007404 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007405 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007406 Built.Init = Init.get();
7407 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007408 Built.LB = LB.get();
7409 Built.UB = UB.get();
7410 Built.IL = IL.get();
7411 Built.ST = ST.get();
7412 Built.EUB = EUB.get();
7413 Built.NLB = NextLB.get();
7414 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007415 Built.PrevLB = PrevLB.get();
7416 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007417 Built.DistInc = DistInc.get();
7418 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007419 Built.DistCombinedFields.LB = CombLB.get();
7420 Built.DistCombinedFields.UB = CombUB.get();
7421 Built.DistCombinedFields.EUB = CombEUB.get();
7422 Built.DistCombinedFields.Init = CombInit.get();
7423 Built.DistCombinedFields.Cond = CombCond.get();
7424 Built.DistCombinedFields.NLB = CombNextLB.get();
7425 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007426 Built.DistCombinedFields.DistCond = CombDistCond.get();
7427 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007428
Alexey Bataevabfc0692014-06-25 06:52:00 +00007429 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007430}
7431
Alexey Bataev10e775f2015-07-30 11:36:16 +00007432static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007433 auto CollapseClauses =
7434 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7435 if (CollapseClauses.begin() != CollapseClauses.end())
7436 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007437 return nullptr;
7438}
7439
Alexey Bataev10e775f2015-07-30 11:36:16 +00007440static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007441 auto OrderedClauses =
7442 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7443 if (OrderedClauses.begin() != OrderedClauses.end())
7444 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007445 return nullptr;
7446}
7447
Kelvin Lic5609492016-07-15 04:39:07 +00007448static bool checkSimdlenSafelenSpecified(Sema &S,
7449 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007450 const OMPSafelenClause *Safelen = nullptr;
7451 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007452
Alexey Bataeve3727102018-04-18 15:57:46 +00007453 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007454 if (Clause->getClauseKind() == OMPC_safelen)
7455 Safelen = cast<OMPSafelenClause>(Clause);
7456 else if (Clause->getClauseKind() == OMPC_simdlen)
7457 Simdlen = cast<OMPSimdlenClause>(Clause);
7458 if (Safelen && Simdlen)
7459 break;
7460 }
7461
7462 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007463 const Expr *SimdlenLength = Simdlen->getSimdlen();
7464 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007465 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7466 SimdlenLength->isInstantiationDependent() ||
7467 SimdlenLength->containsUnexpandedParameterPack())
7468 return false;
7469 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7470 SafelenLength->isInstantiationDependent() ||
7471 SafelenLength->containsUnexpandedParameterPack())
7472 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007473 Expr::EvalResult SimdlenResult, SafelenResult;
7474 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7475 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7476 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7477 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007478 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7479 // If both simdlen and safelen clauses are specified, the value of the
7480 // simdlen parameter must be less than or equal to the value of the safelen
7481 // parameter.
7482 if (SimdlenRes > SafelenRes) {
7483 S.Diag(SimdlenLength->getExprLoc(),
7484 diag::err_omp_wrong_simdlen_safelen_values)
7485 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7486 return true;
7487 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007488 }
7489 return false;
7490}
7491
Alexey Bataeve3727102018-04-18 15:57:46 +00007492StmtResult
7493Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7494 SourceLocation StartLoc, SourceLocation EndLoc,
7495 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007496 if (!AStmt)
7497 return StmtError();
7498
7499 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007500 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007501 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7502 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007503 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007504 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7505 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007506 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007507 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007508
Alexander Musmana5f070a2014-10-01 06:03:56 +00007509 assert((CurContext->isDependentContext() || B.builtAll()) &&
7510 "omp simd loop exprs were not built");
7511
Alexander Musman3276a272015-03-21 10:12:56 +00007512 if (!CurContext->isDependentContext()) {
7513 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007514 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007515 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007516 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007517 B.NumIterations, *this, CurScope,
7518 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007519 return StmtError();
7520 }
7521 }
7522
Kelvin Lic5609492016-07-15 04:39:07 +00007523 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007524 return StmtError();
7525
Reid Kleckner87a31802018-03-12 21:43:02 +00007526 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007527 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7528 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007529}
7530
Alexey Bataeve3727102018-04-18 15:57:46 +00007531StmtResult
7532Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7533 SourceLocation StartLoc, SourceLocation EndLoc,
7534 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007535 if (!AStmt)
7536 return StmtError();
7537
7538 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007539 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007540 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7541 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007542 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007543 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7544 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007545 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007546 return StmtError();
7547
Alexander Musmana5f070a2014-10-01 06:03:56 +00007548 assert((CurContext->isDependentContext() || B.builtAll()) &&
7549 "omp for loop exprs were not built");
7550
Alexey Bataev54acd402015-08-04 11:18:19 +00007551 if (!CurContext->isDependentContext()) {
7552 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007553 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007554 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007555 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007556 B.NumIterations, *this, CurScope,
7557 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007558 return StmtError();
7559 }
7560 }
7561
Reid Kleckner87a31802018-03-12 21:43:02 +00007562 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007563 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007564 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007565}
7566
Alexander Musmanf82886e2014-09-18 05:12:34 +00007567StmtResult Sema::ActOnOpenMPForSimdDirective(
7568 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007569 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007570 if (!AStmt)
7571 return StmtError();
7572
7573 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007574 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007575 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7576 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007577 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007578 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007579 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7580 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007581 if (NestedLoopCount == 0)
7582 return StmtError();
7583
Alexander Musmanc6388682014-12-15 07:07:06 +00007584 assert((CurContext->isDependentContext() || B.builtAll()) &&
7585 "omp for simd loop exprs were not built");
7586
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007587 if (!CurContext->isDependentContext()) {
7588 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007589 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007590 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007591 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007592 B.NumIterations, *this, CurScope,
7593 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007594 return StmtError();
7595 }
7596 }
7597
Kelvin Lic5609492016-07-15 04:39:07 +00007598 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007599 return StmtError();
7600
Reid Kleckner87a31802018-03-12 21:43:02 +00007601 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007602 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7603 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007604}
7605
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007606StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7607 Stmt *AStmt,
7608 SourceLocation StartLoc,
7609 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007610 if (!AStmt)
7611 return StmtError();
7612
7613 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007614 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007615 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007616 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007617 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007618 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007619 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007620 return StmtError();
7621 // All associated statements must be '#pragma omp section' except for
7622 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007623 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007624 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7625 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007626 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007627 diag::err_omp_sections_substmt_not_section);
7628 return StmtError();
7629 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007630 cast<OMPSectionDirective>(SectionStmt)
7631 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007632 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007633 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007634 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007635 return StmtError();
7636 }
7637
Reid Kleckner87a31802018-03-12 21:43:02 +00007638 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007639
Alexey Bataev25e5b442015-09-15 12:52:43 +00007640 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7641 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007642}
7643
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007644StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
7645 SourceLocation StartLoc,
7646 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007647 if (!AStmt)
7648 return StmtError();
7649
7650 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007651
Reid Kleckner87a31802018-03-12 21:43:02 +00007652 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00007653 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007654
Alexey Bataev25e5b442015-09-15 12:52:43 +00007655 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
7656 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007657}
7658
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007659StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7660 Stmt *AStmt,
7661 SourceLocation StartLoc,
7662 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007663 if (!AStmt)
7664 return StmtError();
7665
7666 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00007667
Reid Kleckner87a31802018-03-12 21:43:02 +00007668 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00007669
Alexey Bataev3255bf32015-01-19 05:20:46 +00007670 // OpenMP [2.7.3, single Construct, Restrictions]
7671 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00007672 const OMPClause *Nowait = nullptr;
7673 const OMPClause *Copyprivate = nullptr;
7674 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00007675 if (Clause->getClauseKind() == OMPC_nowait)
7676 Nowait = Clause;
7677 else if (Clause->getClauseKind() == OMPC_copyprivate)
7678 Copyprivate = Clause;
7679 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007680 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00007681 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007682 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00007683 return StmtError();
7684 }
7685 }
7686
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007687 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7688}
7689
Alexander Musman80c22892014-07-17 08:54:58 +00007690StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
7691 SourceLocation StartLoc,
7692 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007693 if (!AStmt)
7694 return StmtError();
7695
7696 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00007697
Reid Kleckner87a31802018-03-12 21:43:02 +00007698 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00007699
7700 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
7701}
7702
Alexey Bataev28c75412015-12-15 08:19:24 +00007703StmtResult Sema::ActOnOpenMPCriticalDirective(
7704 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
7705 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007706 if (!AStmt)
7707 return StmtError();
7708
7709 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007710
Alexey Bataev28c75412015-12-15 08:19:24 +00007711 bool ErrorFound = false;
7712 llvm::APSInt Hint;
7713 SourceLocation HintLoc;
7714 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007715 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007716 if (C->getClauseKind() == OMPC_hint) {
7717 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007718 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00007719 ErrorFound = true;
7720 }
7721 Expr *E = cast<OMPHintClause>(C)->getHint();
7722 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00007723 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007724 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007725 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00007726 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007727 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00007728 }
7729 }
7730 }
7731 if (ErrorFound)
7732 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007733 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00007734 if (Pair.first && DirName.getName() && !DependentHint) {
7735 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
7736 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00007737 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00007738 Diag(HintLoc, diag::note_omp_critical_hint_here)
7739 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007740 else
Alexey Bataev28c75412015-12-15 08:19:24 +00007741 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00007742 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007743 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00007744 << 1
7745 << C->getHint()->EvaluateKnownConstInt(Context).toString(
7746 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007747 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007748 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00007749 }
Alexey Bataev28c75412015-12-15 08:19:24 +00007750 }
7751 }
7752
Reid Kleckner87a31802018-03-12 21:43:02 +00007753 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007754
Alexey Bataev28c75412015-12-15 08:19:24 +00007755 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
7756 Clauses, AStmt);
7757 if (!Pair.first && DirName.getName() && !DependentHint)
7758 DSAStack->addCriticalWithHint(Dir, Hint);
7759 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007760}
7761
Alexey Bataev4acb8592014-07-07 13:01:15 +00007762StmtResult Sema::ActOnOpenMPParallelForDirective(
7763 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007764 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007765 if (!AStmt)
7766 return StmtError();
7767
Alexey Bataeve3727102018-04-18 15:57:46 +00007768 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007769 // 1.2.2 OpenMP Language Terminology
7770 // Structured block - An executable statement with a single entry at the
7771 // top and a single exit at the bottom.
7772 // The point of exit cannot be a branch out of the structured block.
7773 // longjmp() and throw() must not violate the entry/exit criteria.
7774 CS->getCapturedDecl()->setNothrow();
7775
Alexander Musmanc6388682014-12-15 07:07:06 +00007776 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007777 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7778 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007779 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007780 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007781 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7782 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007783 if (NestedLoopCount == 0)
7784 return StmtError();
7785
Alexander Musmana5f070a2014-10-01 06:03:56 +00007786 assert((CurContext->isDependentContext() || B.builtAll()) &&
7787 "omp parallel for loop exprs were not built");
7788
Alexey Bataev54acd402015-08-04 11:18:19 +00007789 if (!CurContext->isDependentContext()) {
7790 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007791 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007792 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007793 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007794 B.NumIterations, *this, CurScope,
7795 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007796 return StmtError();
7797 }
7798 }
7799
Reid Kleckner87a31802018-03-12 21:43:02 +00007800 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007801 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007802 NestedLoopCount, Clauses, AStmt, B,
7803 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00007804}
7805
Alexander Musmane4e893b2014-09-23 09:33:00 +00007806StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
7807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007809 if (!AStmt)
7810 return StmtError();
7811
Alexey Bataeve3727102018-04-18 15:57:46 +00007812 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007813 // 1.2.2 OpenMP Language Terminology
7814 // Structured block - An executable statement with a single entry at the
7815 // top and a single exit at the bottom.
7816 // The point of exit cannot be a branch out of the structured block.
7817 // longjmp() and throw() must not violate the entry/exit criteria.
7818 CS->getCapturedDecl()->setNothrow();
7819
Alexander Musmanc6388682014-12-15 07:07:06 +00007820 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007821 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7822 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007823 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007824 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007825 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7826 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007827 if (NestedLoopCount == 0)
7828 return StmtError();
7829
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007830 if (!CurContext->isDependentContext()) {
7831 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007832 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007833 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007834 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007835 B.NumIterations, *this, CurScope,
7836 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007837 return StmtError();
7838 }
7839 }
7840
Kelvin Lic5609492016-07-15 04:39:07 +00007841 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007842 return StmtError();
7843
Reid Kleckner87a31802018-03-12 21:43:02 +00007844 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007845 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007846 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007847}
7848
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007849StmtResult
7850Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7851 Stmt *AStmt, SourceLocation StartLoc,
7852 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007853 if (!AStmt)
7854 return StmtError();
7855
7856 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007857 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007858 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007859 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007860 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007861 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007862 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007863 return StmtError();
7864 // All associated statements must be '#pragma omp section' except for
7865 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007866 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007867 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7868 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007869 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007870 diag::err_omp_parallel_sections_substmt_not_section);
7871 return StmtError();
7872 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007873 cast<OMPSectionDirective>(SectionStmt)
7874 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007875 }
7876 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007877 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007878 diag::err_omp_parallel_sections_not_compound_stmt);
7879 return StmtError();
7880 }
7881
Reid Kleckner87a31802018-03-12 21:43:02 +00007882 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007883
Alexey Bataev25e5b442015-09-15 12:52:43 +00007884 return OMPParallelSectionsDirective::Create(
7885 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007886}
7887
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007888StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7889 Stmt *AStmt, SourceLocation StartLoc,
7890 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007891 if (!AStmt)
7892 return StmtError();
7893
David Majnemer9d168222016-08-05 17:44:54 +00007894 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007895 // 1.2.2 OpenMP Language Terminology
7896 // Structured block - An executable statement with a single entry at the
7897 // top and a single exit at the bottom.
7898 // The point of exit cannot be a branch out of the structured block.
7899 // longjmp() and throw() must not violate the entry/exit criteria.
7900 CS->getCapturedDecl()->setNothrow();
7901
Reid Kleckner87a31802018-03-12 21:43:02 +00007902 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007903
Alexey Bataev25e5b442015-09-15 12:52:43 +00007904 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7905 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007906}
7907
Alexey Bataev68446b72014-07-18 07:47:19 +00007908StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7909 SourceLocation EndLoc) {
7910 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
7911}
7912
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00007913StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7914 SourceLocation EndLoc) {
7915 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
7916}
7917
Alexey Bataev2df347a2014-07-18 10:17:07 +00007918StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7919 SourceLocation EndLoc) {
7920 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
7921}
7922
Alexey Bataev169d96a2017-07-18 20:17:46 +00007923StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
7924 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007925 SourceLocation StartLoc,
7926 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007927 if (!AStmt)
7928 return StmtError();
7929
7930 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007931
Reid Kleckner87a31802018-03-12 21:43:02 +00007932 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007933
Alexey Bataev169d96a2017-07-18 20:17:46 +00007934 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00007935 AStmt,
7936 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007937}
7938
Alexey Bataev6125da92014-07-21 11:26:11 +00007939StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7940 SourceLocation StartLoc,
7941 SourceLocation EndLoc) {
7942 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
7943 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
7944}
7945
Alexey Bataev346265e2015-09-25 10:37:12 +00007946StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7947 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007948 SourceLocation StartLoc,
7949 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007950 const OMPClause *DependFound = nullptr;
7951 const OMPClause *DependSourceClause = nullptr;
7952 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00007953 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007954 const OMPThreadsClause *TC = nullptr;
7955 const OMPSIMDClause *SC = nullptr;
7956 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00007957 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
7958 DependFound = C;
7959 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
7960 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007961 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00007962 << getOpenMPDirectiveName(OMPD_ordered)
7963 << getOpenMPClauseName(OMPC_depend) << 2;
7964 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007965 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00007966 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00007967 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007968 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007969 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007970 << 0;
7971 ErrorFound = true;
7972 }
7973 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
7974 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007975 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007976 << 1;
7977 ErrorFound = true;
7978 }
7979 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00007980 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00007982 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007983 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007984 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007985 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007986 }
Alexey Bataeveb482352015-12-18 05:05:56 +00007987 if (!ErrorFound && !SC &&
7988 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007989 // OpenMP [2.8.1,simd Construct, Restrictions]
7990 // An ordered construct with the simd clause is the only OpenMP construct
7991 // that can appear in the simd region.
7992 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00007993 ErrorFound = true;
7994 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007995 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00007996 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
7997 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007998 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007999 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008000 diag::err_omp_ordered_directive_without_param);
8001 ErrorFound = true;
8002 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008003 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008004 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008005 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8006 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008007 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008008 ErrorFound = true;
8009 }
8010 }
8011 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008012 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008013
8014 if (AStmt) {
8015 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8016
Reid Kleckner87a31802018-03-12 21:43:02 +00008017 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008018 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008019
8020 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008021}
8022
Alexey Bataev1d160b12015-03-13 12:27:31 +00008023namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008024/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008025/// construct.
8026class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008027 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008028 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008029 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008030 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008031 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008032 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008033 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008034 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008035 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008036 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008037 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008038 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008039 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008040 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008041 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008042 /// expression.
8043 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008044 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008045 /// part.
8046 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008047 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008048 NoError
8049 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008050 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008051 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008052 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008053 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008054 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008055 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008056 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008057 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008058 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008059 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8060 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8061 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008062 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008063 /// important for non-associative operations.
8064 bool IsXLHSInRHSPart;
8065 BinaryOperatorKind Op;
8066 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008067 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008068 /// if it is a prefix unary operation.
8069 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008070
8071public:
8072 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008073 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008074 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008075 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008076 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008077 /// expression. If DiagId and NoteId == 0, then only check is performed
8078 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008079 /// \param DiagId Diagnostic which should be emitted if error is found.
8080 /// \param NoteId Diagnostic note for the main error message.
8081 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008082 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008083 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008084 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008085 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008086 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008087 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008088 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8089 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8090 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008091 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008092 /// false otherwise.
8093 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8094
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008095 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008096 /// if it is a prefix unary operation.
8097 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8098
Alexey Bataev1d160b12015-03-13 12:27:31 +00008099private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008100 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8101 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008102};
8103} // namespace
8104
8105bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8106 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8107 ExprAnalysisErrorCode ErrorFound = NoError;
8108 SourceLocation ErrorLoc, NoteLoc;
8109 SourceRange ErrorRange, NoteRange;
8110 // Allowed constructs are:
8111 // x = x binop expr;
8112 // x = expr binop x;
8113 if (AtomicBinOp->getOpcode() == BO_Assign) {
8114 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008115 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008116 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8117 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8118 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8119 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008120 Op = AtomicInnerBinOp->getOpcode();
8121 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008122 Expr *LHS = AtomicInnerBinOp->getLHS();
8123 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008124 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8125 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8126 /*Canonical=*/true);
8127 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8128 /*Canonical=*/true);
8129 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8130 /*Canonical=*/true);
8131 if (XId == LHSId) {
8132 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008133 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008134 } else if (XId == RHSId) {
8135 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008136 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008137 } else {
8138 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8139 ErrorRange = AtomicInnerBinOp->getSourceRange();
8140 NoteLoc = X->getExprLoc();
8141 NoteRange = X->getSourceRange();
8142 ErrorFound = NotAnUpdateExpression;
8143 }
8144 } else {
8145 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8146 ErrorRange = AtomicInnerBinOp->getSourceRange();
8147 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8148 NoteRange = SourceRange(NoteLoc, NoteLoc);
8149 ErrorFound = NotABinaryOperator;
8150 }
8151 } else {
8152 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8153 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8154 ErrorFound = NotABinaryExpression;
8155 }
8156 } else {
8157 ErrorLoc = AtomicBinOp->getExprLoc();
8158 ErrorRange = AtomicBinOp->getSourceRange();
8159 NoteLoc = AtomicBinOp->getOperatorLoc();
8160 NoteRange = SourceRange(NoteLoc, NoteLoc);
8161 ErrorFound = NotAnAssignmentOp;
8162 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008163 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008164 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8165 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8166 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008167 }
8168 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008169 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008170 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008171}
8172
8173bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8174 unsigned NoteId) {
8175 ExprAnalysisErrorCode ErrorFound = NoError;
8176 SourceLocation ErrorLoc, NoteLoc;
8177 SourceRange ErrorRange, NoteRange;
8178 // Allowed constructs are:
8179 // x++;
8180 // x--;
8181 // ++x;
8182 // --x;
8183 // x binop= expr;
8184 // x = x binop expr;
8185 // x = expr binop x;
8186 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8187 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8188 if (AtomicBody->getType()->isScalarType() ||
8189 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008190 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008191 AtomicBody->IgnoreParenImpCasts())) {
8192 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008193 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008194 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008195 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008196 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008197 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008198 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008199 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8200 AtomicBody->IgnoreParenImpCasts())) {
8201 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008202 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008203 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008204 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008205 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008206 // Check for Unary Operation
8207 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008208 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008209 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8210 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008211 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008212 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8213 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008214 } else {
8215 ErrorFound = NotAnUnaryIncDecExpression;
8216 ErrorLoc = AtomicUnaryOp->getExprLoc();
8217 ErrorRange = AtomicUnaryOp->getSourceRange();
8218 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8219 NoteRange = SourceRange(NoteLoc, NoteLoc);
8220 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008221 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008222 ErrorFound = NotABinaryOrUnaryExpression;
8223 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8224 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8225 }
8226 } else {
8227 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008228 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008229 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8230 }
8231 } else {
8232 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008233 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008234 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8235 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008236 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008237 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8238 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8239 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008240 }
8241 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008242 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008243 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008244 // Build an update expression of form 'OpaqueValueExpr(x) binop
8245 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8246 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8247 auto *OVEX = new (SemaRef.getASTContext())
8248 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8249 auto *OVEExpr = new (SemaRef.getASTContext())
8250 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008251 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008252 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8253 IsXLHSInRHSPart ? OVEExpr : OVEX);
8254 if (Update.isInvalid())
8255 return true;
8256 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8257 Sema::AA_Casting);
8258 if (Update.isInvalid())
8259 return true;
8260 UpdateExpr = Update.get();
8261 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008262 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008263}
8264
Alexey Bataev0162e452014-07-22 10:10:35 +00008265StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8266 Stmt *AStmt,
8267 SourceLocation StartLoc,
8268 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008269 if (!AStmt)
8270 return StmtError();
8271
David Majnemer9d168222016-08-05 17:44:54 +00008272 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008273 // 1.2.2 OpenMP Language Terminology
8274 // Structured block - An executable statement with a single entry at the
8275 // top and a single exit at the bottom.
8276 // The point of exit cannot be a branch out of the structured block.
8277 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008278 OpenMPClauseKind AtomicKind = OMPC_unknown;
8279 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008280 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008281 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008282 C->getClauseKind() == OMPC_update ||
8283 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008284 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008285 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008286 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008287 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8288 << getOpenMPClauseName(AtomicKind);
8289 } else {
8290 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008291 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008292 }
8293 }
8294 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008295
Alexey Bataeve3727102018-04-18 15:57:46 +00008296 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008297 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8298 Body = EWC->getSubExpr();
8299
Alexey Bataev62cec442014-11-18 10:14:22 +00008300 Expr *X = nullptr;
8301 Expr *V = nullptr;
8302 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008303 Expr *UE = nullptr;
8304 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008305 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008306 // OpenMP [2.12.6, atomic Construct]
8307 // In the next expressions:
8308 // * x and v (as applicable) are both l-value expressions with scalar type.
8309 // * During the execution of an atomic region, multiple syntactic
8310 // occurrences of x must designate the same storage location.
8311 // * Neither of v and expr (as applicable) may access the storage location
8312 // designated by x.
8313 // * Neither of x and expr (as applicable) may access the storage location
8314 // designated by v.
8315 // * expr is an expression with scalar type.
8316 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8317 // * binop, binop=, ++, and -- are not overloaded operators.
8318 // * The expression x binop expr must be numerically equivalent to x binop
8319 // (expr). This requirement is satisfied if the operators in expr have
8320 // precedence greater than binop, or by using parentheses around expr or
8321 // subexpressions of expr.
8322 // * The expression expr binop x must be numerically equivalent to (expr)
8323 // binop x. This requirement is satisfied if the operators in expr have
8324 // precedence equal to or greater than binop, or by using parentheses around
8325 // expr or subexpressions of expr.
8326 // * For forms that allow multiple occurrences of x, the number of times
8327 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008328 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008329 enum {
8330 NotAnExpression,
8331 NotAnAssignmentOp,
8332 NotAScalarType,
8333 NotAnLValue,
8334 NoError
8335 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008336 SourceLocation ErrorLoc, NoteLoc;
8337 SourceRange ErrorRange, NoteRange;
8338 // If clause is read:
8339 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008340 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8341 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008342 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8343 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8344 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8345 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8346 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8347 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8348 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008349 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008350 ErrorFound = NotAnLValue;
8351 ErrorLoc = AtomicBinOp->getExprLoc();
8352 ErrorRange = AtomicBinOp->getSourceRange();
8353 NoteLoc = NotLValueExpr->getExprLoc();
8354 NoteRange = NotLValueExpr->getSourceRange();
8355 }
8356 } else if (!X->isInstantiationDependent() ||
8357 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008358 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008359 (X->isInstantiationDependent() || X->getType()->isScalarType())
8360 ? V
8361 : X;
8362 ErrorFound = NotAScalarType;
8363 ErrorLoc = AtomicBinOp->getExprLoc();
8364 ErrorRange = AtomicBinOp->getSourceRange();
8365 NoteLoc = NotScalarExpr->getExprLoc();
8366 NoteRange = NotScalarExpr->getSourceRange();
8367 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008368 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008369 ErrorFound = NotAnAssignmentOp;
8370 ErrorLoc = AtomicBody->getExprLoc();
8371 ErrorRange = AtomicBody->getSourceRange();
8372 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8373 : AtomicBody->getExprLoc();
8374 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8375 : AtomicBody->getSourceRange();
8376 }
8377 } else {
8378 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008379 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008380 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008381 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008382 if (ErrorFound != NoError) {
8383 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8384 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008385 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8386 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008387 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008388 }
8389 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008390 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008391 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008392 enum {
8393 NotAnExpression,
8394 NotAnAssignmentOp,
8395 NotAScalarType,
8396 NotAnLValue,
8397 NoError
8398 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008399 SourceLocation ErrorLoc, NoteLoc;
8400 SourceRange ErrorRange, NoteRange;
8401 // If clause is write:
8402 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008403 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8404 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008405 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8406 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008407 X = AtomicBinOp->getLHS();
8408 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008409 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8410 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8411 if (!X->isLValue()) {
8412 ErrorFound = NotAnLValue;
8413 ErrorLoc = AtomicBinOp->getExprLoc();
8414 ErrorRange = AtomicBinOp->getSourceRange();
8415 NoteLoc = X->getExprLoc();
8416 NoteRange = X->getSourceRange();
8417 }
8418 } else if (!X->isInstantiationDependent() ||
8419 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008420 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008421 (X->isInstantiationDependent() || X->getType()->isScalarType())
8422 ? E
8423 : X;
8424 ErrorFound = NotAScalarType;
8425 ErrorLoc = AtomicBinOp->getExprLoc();
8426 ErrorRange = AtomicBinOp->getSourceRange();
8427 NoteLoc = NotScalarExpr->getExprLoc();
8428 NoteRange = NotScalarExpr->getSourceRange();
8429 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008430 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008431 ErrorFound = NotAnAssignmentOp;
8432 ErrorLoc = AtomicBody->getExprLoc();
8433 ErrorRange = AtomicBody->getSourceRange();
8434 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8435 : AtomicBody->getExprLoc();
8436 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8437 : AtomicBody->getSourceRange();
8438 }
8439 } else {
8440 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008441 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008442 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008443 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008444 if (ErrorFound != NoError) {
8445 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8446 << ErrorRange;
8447 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8448 << NoteRange;
8449 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008450 }
8451 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008452 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008453 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008454 // If clause is update:
8455 // x++;
8456 // x--;
8457 // ++x;
8458 // --x;
8459 // x binop= expr;
8460 // x = x binop expr;
8461 // x = expr binop x;
8462 OpenMPAtomicUpdateChecker Checker(*this);
8463 if (Checker.checkStatement(
8464 Body, (AtomicKind == OMPC_update)
8465 ? diag::err_omp_atomic_update_not_expression_statement
8466 : diag::err_omp_atomic_not_expression_statement,
8467 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008468 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008469 if (!CurContext->isDependentContext()) {
8470 E = Checker.getExpr();
8471 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008472 UE = Checker.getUpdateExpr();
8473 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008474 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008475 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008476 enum {
8477 NotAnAssignmentOp,
8478 NotACompoundStatement,
8479 NotTwoSubstatements,
8480 NotASpecificExpression,
8481 NoError
8482 } ErrorFound = NoError;
8483 SourceLocation ErrorLoc, NoteLoc;
8484 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008485 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008486 // If clause is a capture:
8487 // v = x++;
8488 // v = x--;
8489 // v = ++x;
8490 // v = --x;
8491 // v = x binop= expr;
8492 // v = x = x binop expr;
8493 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008494 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008495 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8496 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8497 V = AtomicBinOp->getLHS();
8498 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8499 OpenMPAtomicUpdateChecker Checker(*this);
8500 if (Checker.checkStatement(
8501 Body, diag::err_omp_atomic_capture_not_expression_statement,
8502 diag::note_omp_atomic_update))
8503 return StmtError();
8504 E = Checker.getExpr();
8505 X = Checker.getX();
8506 UE = Checker.getUpdateExpr();
8507 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8508 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008509 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008510 ErrorLoc = AtomicBody->getExprLoc();
8511 ErrorRange = AtomicBody->getSourceRange();
8512 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8513 : AtomicBody->getExprLoc();
8514 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8515 : AtomicBody->getSourceRange();
8516 ErrorFound = NotAnAssignmentOp;
8517 }
8518 if (ErrorFound != NoError) {
8519 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8520 << ErrorRange;
8521 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8522 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008523 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008524 if (CurContext->isDependentContext())
8525 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008526 } else {
8527 // If clause is a capture:
8528 // { v = x; x = expr; }
8529 // { v = x; x++; }
8530 // { v = x; x--; }
8531 // { v = x; ++x; }
8532 // { v = x; --x; }
8533 // { v = x; x binop= expr; }
8534 // { v = x; x = x binop expr; }
8535 // { v = x; x = expr binop x; }
8536 // { x++; v = x; }
8537 // { x--; v = x; }
8538 // { ++x; v = x; }
8539 // { --x; v = x; }
8540 // { x binop= expr; v = x; }
8541 // { x = x binop expr; v = x; }
8542 // { x = expr binop x; v = x; }
8543 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8544 // Check that this is { expr1; expr2; }
8545 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008546 Stmt *First = CS->body_front();
8547 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008548 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8549 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8550 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8551 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8552 // Need to find what subexpression is 'v' and what is 'x'.
8553 OpenMPAtomicUpdateChecker Checker(*this);
8554 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8555 BinaryOperator *BinOp = nullptr;
8556 if (IsUpdateExprFound) {
8557 BinOp = dyn_cast<BinaryOperator>(First);
8558 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8559 }
8560 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8561 // { v = x; x++; }
8562 // { v = x; x--; }
8563 // { v = x; ++x; }
8564 // { v = x; --x; }
8565 // { v = x; x binop= expr; }
8566 // { v = x; x = x binop expr; }
8567 // { v = x; x = expr binop x; }
8568 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008569 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008570 llvm::FoldingSetNodeID XId, PossibleXId;
8571 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8572 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8573 IsUpdateExprFound = XId == PossibleXId;
8574 if (IsUpdateExprFound) {
8575 V = BinOp->getLHS();
8576 X = Checker.getX();
8577 E = Checker.getExpr();
8578 UE = Checker.getUpdateExpr();
8579 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008580 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008581 }
8582 }
8583 if (!IsUpdateExprFound) {
8584 IsUpdateExprFound = !Checker.checkStatement(First);
8585 BinOp = nullptr;
8586 if (IsUpdateExprFound) {
8587 BinOp = dyn_cast<BinaryOperator>(Second);
8588 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8589 }
8590 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8591 // { x++; v = x; }
8592 // { x--; v = x; }
8593 // { ++x; v = x; }
8594 // { --x; v = x; }
8595 // { x binop= expr; v = x; }
8596 // { x = x binop expr; v = x; }
8597 // { x = expr binop x; v = x; }
8598 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008599 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008600 llvm::FoldingSetNodeID XId, PossibleXId;
8601 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8602 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8603 IsUpdateExprFound = XId == PossibleXId;
8604 if (IsUpdateExprFound) {
8605 V = BinOp->getLHS();
8606 X = Checker.getX();
8607 E = Checker.getExpr();
8608 UE = Checker.getUpdateExpr();
8609 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008610 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008611 }
8612 }
8613 }
8614 if (!IsUpdateExprFound) {
8615 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00008616 auto *FirstExpr = dyn_cast<Expr>(First);
8617 auto *SecondExpr = dyn_cast<Expr>(Second);
8618 if (!FirstExpr || !SecondExpr ||
8619 !(FirstExpr->isInstantiationDependent() ||
8620 SecondExpr->isInstantiationDependent())) {
8621 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
8622 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008623 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00008624 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008625 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008626 NoteRange = ErrorRange = FirstBinOp
8627 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00008628 : SourceRange(ErrorLoc, ErrorLoc);
8629 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00008630 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
8631 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
8632 ErrorFound = NotAnAssignmentOp;
8633 NoteLoc = ErrorLoc = SecondBinOp
8634 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008635 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008636 NoteRange = ErrorRange =
8637 SecondBinOp ? SecondBinOp->getSourceRange()
8638 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00008639 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008640 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00008641 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00008642 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00008643 SecondBinOp->getLHS()->IgnoreParenImpCasts();
8644 llvm::FoldingSetNodeID X1Id, X2Id;
8645 PossibleXRHSInFirst->Profile(X1Id, Context,
8646 /*Canonical=*/true);
8647 PossibleXLHSInSecond->Profile(X2Id, Context,
8648 /*Canonical=*/true);
8649 IsUpdateExprFound = X1Id == X2Id;
8650 if (IsUpdateExprFound) {
8651 V = FirstBinOp->getLHS();
8652 X = SecondBinOp->getLHS();
8653 E = SecondBinOp->getRHS();
8654 UE = nullptr;
8655 IsXLHSInRHSPart = false;
8656 IsPostfixUpdate = true;
8657 } else {
8658 ErrorFound = NotASpecificExpression;
8659 ErrorLoc = FirstBinOp->getExprLoc();
8660 ErrorRange = FirstBinOp->getSourceRange();
8661 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
8662 NoteRange = SecondBinOp->getRHS()->getSourceRange();
8663 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008664 }
8665 }
8666 }
8667 }
8668 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008669 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008670 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008671 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008672 ErrorFound = NotTwoSubstatements;
8673 }
8674 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008675 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008676 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008677 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008678 ErrorFound = NotACompoundStatement;
8679 }
8680 if (ErrorFound != NoError) {
8681 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
8682 << ErrorRange;
8683 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8684 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008685 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008686 if (CurContext->isDependentContext())
8687 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00008688 }
Alexey Bataevdea47612014-07-23 07:46:59 +00008689 }
Alexey Bataev0162e452014-07-22 10:10:35 +00008690
Reid Kleckner87a31802018-03-12 21:43:02 +00008691 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00008692
Alexey Bataev62cec442014-11-18 10:14:22 +00008693 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00008694 X, V, E, UE, IsXLHSInRHSPart,
8695 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00008696}
8697
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008698StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8699 Stmt *AStmt,
8700 SourceLocation StartLoc,
8701 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008702 if (!AStmt)
8703 return StmtError();
8704
Alexey Bataeve3727102018-04-18 15:57:46 +00008705 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00008706 // 1.2.2 OpenMP Language Terminology
8707 // Structured block - An executable statement with a single entry at the
8708 // top and a single exit at the bottom.
8709 // The point of exit cannot be a branch out of the structured block.
8710 // longjmp() and throw() must not violate the entry/exit criteria.
8711 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008712 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
8713 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8714 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8715 // 1.2.2 OpenMP Language Terminology
8716 // Structured block - An executable statement with a single entry at the
8717 // top and a single exit at the bottom.
8718 // The point of exit cannot be a branch out of the structured block.
8719 // longjmp() and throw() must not violate the entry/exit criteria.
8720 CS->getCapturedDecl()->setNothrow();
8721 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008722
Alexey Bataev13314bf2014-10-09 04:18:56 +00008723 // OpenMP [2.16, Nesting of Regions]
8724 // If specified, a teams construct must be contained within a target
8725 // construct. That target construct must contain no statements or directives
8726 // outside of the teams construct.
8727 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008728 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008729 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008730 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00008731 auto I = CS->body_begin();
8732 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008733 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00008734 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
8735 OMPTeamsFound) {
8736
Alexey Bataev13314bf2014-10-09 04:18:56 +00008737 OMPTeamsFound = false;
8738 break;
8739 }
8740 ++I;
8741 }
8742 assert(I != CS->body_end() && "Not found statement");
8743 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00008744 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008745 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00008746 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00008747 }
8748 if (!OMPTeamsFound) {
8749 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
8750 Diag(DSAStack->getInnerTeamsRegionLoc(),
8751 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008752 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00008753 << isa<OMPExecutableDirective>(S);
8754 return StmtError();
8755 }
8756 }
8757
Reid Kleckner87a31802018-03-12 21:43:02 +00008758 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008759
8760 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8761}
8762
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008763StmtResult
8764Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8765 Stmt *AStmt, SourceLocation StartLoc,
8766 SourceLocation EndLoc) {
8767 if (!AStmt)
8768 return StmtError();
8769
Alexey Bataeve3727102018-04-18 15:57:46 +00008770 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008771 // 1.2.2 OpenMP Language Terminology
8772 // Structured block - An executable statement with a single entry at the
8773 // top and a single exit at the bottom.
8774 // The point of exit cannot be a branch out of the structured block.
8775 // longjmp() and throw() must not violate the entry/exit criteria.
8776 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008777 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8778 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8779 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8780 // 1.2.2 OpenMP Language Terminology
8781 // Structured block - An executable statement with a single entry at the
8782 // top and a single exit at the bottom.
8783 // The point of exit cannot be a branch out of the structured block.
8784 // longjmp() and throw() must not violate the entry/exit criteria.
8785 CS->getCapturedDecl()->setNothrow();
8786 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008787
Reid Kleckner87a31802018-03-12 21:43:02 +00008788 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008789
8790 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8791 AStmt);
8792}
8793
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008794StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
8795 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008796 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008797 if (!AStmt)
8798 return StmtError();
8799
Alexey Bataeve3727102018-04-18 15:57:46 +00008800 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008801 // 1.2.2 OpenMP Language Terminology
8802 // Structured block - An executable statement with a single entry at the
8803 // top and a single exit at the bottom.
8804 // The point of exit cannot be a branch out of the structured block.
8805 // longjmp() and throw() must not violate the entry/exit criteria.
8806 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008807 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8808 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8809 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8810 // 1.2.2 OpenMP Language Terminology
8811 // Structured block - An executable statement with a single entry at the
8812 // top and a single exit at the bottom.
8813 // The point of exit cannot be a branch out of the structured block.
8814 // longjmp() and throw() must not violate the entry/exit criteria.
8815 CS->getCapturedDecl()->setNothrow();
8816 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008817
8818 OMPLoopDirective::HelperExprs B;
8819 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8820 // define the nested loops number.
8821 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008822 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008823 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008824 VarsWithImplicitDSA, B);
8825 if (NestedLoopCount == 0)
8826 return StmtError();
8827
8828 assert((CurContext->isDependentContext() || B.builtAll()) &&
8829 "omp target parallel for loop exprs were not built");
8830
8831 if (!CurContext->isDependentContext()) {
8832 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008833 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008834 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008835 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008836 B.NumIterations, *this, CurScope,
8837 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008838 return StmtError();
8839 }
8840 }
8841
Reid Kleckner87a31802018-03-12 21:43:02 +00008842 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008843 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8844 NestedLoopCount, Clauses, AStmt,
8845 B, DSAStack->isCancelRegion());
8846}
8847
Alexey Bataev95b64a92017-05-30 16:00:04 +00008848/// Check for existence of a map clause in the list of clauses.
8849static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8850 const OpenMPClauseKind K) {
8851 return llvm::any_of(
8852 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8853}
Samuel Antaodf67fc42016-01-19 19:15:56 +00008854
Alexey Bataev95b64a92017-05-30 16:00:04 +00008855template <typename... Params>
8856static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
8857 const Params... ClauseTypes) {
8858 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008859}
8860
Michael Wong65f367f2015-07-21 13:44:28 +00008861StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8862 Stmt *AStmt,
8863 SourceLocation StartLoc,
8864 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008865 if (!AStmt)
8866 return StmtError();
8867
8868 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8869
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008870 // OpenMP [2.10.1, Restrictions, p. 97]
8871 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008872 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
8873 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8874 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00008875 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008876 return StmtError();
8877 }
8878
Reid Kleckner87a31802018-03-12 21:43:02 +00008879 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00008880
8881 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8882 AStmt);
8883}
8884
Samuel Antaodf67fc42016-01-19 19:15:56 +00008885StmtResult
8886Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8887 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008888 SourceLocation EndLoc, Stmt *AStmt) {
8889 if (!AStmt)
8890 return StmtError();
8891
Alexey Bataeve3727102018-04-18 15:57:46 +00008892 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008893 // 1.2.2 OpenMP Language Terminology
8894 // Structured block - An executable statement with a single entry at the
8895 // top and a single exit at the bottom.
8896 // The point of exit cannot be a branch out of the structured block.
8897 // longjmp() and throw() must not violate the entry/exit criteria.
8898 CS->getCapturedDecl()->setNothrow();
8899 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
8900 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8901 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8902 // 1.2.2 OpenMP Language Terminology
8903 // Structured block - An executable statement with a single entry at the
8904 // top and a single exit at the bottom.
8905 // The point of exit cannot be a branch out of the structured block.
8906 // longjmp() and throw() must not violate the entry/exit criteria.
8907 CS->getCapturedDecl()->setNothrow();
8908 }
8909
Samuel Antaodf67fc42016-01-19 19:15:56 +00008910 // OpenMP [2.10.2, Restrictions, p. 99]
8911 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008912 if (!hasClauses(Clauses, OMPC_map)) {
8913 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8914 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008915 return StmtError();
8916 }
8917
Alexey Bataev7828b252017-11-21 17:08:48 +00008918 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8919 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008920}
8921
Samuel Antao72590762016-01-19 20:04:50 +00008922StmtResult
8923Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8924 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008925 SourceLocation EndLoc, Stmt *AStmt) {
8926 if (!AStmt)
8927 return StmtError();
8928
Alexey Bataeve3727102018-04-18 15:57:46 +00008929 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008930 // 1.2.2 OpenMP Language Terminology
8931 // Structured block - An executable statement with a single entry at the
8932 // top and a single exit at the bottom.
8933 // The point of exit cannot be a branch out of the structured block.
8934 // longjmp() and throw() must not violate the entry/exit criteria.
8935 CS->getCapturedDecl()->setNothrow();
8936 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
8937 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8938 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8939 // 1.2.2 OpenMP Language Terminology
8940 // Structured block - An executable statement with a single entry at the
8941 // top and a single exit at the bottom.
8942 // The point of exit cannot be a branch out of the structured block.
8943 // longjmp() and throw() must not violate the entry/exit criteria.
8944 CS->getCapturedDecl()->setNothrow();
8945 }
8946
Samuel Antao72590762016-01-19 20:04:50 +00008947 // OpenMP [2.10.3, Restrictions, p. 102]
8948 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008949 if (!hasClauses(Clauses, OMPC_map)) {
8950 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8951 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00008952 return StmtError();
8953 }
8954
Alexey Bataev7828b252017-11-21 17:08:48 +00008955 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8956 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00008957}
8958
Samuel Antao686c70c2016-05-26 17:30:50 +00008959StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8960 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008961 SourceLocation EndLoc,
8962 Stmt *AStmt) {
8963 if (!AStmt)
8964 return StmtError();
8965
Alexey Bataeve3727102018-04-18 15:57:46 +00008966 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008967 // 1.2.2 OpenMP Language Terminology
8968 // Structured block - An executable statement with a single entry at the
8969 // top and a single exit at the bottom.
8970 // The point of exit cannot be a branch out of the structured block.
8971 // longjmp() and throw() must not violate the entry/exit criteria.
8972 CS->getCapturedDecl()->setNothrow();
8973 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
8974 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8975 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8976 // 1.2.2 OpenMP Language Terminology
8977 // Structured block - An executable statement with a single entry at the
8978 // top and a single exit at the bottom.
8979 // The point of exit cannot be a branch out of the structured block.
8980 // longjmp() and throw() must not violate the entry/exit criteria.
8981 CS->getCapturedDecl()->setNothrow();
8982 }
8983
Alexey Bataev95b64a92017-05-30 16:00:04 +00008984 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00008985 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
8986 return StmtError();
8987 }
Alexey Bataev7828b252017-11-21 17:08:48 +00008988 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
8989 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00008990}
8991
Alexey Bataev13314bf2014-10-09 04:18:56 +00008992StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8993 Stmt *AStmt, SourceLocation StartLoc,
8994 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008995 if (!AStmt)
8996 return StmtError();
8997
Alexey Bataeve3727102018-04-18 15:57:46 +00008998 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008999 // 1.2.2 OpenMP Language Terminology
9000 // Structured block - An executable statement with a single entry at the
9001 // top and a single exit at the bottom.
9002 // The point of exit cannot be a branch out of the structured block.
9003 // longjmp() and throw() must not violate the entry/exit criteria.
9004 CS->getCapturedDecl()->setNothrow();
9005
Reid Kleckner87a31802018-03-12 21:43:02 +00009006 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009007
Alexey Bataevceabd412017-11-30 18:01:54 +00009008 DSAStack->setParentTeamsRegionLoc(StartLoc);
9009
Alexey Bataev13314bf2014-10-09 04:18:56 +00009010 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9011}
9012
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009013StmtResult
9014Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9015 SourceLocation EndLoc,
9016 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009017 if (DSAStack->isParentNowaitRegion()) {
9018 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9019 return StmtError();
9020 }
9021 if (DSAStack->isParentOrderedRegion()) {
9022 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9023 return StmtError();
9024 }
9025 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9026 CancelRegion);
9027}
9028
Alexey Bataev87933c72015-09-18 08:07:34 +00009029StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9030 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009031 SourceLocation EndLoc,
9032 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009033 if (DSAStack->isParentNowaitRegion()) {
9034 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9035 return StmtError();
9036 }
9037 if (DSAStack->isParentOrderedRegion()) {
9038 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9039 return StmtError();
9040 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009041 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009042 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9043 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009044}
9045
Alexey Bataev382967a2015-12-08 12:06:20 +00009046static bool checkGrainsizeNumTasksClauses(Sema &S,
9047 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009048 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009049 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009050 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009051 if (C->getClauseKind() == OMPC_grainsize ||
9052 C->getClauseKind() == OMPC_num_tasks) {
9053 if (!PrevClause)
9054 PrevClause = C;
9055 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009056 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009057 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9058 << getOpenMPClauseName(C->getClauseKind())
9059 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009060 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009061 diag::note_omp_previous_grainsize_num_tasks)
9062 << getOpenMPClauseName(PrevClause->getClauseKind());
9063 ErrorFound = true;
9064 }
9065 }
9066 }
9067 return ErrorFound;
9068}
9069
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009070static bool checkReductionClauseWithNogroup(Sema &S,
9071 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009072 const OMPClause *ReductionClause = nullptr;
9073 const OMPClause *NogroupClause = nullptr;
9074 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009075 if (C->getClauseKind() == OMPC_reduction) {
9076 ReductionClause = C;
9077 if (NogroupClause)
9078 break;
9079 continue;
9080 }
9081 if (C->getClauseKind() == OMPC_nogroup) {
9082 NogroupClause = C;
9083 if (ReductionClause)
9084 break;
9085 continue;
9086 }
9087 }
9088 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009089 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9090 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009091 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009092 return true;
9093 }
9094 return false;
9095}
9096
Alexey Bataev49f6e782015-12-01 04:18:41 +00009097StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009099 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009100 if (!AStmt)
9101 return StmtError();
9102
9103 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9104 OMPLoopDirective::HelperExprs B;
9105 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9106 // define the nested loops number.
9107 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009108 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009109 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009110 VarsWithImplicitDSA, B);
9111 if (NestedLoopCount == 0)
9112 return StmtError();
9113
9114 assert((CurContext->isDependentContext() || B.builtAll()) &&
9115 "omp for loop exprs were not built");
9116
Alexey Bataev382967a2015-12-08 12:06:20 +00009117 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9118 // The grainsize clause and num_tasks clause are mutually exclusive and may
9119 // not appear on the same taskloop directive.
9120 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9121 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009122 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9123 // If a reduction clause is present on the taskloop directive, the nogroup
9124 // clause must not be specified.
9125 if (checkReductionClauseWithNogroup(*this, Clauses))
9126 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009127
Reid Kleckner87a31802018-03-12 21:43:02 +00009128 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009129 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9130 NestedLoopCount, Clauses, AStmt, B);
9131}
9132
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009133StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009135 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009136 if (!AStmt)
9137 return StmtError();
9138
9139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9140 OMPLoopDirective::HelperExprs B;
9141 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9142 // define the nested loops number.
9143 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009144 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009145 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9146 VarsWithImplicitDSA, B);
9147 if (NestedLoopCount == 0)
9148 return StmtError();
9149
9150 assert((CurContext->isDependentContext() || B.builtAll()) &&
9151 "omp for loop exprs were not built");
9152
Alexey Bataev5a3af132016-03-29 08:58:54 +00009153 if (!CurContext->isDependentContext()) {
9154 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009155 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009156 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009157 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009158 B.NumIterations, *this, CurScope,
9159 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009160 return StmtError();
9161 }
9162 }
9163
Alexey Bataev382967a2015-12-08 12:06:20 +00009164 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9165 // The grainsize clause and num_tasks clause are mutually exclusive and may
9166 // not appear on the same taskloop directive.
9167 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9168 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009169 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9170 // If a reduction clause is present on the taskloop directive, the nogroup
9171 // clause must not be specified.
9172 if (checkReductionClauseWithNogroup(*this, Clauses))
9173 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009174 if (checkSimdlenSafelenSpecified(*this, Clauses))
9175 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009176
Reid Kleckner87a31802018-03-12 21:43:02 +00009177 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009178 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9179 NestedLoopCount, Clauses, AStmt, B);
9180}
9181
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009182StmtResult Sema::ActOnOpenMPDistributeDirective(
9183 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009184 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009185 if (!AStmt)
9186 return StmtError();
9187
9188 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9189 OMPLoopDirective::HelperExprs B;
9190 // In presence of clause 'collapse' with number of loops, it will
9191 // define the nested loops number.
9192 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009193 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009194 nullptr /*ordered not a clause on distribute*/, AStmt,
9195 *this, *DSAStack, VarsWithImplicitDSA, B);
9196 if (NestedLoopCount == 0)
9197 return StmtError();
9198
9199 assert((CurContext->isDependentContext() || B.builtAll()) &&
9200 "omp for loop exprs were not built");
9201
Reid Kleckner87a31802018-03-12 21:43:02 +00009202 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009203 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9204 NestedLoopCount, Clauses, AStmt, B);
9205}
9206
Carlo Bertolli9925f152016-06-27 14:55:37 +00009207StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9208 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009209 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009210 if (!AStmt)
9211 return StmtError();
9212
Alexey Bataeve3727102018-04-18 15:57:46 +00009213 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009214 // 1.2.2 OpenMP Language Terminology
9215 // Structured block - An executable statement with a single entry at the
9216 // top and a single exit at the bottom.
9217 // The point of exit cannot be a branch out of the structured block.
9218 // longjmp() and throw() must not violate the entry/exit criteria.
9219 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009220 for (int ThisCaptureLevel =
9221 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9222 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9223 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9224 // 1.2.2 OpenMP Language Terminology
9225 // Structured block - An executable statement with a single entry at the
9226 // top and a single exit at the bottom.
9227 // The point of exit cannot be a branch out of the structured block.
9228 // longjmp() and throw() must not violate the entry/exit criteria.
9229 CS->getCapturedDecl()->setNothrow();
9230 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009231
9232 OMPLoopDirective::HelperExprs B;
9233 // In presence of clause 'collapse' with number of loops, it will
9234 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009235 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009236 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009237 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009238 VarsWithImplicitDSA, B);
9239 if (NestedLoopCount == 0)
9240 return StmtError();
9241
9242 assert((CurContext->isDependentContext() || B.builtAll()) &&
9243 "omp for loop exprs were not built");
9244
Reid Kleckner87a31802018-03-12 21:43:02 +00009245 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009246 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009247 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9248 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009249}
9250
Kelvin Li4a39add2016-07-05 05:00:15 +00009251StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9252 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009253 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009254 if (!AStmt)
9255 return StmtError();
9256
Alexey Bataeve3727102018-04-18 15:57:46 +00009257 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009258 // 1.2.2 OpenMP Language Terminology
9259 // Structured block - An executable statement with a single entry at the
9260 // top and a single exit at the bottom.
9261 // The point of exit cannot be a branch out of the structured block.
9262 // longjmp() and throw() must not violate the entry/exit criteria.
9263 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009264 for (int ThisCaptureLevel =
9265 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9266 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9267 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9268 // 1.2.2 OpenMP Language Terminology
9269 // Structured block - An executable statement with a single entry at the
9270 // top and a single exit at the bottom.
9271 // The point of exit cannot be a branch out of the structured block.
9272 // longjmp() and throw() must not violate the entry/exit criteria.
9273 CS->getCapturedDecl()->setNothrow();
9274 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009275
9276 OMPLoopDirective::HelperExprs B;
9277 // In presence of clause 'collapse' with number of loops, it will
9278 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009279 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009280 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009281 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009282 VarsWithImplicitDSA, B);
9283 if (NestedLoopCount == 0)
9284 return StmtError();
9285
9286 assert((CurContext->isDependentContext() || B.builtAll()) &&
9287 "omp for loop exprs were not built");
9288
Alexey Bataev438388c2017-11-22 18:34:02 +00009289 if (!CurContext->isDependentContext()) {
9290 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009291 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009292 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9293 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9294 B.NumIterations, *this, CurScope,
9295 DSAStack))
9296 return StmtError();
9297 }
9298 }
9299
Kelvin Lic5609492016-07-15 04:39:07 +00009300 if (checkSimdlenSafelenSpecified(*this, Clauses))
9301 return StmtError();
9302
Reid Kleckner87a31802018-03-12 21:43:02 +00009303 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009304 return OMPDistributeParallelForSimdDirective::Create(
9305 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9306}
9307
Kelvin Li787f3fc2016-07-06 04:45:38 +00009308StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9309 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009310 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009311 if (!AStmt)
9312 return StmtError();
9313
Alexey Bataeve3727102018-04-18 15:57:46 +00009314 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009315 // 1.2.2 OpenMP Language Terminology
9316 // Structured block - An executable statement with a single entry at the
9317 // top and a single exit at the bottom.
9318 // The point of exit cannot be a branch out of the structured block.
9319 // longjmp() and throw() must not violate the entry/exit criteria.
9320 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009321 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9322 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9323 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9324 // 1.2.2 OpenMP Language Terminology
9325 // Structured block - An executable statement with a single entry at the
9326 // top and a single exit at the bottom.
9327 // The point of exit cannot be a branch out of the structured block.
9328 // longjmp() and throw() must not violate the entry/exit criteria.
9329 CS->getCapturedDecl()->setNothrow();
9330 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009331
9332 OMPLoopDirective::HelperExprs B;
9333 // In presence of clause 'collapse' with number of loops, it will
9334 // define the nested loops number.
9335 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009336 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009337 nullptr /*ordered not a clause on distribute*/, CS, *this,
9338 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009339 if (NestedLoopCount == 0)
9340 return StmtError();
9341
9342 assert((CurContext->isDependentContext() || B.builtAll()) &&
9343 "omp for loop exprs were not built");
9344
Alexey Bataev438388c2017-11-22 18:34:02 +00009345 if (!CurContext->isDependentContext()) {
9346 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009347 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009348 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9349 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9350 B.NumIterations, *this, CurScope,
9351 DSAStack))
9352 return StmtError();
9353 }
9354 }
9355
Kelvin Lic5609492016-07-15 04:39:07 +00009356 if (checkSimdlenSafelenSpecified(*this, Clauses))
9357 return StmtError();
9358
Reid Kleckner87a31802018-03-12 21:43:02 +00009359 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009360 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9361 NestedLoopCount, Clauses, AStmt, B);
9362}
9363
Kelvin Lia579b912016-07-14 02:54:56 +00009364StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9365 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009366 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009367 if (!AStmt)
9368 return StmtError();
9369
Alexey Bataeve3727102018-04-18 15:57:46 +00009370 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009371 // 1.2.2 OpenMP Language Terminology
9372 // Structured block - An executable statement with a single entry at the
9373 // top and a single exit at the bottom.
9374 // The point of exit cannot be a branch out of the structured block.
9375 // longjmp() and throw() must not violate the entry/exit criteria.
9376 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009377 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9378 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9379 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9380 // 1.2.2 OpenMP Language Terminology
9381 // Structured block - An executable statement with a single entry at the
9382 // top and a single exit at the bottom.
9383 // The point of exit cannot be a branch out of the structured block.
9384 // longjmp() and throw() must not violate the entry/exit criteria.
9385 CS->getCapturedDecl()->setNothrow();
9386 }
Kelvin Lia579b912016-07-14 02:54:56 +00009387
9388 OMPLoopDirective::HelperExprs B;
9389 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9390 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009391 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00009392 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009393 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00009394 VarsWithImplicitDSA, B);
9395 if (NestedLoopCount == 0)
9396 return StmtError();
9397
9398 assert((CurContext->isDependentContext() || B.builtAll()) &&
9399 "omp target parallel for simd loop exprs were not built");
9400
9401 if (!CurContext->isDependentContext()) {
9402 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009403 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009404 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00009405 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9406 B.NumIterations, *this, CurScope,
9407 DSAStack))
9408 return StmtError();
9409 }
9410 }
Kelvin Lic5609492016-07-15 04:39:07 +00009411 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00009412 return StmtError();
9413
Reid Kleckner87a31802018-03-12 21:43:02 +00009414 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00009415 return OMPTargetParallelForSimdDirective::Create(
9416 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9417}
9418
Kelvin Li986330c2016-07-20 22:57:10 +00009419StmtResult Sema::ActOnOpenMPTargetSimdDirective(
9420 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009421 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00009422 if (!AStmt)
9423 return StmtError();
9424
Alexey Bataeve3727102018-04-18 15:57:46 +00009425 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +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();
Alexey Bataevf8365372017-11-17 17:57:25 +00009432 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
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
Kelvin Li986330c2016-07-20 22:57:10 +00009443 OMPLoopDirective::HelperExprs B;
9444 // In presence of clause 'collapse' with number of loops, it will define the
9445 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00009446 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009447 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00009448 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00009449 VarsWithImplicitDSA, B);
9450 if (NestedLoopCount == 0)
9451 return StmtError();
9452
9453 assert((CurContext->isDependentContext() || B.builtAll()) &&
9454 "omp target simd loop exprs were not built");
9455
9456 if (!CurContext->isDependentContext()) {
9457 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009458 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009459 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00009460 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9461 B.NumIterations, *this, CurScope,
9462 DSAStack))
9463 return StmtError();
9464 }
9465 }
9466
9467 if (checkSimdlenSafelenSpecified(*this, Clauses))
9468 return StmtError();
9469
Reid Kleckner87a31802018-03-12 21:43:02 +00009470 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00009471 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
9472 NestedLoopCount, Clauses, AStmt, B);
9473}
9474
Kelvin Li02532872016-08-05 14:37:37 +00009475StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
9476 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009477 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00009478 if (!AStmt)
9479 return StmtError();
9480
Alexey Bataeve3727102018-04-18 15:57:46 +00009481 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00009482 // 1.2.2 OpenMP Language Terminology
9483 // Structured block - An executable statement with a single entry at the
9484 // top and a single exit at the bottom.
9485 // The point of exit cannot be a branch out of the structured block.
9486 // longjmp() and throw() must not violate the entry/exit criteria.
9487 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009488 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
9489 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9490 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9491 // 1.2.2 OpenMP Language Terminology
9492 // Structured block - An executable statement with a single entry at the
9493 // top and a single exit at the bottom.
9494 // The point of exit cannot be a branch out of the structured block.
9495 // longjmp() and throw() must not violate the entry/exit criteria.
9496 CS->getCapturedDecl()->setNothrow();
9497 }
Kelvin Li02532872016-08-05 14:37:37 +00009498
9499 OMPLoopDirective::HelperExprs B;
9500 // In presence of clause 'collapse' with number of loops, it will
9501 // define the nested loops number.
9502 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009503 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009504 nullptr /*ordered not a clause on distribute*/, CS, *this,
9505 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00009506 if (NestedLoopCount == 0)
9507 return StmtError();
9508
9509 assert((CurContext->isDependentContext() || B.builtAll()) &&
9510 "omp teams distribute loop exprs were not built");
9511
Reid Kleckner87a31802018-03-12 21:43:02 +00009512 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009513
9514 DSAStack->setParentTeamsRegionLoc(StartLoc);
9515
David Majnemer9d168222016-08-05 17:44:54 +00009516 return OMPTeamsDistributeDirective::Create(
9517 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00009518}
9519
Kelvin Li4e325f72016-10-25 12:50:55 +00009520StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
9521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009522 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009523 if (!AStmt)
9524 return StmtError();
9525
Alexey Bataeve3727102018-04-18 15:57:46 +00009526 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00009527 // 1.2.2 OpenMP Language Terminology
9528 // Structured block - An executable statement with a single entry at the
9529 // top and a single exit at the bottom.
9530 // The point of exit cannot be a branch out of the structured block.
9531 // longjmp() and throw() must not violate the entry/exit criteria.
9532 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00009533 for (int ThisCaptureLevel =
9534 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
9535 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9536 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9537 // 1.2.2 OpenMP Language Terminology
9538 // Structured block - An executable statement with a single entry at the
9539 // top and a single exit at the bottom.
9540 // The point of exit cannot be a branch out of the structured block.
9541 // longjmp() and throw() must not violate the entry/exit criteria.
9542 CS->getCapturedDecl()->setNothrow();
9543 }
9544
Kelvin Li4e325f72016-10-25 12:50:55 +00009545
9546 OMPLoopDirective::HelperExprs B;
9547 // In presence of clause 'collapse' with number of loops, it will
9548 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009549 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00009550 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00009551 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00009552 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00009553
9554 if (NestedLoopCount == 0)
9555 return StmtError();
9556
9557 assert((CurContext->isDependentContext() || B.builtAll()) &&
9558 "omp teams distribute simd loop exprs were not built");
9559
9560 if (!CurContext->isDependentContext()) {
9561 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009562 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009563 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9564 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9565 B.NumIterations, *this, CurScope,
9566 DSAStack))
9567 return StmtError();
9568 }
9569 }
9570
9571 if (checkSimdlenSafelenSpecified(*this, Clauses))
9572 return StmtError();
9573
Reid Kleckner87a31802018-03-12 21:43:02 +00009574 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009575
9576 DSAStack->setParentTeamsRegionLoc(StartLoc);
9577
Kelvin Li4e325f72016-10-25 12:50:55 +00009578 return OMPTeamsDistributeSimdDirective::Create(
9579 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9580}
9581
Kelvin Li579e41c2016-11-30 23:51:03 +00009582StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9583 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009584 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009585 if (!AStmt)
9586 return StmtError();
9587
Alexey Bataeve3727102018-04-18 15:57:46 +00009588 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00009589 // 1.2.2 OpenMP Language Terminology
9590 // Structured block - An executable statement with a single entry at the
9591 // top and a single exit at the bottom.
9592 // The point of exit cannot be a branch out of the structured block.
9593 // longjmp() and throw() must not violate the entry/exit criteria.
9594 CS->getCapturedDecl()->setNothrow();
9595
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009596 for (int ThisCaptureLevel =
9597 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
9598 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9599 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9600 // 1.2.2 OpenMP Language Terminology
9601 // Structured block - An executable statement with a single entry at the
9602 // top and a single exit at the bottom.
9603 // The point of exit cannot be a branch out of the structured block.
9604 // longjmp() and throw() must not violate the entry/exit criteria.
9605 CS->getCapturedDecl()->setNothrow();
9606 }
9607
Kelvin Li579e41c2016-11-30 23:51:03 +00009608 OMPLoopDirective::HelperExprs B;
9609 // In presence of clause 'collapse' with number of loops, it will
9610 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009611 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00009612 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009613 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00009614 VarsWithImplicitDSA, B);
9615
9616 if (NestedLoopCount == 0)
9617 return StmtError();
9618
9619 assert((CurContext->isDependentContext() || B.builtAll()) &&
9620 "omp for loop exprs were not built");
9621
9622 if (!CurContext->isDependentContext()) {
9623 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009624 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009625 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9626 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9627 B.NumIterations, *this, CurScope,
9628 DSAStack))
9629 return StmtError();
9630 }
9631 }
9632
9633 if (checkSimdlenSafelenSpecified(*this, Clauses))
9634 return StmtError();
9635
Reid Kleckner87a31802018-03-12 21:43:02 +00009636 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009637
9638 DSAStack->setParentTeamsRegionLoc(StartLoc);
9639
Kelvin Li579e41c2016-11-30 23:51:03 +00009640 return OMPTeamsDistributeParallelForSimdDirective::Create(
9641 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9642}
9643
Kelvin Li7ade93f2016-12-09 03:24:30 +00009644StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
9645 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009646 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00009647 if (!AStmt)
9648 return StmtError();
9649
Alexey Bataeve3727102018-04-18 15:57:46 +00009650 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00009651 // 1.2.2 OpenMP Language Terminology
9652 // Structured block - An executable statement with a single entry at the
9653 // top and a single exit at the bottom.
9654 // The point of exit cannot be a branch out of the structured block.
9655 // longjmp() and throw() must not violate the entry/exit criteria.
9656 CS->getCapturedDecl()->setNothrow();
9657
Carlo Bertolli62fae152017-11-20 20:46:39 +00009658 for (int ThisCaptureLevel =
9659 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
9660 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9661 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9662 // 1.2.2 OpenMP Language Terminology
9663 // Structured block - An executable statement with a single entry at the
9664 // top and a single exit at the bottom.
9665 // The point of exit cannot be a branch out of the structured block.
9666 // longjmp() and throw() must not violate the entry/exit criteria.
9667 CS->getCapturedDecl()->setNothrow();
9668 }
9669
Kelvin Li7ade93f2016-12-09 03:24:30 +00009670 OMPLoopDirective::HelperExprs B;
9671 // In presence of clause 'collapse' with number of loops, it will
9672 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009673 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00009674 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00009675 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00009676 VarsWithImplicitDSA, B);
9677
9678 if (NestedLoopCount == 0)
9679 return StmtError();
9680
9681 assert((CurContext->isDependentContext() || B.builtAll()) &&
9682 "omp for loop exprs were not built");
9683
Reid Kleckner87a31802018-03-12 21:43:02 +00009684 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009685
9686 DSAStack->setParentTeamsRegionLoc(StartLoc);
9687
Kelvin Li7ade93f2016-12-09 03:24:30 +00009688 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009689 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9690 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00009691}
9692
Kelvin Libf594a52016-12-17 05:48:59 +00009693StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9694 Stmt *AStmt,
9695 SourceLocation StartLoc,
9696 SourceLocation EndLoc) {
9697 if (!AStmt)
9698 return StmtError();
9699
Alexey Bataeve3727102018-04-18 15:57:46 +00009700 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00009701 // 1.2.2 OpenMP Language Terminology
9702 // Structured block - An executable statement with a single entry at the
9703 // top and a single exit at the bottom.
9704 // The point of exit cannot be a branch out of the structured block.
9705 // longjmp() and throw() must not violate the entry/exit criteria.
9706 CS->getCapturedDecl()->setNothrow();
9707
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00009708 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
9709 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9710 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9711 // 1.2.2 OpenMP Language Terminology
9712 // Structured block - An executable statement with a single entry at the
9713 // top and a single exit at the bottom.
9714 // The point of exit cannot be a branch out of the structured block.
9715 // longjmp() and throw() must not violate the entry/exit criteria.
9716 CS->getCapturedDecl()->setNothrow();
9717 }
Reid Kleckner87a31802018-03-12 21:43:02 +00009718 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00009719
9720 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
9721 AStmt);
9722}
9723
Kelvin Li83c451e2016-12-25 04:52:54 +00009724StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
9725 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009726 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00009727 if (!AStmt)
9728 return StmtError();
9729
Alexey Bataeve3727102018-04-18 15:57:46 +00009730 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00009731 // 1.2.2 OpenMP Language Terminology
9732 // Structured block - An executable statement with a single entry at the
9733 // top and a single exit at the bottom.
9734 // The point of exit cannot be a branch out of the structured block.
9735 // longjmp() and throw() must not violate the entry/exit criteria.
9736 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00009737 for (int ThisCaptureLevel =
9738 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
9739 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9740 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9741 // 1.2.2 OpenMP Language Terminology
9742 // Structured block - An executable statement with a single entry at the
9743 // top and a single exit at the bottom.
9744 // The point of exit cannot be a branch out of the structured block.
9745 // longjmp() and throw() must not violate the entry/exit criteria.
9746 CS->getCapturedDecl()->setNothrow();
9747 }
Kelvin Li83c451e2016-12-25 04:52:54 +00009748
9749 OMPLoopDirective::HelperExprs B;
9750 // In presence of clause 'collapse' with number of loops, it will
9751 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009752 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00009753 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
9754 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00009755 VarsWithImplicitDSA, B);
9756 if (NestedLoopCount == 0)
9757 return StmtError();
9758
9759 assert((CurContext->isDependentContext() || B.builtAll()) &&
9760 "omp target teams distribute loop exprs were not built");
9761
Reid Kleckner87a31802018-03-12 21:43:02 +00009762 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00009763 return OMPTargetTeamsDistributeDirective::Create(
9764 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9765}
9766
Kelvin Li80e8f562016-12-29 22:16:30 +00009767StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9768 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009769 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00009770 if (!AStmt)
9771 return StmtError();
9772
Alexey Bataeve3727102018-04-18 15:57:46 +00009773 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00009774 // 1.2.2 OpenMP Language Terminology
9775 // Structured block - An executable statement with a single entry at the
9776 // top and a single exit at the bottom.
9777 // The point of exit cannot be a branch out of the structured block.
9778 // longjmp() and throw() must not violate the entry/exit criteria.
9779 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00009780 for (int ThisCaptureLevel =
9781 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
9782 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9783 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9784 // 1.2.2 OpenMP Language Terminology
9785 // Structured block - An executable statement with a single entry at the
9786 // top and a single exit at the bottom.
9787 // The point of exit cannot be a branch out of the structured block.
9788 // longjmp() and throw() must not violate the entry/exit criteria.
9789 CS->getCapturedDecl()->setNothrow();
9790 }
9791
Kelvin Li80e8f562016-12-29 22:16:30 +00009792 OMPLoopDirective::HelperExprs B;
9793 // In presence of clause 'collapse' with number of loops, it will
9794 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009795 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00009796 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
9797 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00009798 VarsWithImplicitDSA, B);
9799 if (NestedLoopCount == 0)
9800 return StmtError();
9801
9802 assert((CurContext->isDependentContext() || B.builtAll()) &&
9803 "omp target teams distribute parallel for loop exprs were not built");
9804
Alexey Bataev647dd842018-01-15 20:59:40 +00009805 if (!CurContext->isDependentContext()) {
9806 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009807 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00009808 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9809 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9810 B.NumIterations, *this, CurScope,
9811 DSAStack))
9812 return StmtError();
9813 }
9814 }
9815
Reid Kleckner87a31802018-03-12 21:43:02 +00009816 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00009817 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00009818 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9819 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00009820}
9821
Kelvin Li1851df52017-01-03 05:23:48 +00009822StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9823 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009824 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00009825 if (!AStmt)
9826 return StmtError();
9827
Alexey Bataeve3727102018-04-18 15:57:46 +00009828 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00009829 // 1.2.2 OpenMP Language Terminology
9830 // Structured block - An executable statement with a single entry at the
9831 // top and a single exit at the bottom.
9832 // The point of exit cannot be a branch out of the structured block.
9833 // longjmp() and throw() must not violate the entry/exit criteria.
9834 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00009835 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
9836 OMPD_target_teams_distribute_parallel_for_simd);
9837 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9838 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9839 // 1.2.2 OpenMP Language Terminology
9840 // Structured block - An executable statement with a single entry at the
9841 // top and a single exit at the bottom.
9842 // The point of exit cannot be a branch out of the structured block.
9843 // longjmp() and throw() must not violate the entry/exit criteria.
9844 CS->getCapturedDecl()->setNothrow();
9845 }
Kelvin Li1851df52017-01-03 05:23:48 +00009846
9847 OMPLoopDirective::HelperExprs B;
9848 // In presence of clause 'collapse' with number of loops, it will
9849 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009850 unsigned NestedLoopCount =
9851 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00009852 getCollapseNumberExpr(Clauses),
9853 nullptr /*ordered not a clause on distribute*/, CS, *this,
9854 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00009855 if (NestedLoopCount == 0)
9856 return StmtError();
9857
9858 assert((CurContext->isDependentContext() || B.builtAll()) &&
9859 "omp target teams distribute parallel for simd loop exprs were not "
9860 "built");
9861
9862 if (!CurContext->isDependentContext()) {
9863 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009864 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00009865 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9866 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9867 B.NumIterations, *this, CurScope,
9868 DSAStack))
9869 return StmtError();
9870 }
9871 }
9872
Alexey Bataev438388c2017-11-22 18:34:02 +00009873 if (checkSimdlenSafelenSpecified(*this, Clauses))
9874 return StmtError();
9875
Reid Kleckner87a31802018-03-12 21:43:02 +00009876 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00009877 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
9878 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9879}
9880
Kelvin Lida681182017-01-10 18:08:18 +00009881StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
9882 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009883 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00009884 if (!AStmt)
9885 return StmtError();
9886
9887 auto *CS = cast<CapturedStmt>(AStmt);
9888 // 1.2.2 OpenMP Language Terminology
9889 // Structured block - An executable statement with a single entry at the
9890 // top and a single exit at the bottom.
9891 // The point of exit cannot be a branch out of the structured block.
9892 // longjmp() and throw() must not violate the entry/exit criteria.
9893 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009894 for (int ThisCaptureLevel =
9895 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
9896 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9897 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9898 // 1.2.2 OpenMP Language Terminology
9899 // Structured block - An executable statement with a single entry at the
9900 // top and a single exit at the bottom.
9901 // The point of exit cannot be a branch out of the structured block.
9902 // longjmp() and throw() must not violate the entry/exit criteria.
9903 CS->getCapturedDecl()->setNothrow();
9904 }
Kelvin Lida681182017-01-10 18:08:18 +00009905
9906 OMPLoopDirective::HelperExprs B;
9907 // In presence of clause 'collapse' with number of loops, it will
9908 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009909 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00009910 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009911 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00009912 VarsWithImplicitDSA, B);
9913 if (NestedLoopCount == 0)
9914 return StmtError();
9915
9916 assert((CurContext->isDependentContext() || B.builtAll()) &&
9917 "omp target teams distribute simd loop exprs were not built");
9918
Alexey Bataev438388c2017-11-22 18:34:02 +00009919 if (!CurContext->isDependentContext()) {
9920 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009921 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009922 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9923 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9924 B.NumIterations, *this, CurScope,
9925 DSAStack))
9926 return StmtError();
9927 }
9928 }
9929
9930 if (checkSimdlenSafelenSpecified(*this, Clauses))
9931 return StmtError();
9932
Reid Kleckner87a31802018-03-12 21:43:02 +00009933 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00009934 return OMPTargetTeamsDistributeSimdDirective::Create(
9935 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9936}
9937
Alexey Bataeved09d242014-05-28 05:53:51 +00009938OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009939 SourceLocation StartLoc,
9940 SourceLocation LParenLoc,
9941 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009942 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009943 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00009944 case OMPC_final:
9945 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
9946 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00009947 case OMPC_num_threads:
9948 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
9949 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009950 case OMPC_safelen:
9951 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
9952 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00009953 case OMPC_simdlen:
9954 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
9955 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009956 case OMPC_allocator:
9957 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
9958 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00009959 case OMPC_collapse:
9960 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
9961 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009962 case OMPC_ordered:
9963 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
9964 break;
Michael Wonge710d542015-08-07 16:16:36 +00009965 case OMPC_device:
9966 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
9967 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00009968 case OMPC_num_teams:
9969 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
9970 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009971 case OMPC_thread_limit:
9972 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
9973 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00009974 case OMPC_priority:
9975 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
9976 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009977 case OMPC_grainsize:
9978 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
9979 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00009980 case OMPC_num_tasks:
9981 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
9982 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00009983 case OMPC_hint:
9984 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
9985 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009986 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009987 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009988 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009989 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009990 case OMPC_private:
9991 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009992 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009993 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009994 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009995 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009996 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009997 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009998 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009999 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010000 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010001 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010002 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010003 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010004 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010005 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010006 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010007 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010008 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010009 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010010 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010011 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010012 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010013 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010014 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010015 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010016 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010017 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010018 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010019 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010020 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010021 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010022 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010023 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010024 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010025 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010026 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010027 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010028 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010029 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010030 case OMPC_device_type:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010031 llvm_unreachable("Clause is not allowed.");
10032 }
10033 return Res;
10034}
10035
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010036// An OpenMP directive such as 'target parallel' has two captured regions:
10037// for the 'target' and 'parallel' respectively. This function returns
10038// the region in which to capture expressions associated with a clause.
10039// A return value of OMPD_unknown signifies that the expression should not
10040// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010041static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10042 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10043 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010044 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010045 switch (CKind) {
10046 case OMPC_if:
10047 switch (DKind) {
10048 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010049 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010050 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010051 // If this clause applies to the nested 'parallel' region, capture within
10052 // the 'target' region, otherwise do not capture.
10053 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10054 CaptureRegion = OMPD_target;
10055 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010056 case OMPD_target_teams_distribute_parallel_for:
10057 case OMPD_target_teams_distribute_parallel_for_simd:
10058 // If this clause applies to the nested 'parallel' region, capture within
10059 // the 'teams' region, otherwise do not capture.
10060 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10061 CaptureRegion = OMPD_teams;
10062 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010063 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010064 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010065 CaptureRegion = OMPD_teams;
10066 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010067 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010068 case OMPD_target_enter_data:
10069 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010070 CaptureRegion = OMPD_task;
10071 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010072 case OMPD_cancel:
10073 case OMPD_parallel:
10074 case OMPD_parallel_sections:
10075 case OMPD_parallel_for:
10076 case OMPD_parallel_for_simd:
10077 case OMPD_target:
10078 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010079 case OMPD_target_teams:
10080 case OMPD_target_teams_distribute:
10081 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010082 case OMPD_distribute_parallel_for:
10083 case OMPD_distribute_parallel_for_simd:
10084 case OMPD_task:
10085 case OMPD_taskloop:
10086 case OMPD_taskloop_simd:
10087 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010088 // Do not capture if-clause expressions.
10089 break;
10090 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010091 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010092 case OMPD_taskyield:
10093 case OMPD_barrier:
10094 case OMPD_taskwait:
10095 case OMPD_cancellation_point:
10096 case OMPD_flush:
10097 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010098 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010099 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010100 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010101 case OMPD_declare_target:
10102 case OMPD_end_declare_target:
10103 case OMPD_teams:
10104 case OMPD_simd:
10105 case OMPD_for:
10106 case OMPD_for_simd:
10107 case OMPD_sections:
10108 case OMPD_section:
10109 case OMPD_single:
10110 case OMPD_master:
10111 case OMPD_critical:
10112 case OMPD_taskgroup:
10113 case OMPD_distribute:
10114 case OMPD_ordered:
10115 case OMPD_atomic:
10116 case OMPD_distribute_simd:
10117 case OMPD_teams_distribute:
10118 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010119 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010120 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10121 case OMPD_unknown:
10122 llvm_unreachable("Unknown OpenMP directive");
10123 }
10124 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010125 case OMPC_num_threads:
10126 switch (DKind) {
10127 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010128 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010129 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010130 CaptureRegion = OMPD_target;
10131 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010132 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010133 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010134 case OMPD_target_teams_distribute_parallel_for:
10135 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010136 CaptureRegion = OMPD_teams;
10137 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010138 case OMPD_parallel:
10139 case OMPD_parallel_sections:
10140 case OMPD_parallel_for:
10141 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010142 case OMPD_distribute_parallel_for:
10143 case OMPD_distribute_parallel_for_simd:
10144 // Do not capture num_threads-clause expressions.
10145 break;
10146 case OMPD_target_data:
10147 case OMPD_target_enter_data:
10148 case OMPD_target_exit_data:
10149 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010150 case OMPD_target:
10151 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010152 case OMPD_target_teams:
10153 case OMPD_target_teams_distribute:
10154 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010155 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010156 case OMPD_task:
10157 case OMPD_taskloop:
10158 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010159 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010160 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010161 case OMPD_taskyield:
10162 case OMPD_barrier:
10163 case OMPD_taskwait:
10164 case OMPD_cancellation_point:
10165 case OMPD_flush:
10166 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010167 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010168 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010169 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010170 case OMPD_declare_target:
10171 case OMPD_end_declare_target:
10172 case OMPD_teams:
10173 case OMPD_simd:
10174 case OMPD_for:
10175 case OMPD_for_simd:
10176 case OMPD_sections:
10177 case OMPD_section:
10178 case OMPD_single:
10179 case OMPD_master:
10180 case OMPD_critical:
10181 case OMPD_taskgroup:
10182 case OMPD_distribute:
10183 case OMPD_ordered:
10184 case OMPD_atomic:
10185 case OMPD_distribute_simd:
10186 case OMPD_teams_distribute:
10187 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010188 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010189 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10190 case OMPD_unknown:
10191 llvm_unreachable("Unknown OpenMP directive");
10192 }
10193 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010194 case OMPC_num_teams:
10195 switch (DKind) {
10196 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010197 case OMPD_target_teams_distribute:
10198 case OMPD_target_teams_distribute_simd:
10199 case OMPD_target_teams_distribute_parallel_for:
10200 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010201 CaptureRegion = OMPD_target;
10202 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010203 case OMPD_teams_distribute_parallel_for:
10204 case OMPD_teams_distribute_parallel_for_simd:
10205 case OMPD_teams:
10206 case OMPD_teams_distribute:
10207 case OMPD_teams_distribute_simd:
10208 // Do not capture num_teams-clause expressions.
10209 break;
10210 case OMPD_distribute_parallel_for:
10211 case OMPD_distribute_parallel_for_simd:
10212 case OMPD_task:
10213 case OMPD_taskloop:
10214 case OMPD_taskloop_simd:
10215 case OMPD_target_data:
10216 case OMPD_target_enter_data:
10217 case OMPD_target_exit_data:
10218 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010219 case OMPD_cancel:
10220 case OMPD_parallel:
10221 case OMPD_parallel_sections:
10222 case OMPD_parallel_for:
10223 case OMPD_parallel_for_simd:
10224 case OMPD_target:
10225 case OMPD_target_simd:
10226 case OMPD_target_parallel:
10227 case OMPD_target_parallel_for:
10228 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010229 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010230 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010231 case OMPD_taskyield:
10232 case OMPD_barrier:
10233 case OMPD_taskwait:
10234 case OMPD_cancellation_point:
10235 case OMPD_flush:
10236 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010237 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010238 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010239 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010240 case OMPD_declare_target:
10241 case OMPD_end_declare_target:
10242 case OMPD_simd:
10243 case OMPD_for:
10244 case OMPD_for_simd:
10245 case OMPD_sections:
10246 case OMPD_section:
10247 case OMPD_single:
10248 case OMPD_master:
10249 case OMPD_critical:
10250 case OMPD_taskgroup:
10251 case OMPD_distribute:
10252 case OMPD_ordered:
10253 case OMPD_atomic:
10254 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010255 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010256 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10257 case OMPD_unknown:
10258 llvm_unreachable("Unknown OpenMP directive");
10259 }
10260 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010261 case OMPC_thread_limit:
10262 switch (DKind) {
10263 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010264 case OMPD_target_teams_distribute:
10265 case OMPD_target_teams_distribute_simd:
10266 case OMPD_target_teams_distribute_parallel_for:
10267 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010268 CaptureRegion = OMPD_target;
10269 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010270 case OMPD_teams_distribute_parallel_for:
10271 case OMPD_teams_distribute_parallel_for_simd:
10272 case OMPD_teams:
10273 case OMPD_teams_distribute:
10274 case OMPD_teams_distribute_simd:
10275 // Do not capture thread_limit-clause expressions.
10276 break;
10277 case OMPD_distribute_parallel_for:
10278 case OMPD_distribute_parallel_for_simd:
10279 case OMPD_task:
10280 case OMPD_taskloop:
10281 case OMPD_taskloop_simd:
10282 case OMPD_target_data:
10283 case OMPD_target_enter_data:
10284 case OMPD_target_exit_data:
10285 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010286 case OMPD_cancel:
10287 case OMPD_parallel:
10288 case OMPD_parallel_sections:
10289 case OMPD_parallel_for:
10290 case OMPD_parallel_for_simd:
10291 case OMPD_target:
10292 case OMPD_target_simd:
10293 case OMPD_target_parallel:
10294 case OMPD_target_parallel_for:
10295 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010296 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010297 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010298 case OMPD_taskyield:
10299 case OMPD_barrier:
10300 case OMPD_taskwait:
10301 case OMPD_cancellation_point:
10302 case OMPD_flush:
10303 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010304 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010305 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010306 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010307 case OMPD_declare_target:
10308 case OMPD_end_declare_target:
10309 case OMPD_simd:
10310 case OMPD_for:
10311 case OMPD_for_simd:
10312 case OMPD_sections:
10313 case OMPD_section:
10314 case OMPD_single:
10315 case OMPD_master:
10316 case OMPD_critical:
10317 case OMPD_taskgroup:
10318 case OMPD_distribute:
10319 case OMPD_ordered:
10320 case OMPD_atomic:
10321 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010322 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010323 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10324 case OMPD_unknown:
10325 llvm_unreachable("Unknown OpenMP directive");
10326 }
10327 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010328 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010329 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010330 case OMPD_parallel_for:
10331 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010332 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010333 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010334 case OMPD_teams_distribute_parallel_for:
10335 case OMPD_teams_distribute_parallel_for_simd:
10336 case OMPD_target_parallel_for:
10337 case OMPD_target_parallel_for_simd:
10338 case OMPD_target_teams_distribute_parallel_for:
10339 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010340 CaptureRegion = OMPD_parallel;
10341 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010342 case OMPD_for:
10343 case OMPD_for_simd:
10344 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010345 break;
10346 case OMPD_task:
10347 case OMPD_taskloop:
10348 case OMPD_taskloop_simd:
10349 case OMPD_target_data:
10350 case OMPD_target_enter_data:
10351 case OMPD_target_exit_data:
10352 case OMPD_target_update:
10353 case OMPD_teams:
10354 case OMPD_teams_distribute:
10355 case OMPD_teams_distribute_simd:
10356 case OMPD_target_teams_distribute:
10357 case OMPD_target_teams_distribute_simd:
10358 case OMPD_target:
10359 case OMPD_target_simd:
10360 case OMPD_target_parallel:
10361 case OMPD_cancel:
10362 case OMPD_parallel:
10363 case OMPD_parallel_sections:
10364 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010365 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010366 case OMPD_taskyield:
10367 case OMPD_barrier:
10368 case OMPD_taskwait:
10369 case OMPD_cancellation_point:
10370 case OMPD_flush:
10371 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010372 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010373 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010374 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010375 case OMPD_declare_target:
10376 case OMPD_end_declare_target:
10377 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010378 case OMPD_sections:
10379 case OMPD_section:
10380 case OMPD_single:
10381 case OMPD_master:
10382 case OMPD_critical:
10383 case OMPD_taskgroup:
10384 case OMPD_distribute:
10385 case OMPD_ordered:
10386 case OMPD_atomic:
10387 case OMPD_distribute_simd:
10388 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010389 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010390 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10391 case OMPD_unknown:
10392 llvm_unreachable("Unknown OpenMP directive");
10393 }
10394 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010395 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010396 switch (DKind) {
10397 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010398 case OMPD_teams_distribute_parallel_for_simd:
10399 case OMPD_teams_distribute:
10400 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010401 case OMPD_target_teams_distribute_parallel_for:
10402 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010403 case OMPD_target_teams_distribute:
10404 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010405 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010406 break;
10407 case OMPD_distribute_parallel_for:
10408 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010409 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010410 case OMPD_distribute_simd:
10411 // Do not capture thread_limit-clause expressions.
10412 break;
10413 case OMPD_parallel_for:
10414 case OMPD_parallel_for_simd:
10415 case OMPD_target_parallel_for_simd:
10416 case OMPD_target_parallel_for:
10417 case OMPD_task:
10418 case OMPD_taskloop:
10419 case OMPD_taskloop_simd:
10420 case OMPD_target_data:
10421 case OMPD_target_enter_data:
10422 case OMPD_target_exit_data:
10423 case OMPD_target_update:
10424 case OMPD_teams:
10425 case OMPD_target:
10426 case OMPD_target_simd:
10427 case OMPD_target_parallel:
10428 case OMPD_cancel:
10429 case OMPD_parallel:
10430 case OMPD_parallel_sections:
10431 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010432 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010433 case OMPD_taskyield:
10434 case OMPD_barrier:
10435 case OMPD_taskwait:
10436 case OMPD_cancellation_point:
10437 case OMPD_flush:
10438 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010439 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010440 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010441 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010442 case OMPD_declare_target:
10443 case OMPD_end_declare_target:
10444 case OMPD_simd:
10445 case OMPD_for:
10446 case OMPD_for_simd:
10447 case OMPD_sections:
10448 case OMPD_section:
10449 case OMPD_single:
10450 case OMPD_master:
10451 case OMPD_critical:
10452 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010453 case OMPD_ordered:
10454 case OMPD_atomic:
10455 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010456 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010457 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10458 case OMPD_unknown:
10459 llvm_unreachable("Unknown OpenMP directive");
10460 }
10461 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010462 case OMPC_device:
10463 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010464 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010465 case OMPD_target_enter_data:
10466 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000010467 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000010468 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000010469 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000010470 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000010471 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000010472 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000010473 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000010474 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000010475 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000010476 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010477 CaptureRegion = OMPD_task;
10478 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010479 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010480 // Do not capture device-clause expressions.
10481 break;
10482 case OMPD_teams_distribute_parallel_for:
10483 case OMPD_teams_distribute_parallel_for_simd:
10484 case OMPD_teams:
10485 case OMPD_teams_distribute:
10486 case OMPD_teams_distribute_simd:
10487 case OMPD_distribute_parallel_for:
10488 case OMPD_distribute_parallel_for_simd:
10489 case OMPD_task:
10490 case OMPD_taskloop:
10491 case OMPD_taskloop_simd:
10492 case OMPD_cancel:
10493 case OMPD_parallel:
10494 case OMPD_parallel_sections:
10495 case OMPD_parallel_for:
10496 case OMPD_parallel_for_simd:
10497 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010498 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010499 case OMPD_taskyield:
10500 case OMPD_barrier:
10501 case OMPD_taskwait:
10502 case OMPD_cancellation_point:
10503 case OMPD_flush:
10504 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010505 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010506 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010507 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010508 case OMPD_declare_target:
10509 case OMPD_end_declare_target:
10510 case OMPD_simd:
10511 case OMPD_for:
10512 case OMPD_for_simd:
10513 case OMPD_sections:
10514 case OMPD_section:
10515 case OMPD_single:
10516 case OMPD_master:
10517 case OMPD_critical:
10518 case OMPD_taskgroup:
10519 case OMPD_distribute:
10520 case OMPD_ordered:
10521 case OMPD_atomic:
10522 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010523 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010524 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10525 case OMPD_unknown:
10526 llvm_unreachable("Unknown OpenMP directive");
10527 }
10528 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010529 case OMPC_firstprivate:
10530 case OMPC_lastprivate:
10531 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010532 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010533 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010534 case OMPC_linear:
10535 case OMPC_default:
10536 case OMPC_proc_bind:
10537 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010538 case OMPC_safelen:
10539 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010540 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010541 case OMPC_collapse:
10542 case OMPC_private:
10543 case OMPC_shared:
10544 case OMPC_aligned:
10545 case OMPC_copyin:
10546 case OMPC_copyprivate:
10547 case OMPC_ordered:
10548 case OMPC_nowait:
10549 case OMPC_untied:
10550 case OMPC_mergeable:
10551 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010552 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010553 case OMPC_flush:
10554 case OMPC_read:
10555 case OMPC_write:
10556 case OMPC_update:
10557 case OMPC_capture:
10558 case OMPC_seq_cst:
10559 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010560 case OMPC_threads:
10561 case OMPC_simd:
10562 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010563 case OMPC_priority:
10564 case OMPC_grainsize:
10565 case OMPC_nogroup:
10566 case OMPC_num_tasks:
10567 case OMPC_hint:
10568 case OMPC_defaultmap:
10569 case OMPC_unknown:
10570 case OMPC_uniform:
10571 case OMPC_to:
10572 case OMPC_from:
10573 case OMPC_use_device_ptr:
10574 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010575 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010576 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010577 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010578 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010579 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010580 case OMPC_device_type:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010581 llvm_unreachable("Unexpected OpenMP clause.");
10582 }
10583 return CaptureRegion;
10584}
10585
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010586OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10587 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010588 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010589 SourceLocation NameModifierLoc,
10590 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010591 SourceLocation EndLoc) {
10592 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010593 Stmt *HelperValStmt = nullptr;
10594 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010595 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10596 !Condition->isInstantiationDependent() &&
10597 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010598 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010599 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010600 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010601
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010602 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010603
10604 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10605 CaptureRegion =
10606 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000010607 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010608 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010609 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010610 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10611 HelperValStmt = buildPreInits(Context, Captures);
10612 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010613 }
10614
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010615 return new (Context)
10616 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
10617 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010618}
10619
Alexey Bataev3778b602014-07-17 07:32:53 +000010620OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
10621 SourceLocation StartLoc,
10622 SourceLocation LParenLoc,
10623 SourceLocation EndLoc) {
10624 Expr *ValExpr = Condition;
10625 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10626 !Condition->isInstantiationDependent() &&
10627 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010628 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000010629 if (Val.isInvalid())
10630 return nullptr;
10631
Richard Smith03a4aa32016-06-23 19:02:52 +000010632 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +000010633 }
10634
10635 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10636}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010637ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
10638 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000010639 if (!Op)
10640 return ExprError();
10641
10642 class IntConvertDiagnoser : public ICEConvertDiagnoser {
10643 public:
10644 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000010645 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000010646 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10647 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010648 return S.Diag(Loc, diag::err_omp_not_integral) << T;
10649 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010650 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
10651 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010652 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
10653 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010654 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
10655 QualType T,
10656 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010657 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
10658 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010659 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
10660 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010661 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000010662 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000010663 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010664 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10665 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010666 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
10667 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010668 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
10669 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010670 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000010671 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000010672 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010673 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
10674 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010675 llvm_unreachable("conversion functions are permitted");
10676 }
10677 } ConvertDiagnoser;
10678 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
10679}
10680
Alexey Bataeve3727102018-04-18 15:57:46 +000010681static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +000010682 OpenMPClauseKind CKind,
10683 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010684 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
10685 !ValExpr->isInstantiationDependent()) {
10686 SourceLocation Loc = ValExpr->getExprLoc();
10687 ExprResult Value =
10688 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
10689 if (Value.isInvalid())
10690 return false;
10691
10692 ValExpr = Value.get();
10693 // The expression must evaluate to a non-negative integer value.
10694 llvm::APSInt Result;
10695 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000010696 Result.isSigned() &&
10697 !((!StrictlyPositive && Result.isNonNegative()) ||
10698 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010699 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000010700 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
10701 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010702 return false;
10703 }
10704 }
10705 return true;
10706}
10707
Alexey Bataev568a8332014-03-06 06:15:19 +000010708OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10709 SourceLocation StartLoc,
10710 SourceLocation LParenLoc,
10711 SourceLocation EndLoc) {
10712 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010713 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000010714
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010715 // OpenMP [2.5, Restrictions]
10716 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000010717 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000010718 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010719 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000010720
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010721 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000010722 OpenMPDirectiveKind CaptureRegion =
10723 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
10724 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010725 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010726 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010727 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10728 HelperValStmt = buildPreInits(Context, Captures);
10729 }
10730
10731 return new (Context) OMPNumThreadsClause(
10732 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000010733}
10734
Alexey Bataev62c87d22014-03-21 04:51:18 +000010735ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010736 OpenMPClauseKind CKind,
10737 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000010738 if (!E)
10739 return ExprError();
10740 if (E->isValueDependent() || E->isTypeDependent() ||
10741 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010742 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010743 llvm::APSInt Result;
10744 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
10745 if (ICE.isInvalid())
10746 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010747 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
10748 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000010749 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010750 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
10751 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000010752 return ExprError();
10753 }
Alexander Musman09184fe2014-09-30 05:29:28 +000010754 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
10755 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
10756 << E->getSourceRange();
10757 return ExprError();
10758 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010759 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
10760 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000010761 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010762 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000010763 return ICE;
10764}
10765
10766OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
10767 SourceLocation LParenLoc,
10768 SourceLocation EndLoc) {
10769 // OpenMP [2.8.1, simd construct, Description]
10770 // The parameter of the safelen clause must be a constant
10771 // positive integer expression.
10772 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
10773 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010774 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010775 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010776 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000010777}
10778
Alexey Bataev66b15b52015-08-21 11:14:16 +000010779OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
10780 SourceLocation LParenLoc,
10781 SourceLocation EndLoc) {
10782 // OpenMP [2.8.1, simd construct, Description]
10783 // The parameter of the simdlen clause must be a constant
10784 // positive integer expression.
10785 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
10786 if (Simdlen.isInvalid())
10787 return nullptr;
10788 return new (Context)
10789 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
10790}
10791
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010792/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010793static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
10794 DSAStackTy *Stack) {
10795 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010796 if (!OMPAllocatorHandleT.isNull())
10797 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010798 // Build the predefined allocator expressions.
10799 bool ErrorFound = false;
10800 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
10801 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
10802 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
10803 StringRef Allocator =
10804 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
10805 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
10806 auto *VD = dyn_cast_or_null<ValueDecl>(
10807 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
10808 if (!VD) {
10809 ErrorFound = true;
10810 break;
10811 }
10812 QualType AllocatorType =
10813 VD->getType().getNonLValueExprType(S.getASTContext());
10814 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
10815 if (!Res.isUsable()) {
10816 ErrorFound = true;
10817 break;
10818 }
10819 if (OMPAllocatorHandleT.isNull())
10820 OMPAllocatorHandleT = AllocatorType;
10821 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
10822 ErrorFound = true;
10823 break;
10824 }
10825 Stack->setAllocator(AllocatorKind, Res.get());
10826 }
10827 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010828 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
10829 return false;
10830 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000010831 OMPAllocatorHandleT.addConst();
10832 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010833 return true;
10834}
10835
10836OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
10837 SourceLocation LParenLoc,
10838 SourceLocation EndLoc) {
10839 // OpenMP [2.11.3, allocate Directive, Description]
10840 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010841 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010842 return nullptr;
10843
10844 ExprResult Allocator = DefaultLvalueConversion(A);
10845 if (Allocator.isInvalid())
10846 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010847 Allocator = PerformImplicitConversion(Allocator.get(),
10848 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010849 Sema::AA_Initializing,
10850 /*AllowExplicit=*/true);
10851 if (Allocator.isInvalid())
10852 return nullptr;
10853 return new (Context)
10854 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
10855}
10856
Alexander Musman64d33f12014-06-04 07:53:32 +000010857OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
10858 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000010859 SourceLocation LParenLoc,
10860 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000010861 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010862 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000010863 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010864 // The parameter of the collapse clause must be a constant
10865 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000010866 ExprResult NumForLoopsResult =
10867 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
10868 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000010869 return nullptr;
10870 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000010871 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000010872}
10873
Alexey Bataev10e775f2015-07-30 11:36:16 +000010874OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
10875 SourceLocation EndLoc,
10876 SourceLocation LParenLoc,
10877 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000010878 // OpenMP [2.7.1, loop construct, Description]
10879 // OpenMP [2.8.1, simd construct, Description]
10880 // OpenMP [2.9.6, distribute construct, Description]
10881 // The parameter of the ordered clause must be a constant
10882 // positive integer expression if any.
10883 if (NumForLoops && LParenLoc.isValid()) {
10884 ExprResult NumForLoopsResult =
10885 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
10886 if (NumForLoopsResult.isInvalid())
10887 return nullptr;
10888 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010889 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000010890 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010891 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000010892 auto *Clause = OMPOrderedClause::Create(
10893 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
10894 StartLoc, LParenLoc, EndLoc);
10895 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
10896 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010897}
10898
Alexey Bataeved09d242014-05-28 05:53:51 +000010899OMPClause *Sema::ActOnOpenMPSimpleClause(
10900 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
10901 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010902 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010903 switch (Kind) {
10904 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010905 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000010906 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
10907 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010908 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010909 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000010910 Res = ActOnOpenMPProcBindClause(
10911 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
10912 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010913 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010914 case OMPC_atomic_default_mem_order:
10915 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
10916 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
10917 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10918 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010919 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010920 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010921 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010922 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010923 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010924 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010925 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010926 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010927 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010928 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010929 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010930 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010931 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010932 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010933 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010934 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010935 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010936 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010937 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010938 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010939 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010940 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010941 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010942 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010943 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010944 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010945 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010946 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010947 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010948 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010949 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010950 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010951 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010952 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010953 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010954 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010955 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010956 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010957 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010958 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010959 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010960 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010961 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010962 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010963 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010964 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010965 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010966 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010967 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010968 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010969 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010970 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010971 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010972 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010973 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000010974 case OMPC_device_type:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010975 llvm_unreachable("Clause is not allowed.");
10976 }
10977 return Res;
10978}
10979
Alexey Bataev6402bca2015-12-28 07:25:51 +000010980static std::string
10981getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
10982 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010983 SmallString<256> Buffer;
10984 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000010985 unsigned Bound = Last >= 2 ? Last - 2 : 0;
10986 unsigned Skipped = Exclude.size();
10987 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000010988 for (unsigned I = First; I < Last; ++I) {
10989 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010990 --Skipped;
10991 continue;
10992 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010993 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
10994 if (I == Bound - Skipped)
10995 Out << " or ";
10996 else if (I != Bound + 1 - Skipped)
10997 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000010998 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010999 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011000}
11001
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011002OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11003 SourceLocation KindKwLoc,
11004 SourceLocation StartLoc,
11005 SourceLocation LParenLoc,
11006 SourceLocation EndLoc) {
11007 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011008 static_assert(OMPC_DEFAULT_unknown > 0,
11009 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011010 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011011 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11012 /*Last=*/OMPC_DEFAULT_unknown)
11013 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011014 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011015 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011016 switch (Kind) {
11017 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011018 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011019 break;
11020 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011021 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011022 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011023 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011024 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011025 break;
11026 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011027 return new (Context)
11028 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011029}
11030
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011031OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11032 SourceLocation KindKwLoc,
11033 SourceLocation StartLoc,
11034 SourceLocation LParenLoc,
11035 SourceLocation EndLoc) {
11036 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011037 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011038 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11039 /*Last=*/OMPC_PROC_BIND_unknown)
11040 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011041 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011042 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011043 return new (Context)
11044 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011045}
11046
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011047OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11048 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11049 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11050 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11051 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11052 << getListOfPossibleValues(
11053 OMPC_atomic_default_mem_order, /*First=*/0,
11054 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11055 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11056 return nullptr;
11057 }
11058 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11059 LParenLoc, EndLoc);
11060}
11061
Alexey Bataev56dafe82014-06-20 07:16:17 +000011062OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011063 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011064 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011065 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011066 SourceLocation EndLoc) {
11067 OMPClause *Res = nullptr;
11068 switch (Kind) {
11069 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011070 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11071 assert(Argument.size() == NumberOfElements &&
11072 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011073 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011074 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11075 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11076 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11077 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11078 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011079 break;
11080 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011081 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11082 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11083 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11084 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011085 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011086 case OMPC_dist_schedule:
11087 Res = ActOnOpenMPDistScheduleClause(
11088 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11089 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11090 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011091 case OMPC_defaultmap:
11092 enum { Modifier, DefaultmapKind };
11093 Res = ActOnOpenMPDefaultmapClause(
11094 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11095 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011096 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11097 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011098 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011099 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011100 case OMPC_num_threads:
11101 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011102 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011103 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011104 case OMPC_collapse:
11105 case OMPC_default:
11106 case OMPC_proc_bind:
11107 case OMPC_private:
11108 case OMPC_firstprivate:
11109 case OMPC_lastprivate:
11110 case OMPC_shared:
11111 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011112 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011113 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011114 case OMPC_linear:
11115 case OMPC_aligned:
11116 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011117 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011118 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011119 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011120 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011121 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011122 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011123 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011124 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011125 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011126 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011127 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011128 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011129 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011130 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011131 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011132 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011133 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011134 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011135 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011136 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011137 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011138 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011139 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011140 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011141 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011142 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011143 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011144 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011145 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011146 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011147 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011148 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011149 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011150 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011151 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011152 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011153 case OMPC_device_type:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011154 llvm_unreachable("Clause is not allowed.");
11155 }
11156 return Res;
11157}
11158
Alexey Bataev6402bca2015-12-28 07:25:51 +000011159static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11160 OpenMPScheduleClauseModifier M2,
11161 SourceLocation M1Loc, SourceLocation M2Loc) {
11162 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11163 SmallVector<unsigned, 2> Excluded;
11164 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11165 Excluded.push_back(M2);
11166 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11167 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11168 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11169 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11170 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11171 << getListOfPossibleValues(OMPC_schedule,
11172 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11173 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11174 Excluded)
11175 << getOpenMPClauseName(OMPC_schedule);
11176 return true;
11177 }
11178 return false;
11179}
11180
Alexey Bataev56dafe82014-06-20 07:16:17 +000011181OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011182 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011183 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011184 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11185 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11186 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11187 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11188 return nullptr;
11189 // OpenMP, 2.7.1, Loop Construct, Restrictions
11190 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11191 // but not both.
11192 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11193 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11194 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11195 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11196 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11197 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11198 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11199 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11200 return nullptr;
11201 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011202 if (Kind == OMPC_SCHEDULE_unknown) {
11203 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011204 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11205 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11206 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11207 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11208 Exclude);
11209 } else {
11210 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11211 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011212 }
11213 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11214 << Values << getOpenMPClauseName(OMPC_schedule);
11215 return nullptr;
11216 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011217 // OpenMP, 2.7.1, Loop Construct, Restrictions
11218 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11219 // schedule(guided).
11220 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11221 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11222 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11223 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11224 diag::err_omp_schedule_nonmonotonic_static);
11225 return nullptr;
11226 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011227 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011228 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011229 if (ChunkSize) {
11230 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11231 !ChunkSize->isInstantiationDependent() &&
11232 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011233 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011234 ExprResult Val =
11235 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11236 if (Val.isInvalid())
11237 return nullptr;
11238
11239 ValExpr = Val.get();
11240
11241 // OpenMP [2.7.1, Restrictions]
11242 // chunk_size must be a loop invariant integer expression with a positive
11243 // value.
11244 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000011245 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11246 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11247 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011248 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000011249 return nullptr;
11250 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000011251 } else if (getOpenMPCaptureRegionForClause(
11252 DSAStack->getCurrentDirective(), OMPC_schedule) !=
11253 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011254 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011255 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011256 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000011257 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11258 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011259 }
11260 }
11261 }
11262
Alexey Bataev6402bca2015-12-28 07:25:51 +000011263 return new (Context)
11264 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000011265 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011266}
11267
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011268OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
11269 SourceLocation StartLoc,
11270 SourceLocation EndLoc) {
11271 OMPClause *Res = nullptr;
11272 switch (Kind) {
11273 case OMPC_ordered:
11274 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
11275 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000011276 case OMPC_nowait:
11277 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
11278 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011279 case OMPC_untied:
11280 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
11281 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011282 case OMPC_mergeable:
11283 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
11284 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011285 case OMPC_read:
11286 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
11287 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000011288 case OMPC_write:
11289 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
11290 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000011291 case OMPC_update:
11292 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
11293 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000011294 case OMPC_capture:
11295 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
11296 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011297 case OMPC_seq_cst:
11298 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
11299 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000011300 case OMPC_threads:
11301 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
11302 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011303 case OMPC_simd:
11304 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
11305 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000011306 case OMPC_nogroup:
11307 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
11308 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011309 case OMPC_unified_address:
11310 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
11311 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011312 case OMPC_unified_shared_memory:
11313 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11314 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011315 case OMPC_reverse_offload:
11316 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
11317 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011318 case OMPC_dynamic_allocators:
11319 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
11320 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011321 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011322 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011323 case OMPC_num_threads:
11324 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011325 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011326 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011327 case OMPC_collapse:
11328 case OMPC_schedule:
11329 case OMPC_private:
11330 case OMPC_firstprivate:
11331 case OMPC_lastprivate:
11332 case OMPC_shared:
11333 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011334 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011335 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011336 case OMPC_linear:
11337 case OMPC_aligned:
11338 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011339 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011340 case OMPC_default:
11341 case OMPC_proc_bind:
11342 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011343 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011344 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011345 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011346 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011347 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011348 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011349 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011350 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011351 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000011352 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011353 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011354 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011355 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011356 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011357 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011358 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011359 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011360 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011361 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011362 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011363 case OMPC_device_type:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011364 llvm_unreachable("Clause is not allowed.");
11365 }
11366 return Res;
11367}
11368
Alexey Bataev236070f2014-06-20 11:19:47 +000011369OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11370 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000011371 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000011372 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
11373}
11374
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011375OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11376 SourceLocation EndLoc) {
11377 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
11378}
11379
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011380OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11381 SourceLocation EndLoc) {
11382 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
11383}
11384
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011385OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
11386 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011387 return new (Context) OMPReadClause(StartLoc, EndLoc);
11388}
11389
Alexey Bataevdea47612014-07-23 07:46:59 +000011390OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
11391 SourceLocation EndLoc) {
11392 return new (Context) OMPWriteClause(StartLoc, EndLoc);
11393}
11394
Alexey Bataev67a4f222014-07-23 10:25:33 +000011395OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11396 SourceLocation EndLoc) {
11397 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
11398}
11399
Alexey Bataev459dec02014-07-24 06:46:57 +000011400OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11401 SourceLocation EndLoc) {
11402 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
11403}
11404
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011405OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11406 SourceLocation EndLoc) {
11407 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
11408}
11409
Alexey Bataev346265e2015-09-25 10:37:12 +000011410OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11411 SourceLocation EndLoc) {
11412 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
11413}
11414
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011415OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11416 SourceLocation EndLoc) {
11417 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
11418}
11419
Alexey Bataevb825de12015-12-07 10:51:44 +000011420OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11421 SourceLocation EndLoc) {
11422 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
11423}
11424
Kelvin Li1408f912018-09-26 04:28:39 +000011425OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11426 SourceLocation EndLoc) {
11427 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
11428}
11429
Patrick Lyster4a370b92018-10-01 13:47:43 +000011430OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11431 SourceLocation EndLoc) {
11432 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11433}
11434
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011435OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11436 SourceLocation EndLoc) {
11437 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
11438}
11439
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011440OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11441 SourceLocation EndLoc) {
11442 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
11443}
11444
Alexey Bataevc5e02582014-06-16 07:08:35 +000011445OMPClause *Sema::ActOnOpenMPVarListClause(
11446 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011447 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11448 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11449 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000011450 OpenMPLinearClauseKind LinKind,
11451 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011452 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
11453 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
11454 SourceLocation StartLoc = Locs.StartLoc;
11455 SourceLocation LParenLoc = Locs.LParenLoc;
11456 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011457 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011458 switch (Kind) {
11459 case OMPC_private:
11460 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11461 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011462 case OMPC_firstprivate:
11463 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11464 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011465 case OMPC_lastprivate:
11466 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11467 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011468 case OMPC_shared:
11469 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
11470 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011471 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000011472 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011473 EndLoc, ReductionOrMapperIdScopeSpec,
11474 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011475 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000011476 case OMPC_task_reduction:
11477 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011478 EndLoc, ReductionOrMapperIdScopeSpec,
11479 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000011480 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000011481 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011482 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11483 EndLoc, ReductionOrMapperIdScopeSpec,
11484 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000011485 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000011486 case OMPC_linear:
11487 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011488 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000011489 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011490 case OMPC_aligned:
11491 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
11492 ColonLoc, EndLoc);
11493 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011494 case OMPC_copyin:
11495 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
11496 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011497 case OMPC_copyprivate:
11498 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11499 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000011500 case OMPC_flush:
11501 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
11502 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011503 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000011504 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011505 StartLoc, LParenLoc, EndLoc);
11506 break;
11507 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011508 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
11509 ReductionOrMapperIdScopeSpec,
11510 ReductionOrMapperId, MapType, IsMapTypeImplicit,
11511 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011512 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011513 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000011514 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
11515 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000011516 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000011517 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000011518 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
11519 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000011520 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000011521 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011522 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011523 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000011524 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011525 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011526 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000011527 case OMPC_allocate:
11528 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
11529 ColonLoc, EndLoc);
11530 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011531 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011532 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011533 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011534 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011535 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011536 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011537 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011538 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011539 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011540 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011541 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011542 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011543 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011544 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011545 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011546 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011547 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011548 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011549 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011550 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000011551 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011552 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011553 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011554 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011555 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011556 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011557 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011558 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011559 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011560 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011561 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011562 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011563 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011564 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000011565 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011566 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011567 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011568 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011569 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011570 case OMPC_device_type:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011571 llvm_unreachable("Clause is not allowed.");
11572 }
11573 return Res;
11574}
11575
Alexey Bataev90c228f2016-02-08 09:29:13 +000011576ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000011577 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000011578 ExprResult Res = BuildDeclRefExpr(
11579 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
11580 if (!Res.isUsable())
11581 return ExprError();
11582 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
11583 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
11584 if (!Res.isUsable())
11585 return ExprError();
11586 }
11587 if (VK != VK_LValue && Res.get()->isGLValue()) {
11588 Res = DefaultLvalueConversion(Res.get());
11589 if (!Res.isUsable())
11590 return ExprError();
11591 }
11592 return Res;
11593}
11594
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011595OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11596 SourceLocation StartLoc,
11597 SourceLocation LParenLoc,
11598 SourceLocation EndLoc) {
11599 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000011600 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000011601 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011602 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011603 SourceLocation ELoc;
11604 SourceRange ERange;
11605 Expr *SimpleRefExpr = RefExpr;
11606 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000011607 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011608 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011609 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011610 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011611 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011612 ValueDecl *D = Res.first;
11613 if (!D)
11614 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011615
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011616 QualType Type = D->getType();
11617 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011618
11619 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11620 // A variable that appears in a private clause must not have an incomplete
11621 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011622 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011623 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011624 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011625
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011626 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11627 // A variable that is privatized must not have a const-qualified type
11628 // unless it is of class type with a mutable member. This restriction does
11629 // not apply to the firstprivate clause.
11630 //
11631 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
11632 // A variable that appears in a private clause must not have a
11633 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011634 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011635 continue;
11636
Alexey Bataev758e55e2013-09-06 18:03:48 +000011637 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11638 // in a Construct]
11639 // Variables with the predetermined data-sharing attributes may not be
11640 // listed in data-sharing attributes clauses, except for the cases
11641 // listed below. For these exceptions only, listing a predetermined
11642 // variable in a data-sharing attribute clause is allowed and overrides
11643 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011644 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011645 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011646 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11647 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000011648 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011649 continue;
11650 }
11651
Alexey Bataeve3727102018-04-18 15:57:46 +000011652 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011653 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011654 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000011655 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011656 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11657 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000011658 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011659 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011660 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011661 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011662 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011663 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011664 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011665 continue;
11666 }
11667
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011668 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11669 // A list item cannot appear in both a map clause and a data-sharing
11670 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000011671 //
11672 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
11673 // A list item cannot appear in both a map clause and a data-sharing
11674 // attribute clause on the same construct unless the construct is a
11675 // combined construct.
11676 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
11677 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000011678 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011679 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011680 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011681 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
11682 OpenMPClauseKind WhereFoundClauseKind) -> bool {
11683 ConflictKind = WhereFoundClauseKind;
11684 return true;
11685 })) {
11686 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011687 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000011688 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000011689 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000011690 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011691 continue;
11692 }
11693 }
11694
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011695 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
11696 // A variable of class type (or array thereof) that appears in a private
11697 // clause requires an accessible, unambiguous default constructor for the
11698 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000011699 // Generate helper private variable and initialize it with the default
11700 // value. The address of the original variable is replaced by the address of
11701 // the new private variable in CodeGen. This new variable is not added to
11702 // IdResolver, so the code in the OpenMP region uses original variable for
11703 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011704 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011705 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011706 buildVarDecl(*this, ELoc, Type, D->getName(),
11707 D->hasAttrs() ? &D->getAttrs() : nullptr,
11708 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000011709 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011710 if (VDPrivate->isInvalidDecl())
11711 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000011712 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011713 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011714
Alexey Bataev90c228f2016-02-08 09:29:13 +000011715 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011716 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000011717 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000011718 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011719 Vars.push_back((VD || CurContext->isDependentContext())
11720 ? RefExpr->IgnoreParens()
11721 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011722 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011723 }
11724
Alexey Bataeved09d242014-05-28 05:53:51 +000011725 if (Vars.empty())
11726 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011727
Alexey Bataev03b340a2014-10-21 03:16:40 +000011728 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11729 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011730}
11731
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011732namespace {
11733class DiagsUninitializedSeveretyRAII {
11734private:
11735 DiagnosticsEngine &Diags;
11736 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000011737 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011738
11739public:
11740 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
11741 bool IsIgnored)
11742 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
11743 if (!IsIgnored) {
11744 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
11745 /*Map*/ diag::Severity::Ignored, Loc);
11746 }
11747 }
11748 ~DiagsUninitializedSeveretyRAII() {
11749 if (!IsIgnored)
11750 Diags.popMappings(SavedLoc);
11751 }
11752};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011753}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011754
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011755OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11756 SourceLocation StartLoc,
11757 SourceLocation LParenLoc,
11758 SourceLocation EndLoc) {
11759 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011760 SmallVector<Expr *, 8> PrivateCopies;
11761 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000011762 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011763 bool IsImplicitClause =
11764 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000011765 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011766
Alexey Bataeve3727102018-04-18 15:57:46 +000011767 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011768 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011769 SourceLocation ELoc;
11770 SourceRange ERange;
11771 Expr *SimpleRefExpr = RefExpr;
11772 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000011773 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011774 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011775 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011776 PrivateCopies.push_back(nullptr);
11777 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011778 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011779 ValueDecl *D = Res.first;
11780 if (!D)
11781 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011782
Alexey Bataev60da77e2016-02-29 05:54:20 +000011783 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011784 QualType Type = D->getType();
11785 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011786
11787 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11788 // A variable that appears in a private clause must not have an incomplete
11789 // type or a reference type.
11790 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000011791 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011792 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011793 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011794
11795 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
11796 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000011797 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011798 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011799 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011800
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011801 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000011802 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011803 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011804 DSAStackTy::DSAVarData DVar =
11805 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000011806 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011807 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011808 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011809 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
11810 // A list item that specifies a given variable may not appear in more
11811 // than one clause on the same directive, except that a variable may be
11812 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011813 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11814 // A list item may appear in a firstprivate or lastprivate clause but not
11815 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011816 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011817 (isOpenMPDistributeDirective(CurrDir) ||
11818 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011819 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011820 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011821 << getOpenMPClauseName(DVar.CKind)
11822 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011823 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011824 continue;
11825 }
11826
11827 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11828 // in a Construct]
11829 // Variables with the predetermined data-sharing attributes may not be
11830 // listed in data-sharing attributes clauses, except for the cases
11831 // listed below. For these exceptions only, listing a predetermined
11832 // variable in a data-sharing attribute clause is allowed and overrides
11833 // the variable's predetermined data-sharing attributes.
11834 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11835 // in a Construct, C/C++, p.2]
11836 // Variables with const-qualified type having no mutable member may be
11837 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000011838 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011839 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
11840 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011841 << getOpenMPClauseName(DVar.CKind)
11842 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011843 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011844 continue;
11845 }
11846
11847 // OpenMP [2.9.3.4, Restrictions, p.2]
11848 // A list item that is private within a parallel region must not appear
11849 // in a firstprivate clause on a worksharing construct if any of the
11850 // worksharing regions arising from the worksharing construct ever bind
11851 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011852 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11853 // A list item that is private within a teams region must not appear in a
11854 // firstprivate clause on a distribute construct if any of the distribute
11855 // regions arising from the distribute construct ever bind to any of the
11856 // teams regions arising from the teams construct.
11857 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11858 // A list item that appears in a reduction clause of a teams construct
11859 // must not appear in a firstprivate clause on a distribute construct if
11860 // any of the distribute regions arising from the distribute construct
11861 // ever bind to any of the teams regions arising from the teams construct.
11862 if ((isOpenMPWorksharingDirective(CurrDir) ||
11863 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011864 !isOpenMPParallelDirective(CurrDir) &&
11865 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011866 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011867 if (DVar.CKind != OMPC_shared &&
11868 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011869 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011870 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000011871 Diag(ELoc, diag::err_omp_required_access)
11872 << getOpenMPClauseName(OMPC_firstprivate)
11873 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011874 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011875 continue;
11876 }
11877 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011878 // OpenMP [2.9.3.4, Restrictions, p.3]
11879 // A list item that appears in a reduction clause of a parallel construct
11880 // must not appear in a firstprivate clause on a worksharing or task
11881 // construct if any of the worksharing or task regions arising from the
11882 // worksharing or task construct ever bind to any of the parallel regions
11883 // arising from the parallel construct.
11884 // OpenMP [2.9.3.4, Restrictions, p.4]
11885 // A list item that appears in a reduction clause in worksharing
11886 // construct must not appear in a firstprivate clause in a task construct
11887 // encountered during execution of any of the worksharing regions arising
11888 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000011889 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011890 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011891 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
11892 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011893 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011894 isOpenMPWorksharingDirective(K) ||
11895 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011896 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011897 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011898 if (DVar.CKind == OMPC_reduction &&
11899 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011900 isOpenMPWorksharingDirective(DVar.DKind) ||
11901 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011902 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
11903 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000011904 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011905 continue;
11906 }
11907 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000011908
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011909 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11910 // A list item cannot appear in both a map clause and a data-sharing
11911 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000011912 //
11913 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
11914 // A list item cannot appear in both a map clause and a data-sharing
11915 // attribute clause on the same construct unless the construct is a
11916 // combined construct.
11917 if ((LangOpts.OpenMP <= 45 &&
11918 isOpenMPTargetExecutionDirective(CurrDir)) ||
11919 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000011920 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011921 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011922 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000011923 [&ConflictKind](
11924 OMPClauseMappableExprCommon::MappableExprComponentListRef,
11925 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000011926 ConflictKind = WhereFoundClauseKind;
11927 return true;
11928 })) {
11929 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011930 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000011931 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011932 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000011933 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011934 continue;
11935 }
11936 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011937 }
11938
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011939 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011940 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000011941 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011942 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11943 << getOpenMPClauseName(OMPC_firstprivate) << Type
11944 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11945 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011946 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011947 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011948 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011949 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000011950 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011951 continue;
11952 }
11953
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011954 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011955 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011956 buildVarDecl(*this, ELoc, Type, D->getName(),
11957 D->hasAttrs() ? &D->getAttrs() : nullptr,
11958 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011959 // Generate helper private variable and initialize it with the value of the
11960 // original variable. The address of the original variable is replaced by
11961 // the address of the new private variable in the CodeGen. This new variable
11962 // is not added to IdResolver, so the code in the OpenMP region uses
11963 // original variable for proper diagnostics and variable capturing.
11964 Expr *VDInitRefExpr = nullptr;
11965 // For arrays generate initializer for single element and replace it by the
11966 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011967 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011968 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011969 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011970 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011971 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011972 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011973 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
11974 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000011975 InitializedEntity Entity =
11976 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011977 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
11978
11979 InitializationSequence InitSeq(*this, Entity, Kind, Init);
11980 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
11981 if (Result.isInvalid())
11982 VDPrivate->setInvalidDecl();
11983 else
11984 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011985 // Remove temp variable declaration.
11986 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011987 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000011988 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
11989 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000011990 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11991 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000011992 AddInitializerToDecl(VDPrivate,
11993 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011994 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011995 }
11996 if (VDPrivate->isInvalidDecl()) {
11997 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011998 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011999 diag::note_omp_task_predetermined_firstprivate_here);
12000 }
12001 continue;
12002 }
12003 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012004 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012005 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12006 RefExpr->getExprLoc());
12007 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012008 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012009 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012010 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012011 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012012 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012013 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012014 ExprCaptures.push_back(Ref->getDecl());
12015 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012016 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012017 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012018 Vars.push_back((VD || CurContext->isDependentContext())
12019 ? RefExpr->IgnoreParens()
12020 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012021 PrivateCopies.push_back(VDPrivateRefExpr);
12022 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012023 }
12024
Alexey Bataeved09d242014-05-28 05:53:51 +000012025 if (Vars.empty())
12026 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012027
12028 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012029 Vars, PrivateCopies, Inits,
12030 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012031}
12032
Alexander Musman1bb328c2014-06-04 13:06:39 +000012033OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12034 SourceLocation StartLoc,
12035 SourceLocation LParenLoc,
12036 SourceLocation EndLoc) {
12037 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012038 SmallVector<Expr *, 8> SrcExprs;
12039 SmallVector<Expr *, 8> DstExprs;
12040 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012041 SmallVector<Decl *, 4> ExprCaptures;
12042 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012043 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012044 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012045 SourceLocation ELoc;
12046 SourceRange ERange;
12047 Expr *SimpleRefExpr = RefExpr;
12048 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012049 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012050 // It will be analyzed later.
12051 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012052 SrcExprs.push_back(nullptr);
12053 DstExprs.push_back(nullptr);
12054 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012055 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012056 ValueDecl *D = Res.first;
12057 if (!D)
12058 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012059
Alexey Bataev74caaf22016-02-20 04:09:36 +000012060 QualType Type = D->getType();
12061 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012062
12063 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12064 // A variable that appears in a lastprivate clause must not have an
12065 // incomplete type or a reference type.
12066 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012067 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012068 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012069 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012070
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012071 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12072 // A variable that is privatized must not have a const-qualified type
12073 // unless it is of class type with a mutable member. This restriction does
12074 // not apply to the firstprivate clause.
12075 //
12076 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12077 // A variable that appears in a lastprivate clause must not have a
12078 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012079 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012080 continue;
12081
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012082 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012083 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12084 // in a Construct]
12085 // Variables with the predetermined data-sharing attributes may not be
12086 // listed in data-sharing attributes clauses, except for the cases
12087 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012088 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12089 // A list item may appear in a firstprivate or lastprivate clause but not
12090 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012091 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012092 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012093 (isOpenMPDistributeDirective(CurrDir) ||
12094 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012095 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12096 Diag(ELoc, diag::err_omp_wrong_dsa)
12097 << getOpenMPClauseName(DVar.CKind)
12098 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012099 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012100 continue;
12101 }
12102
Alexey Bataevf29276e2014-06-18 04:14:57 +000012103 // OpenMP [2.14.3.5, Restrictions, p.2]
12104 // A list item that is private within a parallel region, or that appears in
12105 // the reduction clause of a parallel construct, must not appear in a
12106 // lastprivate clause on a worksharing construct if any of the corresponding
12107 // worksharing regions ever binds to any of the corresponding parallel
12108 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012109 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012110 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012111 !isOpenMPParallelDirective(CurrDir) &&
12112 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012113 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012114 if (DVar.CKind != OMPC_shared) {
12115 Diag(ELoc, diag::err_omp_required_access)
12116 << getOpenMPClauseName(OMPC_lastprivate)
12117 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012118 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012119 continue;
12120 }
12121 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012122
Alexander Musman1bb328c2014-06-04 13:06:39 +000012123 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012124 // A variable of class type (or array thereof) that appears in a
12125 // lastprivate clause requires an accessible, unambiguous default
12126 // constructor for the class type, unless the list item is also specified
12127 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012128 // A variable of class type (or array thereof) that appears in a
12129 // lastprivate clause requires an accessible, unambiguous copy assignment
12130 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012131 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012132 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12133 Type.getUnqualifiedType(), ".lastprivate.src",
12134 D->hasAttrs() ? &D->getAttrs() : nullptr);
12135 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012136 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012137 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012138 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012139 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012140 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012141 // For arrays generate assignment operation for single element and replace
12142 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012143 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12144 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012145 if (AssignmentOp.isInvalid())
12146 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012147 AssignmentOp =
12148 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012149 if (AssignmentOp.isInvalid())
12150 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012151
Alexey Bataev74caaf22016-02-20 04:09:36 +000012152 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012153 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012154 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012155 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012156 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012157 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012158 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012159 ExprCaptures.push_back(Ref->getDecl());
12160 }
12161 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012162 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012163 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012164 ExprResult RefRes = DefaultLvalueConversion(Ref);
12165 if (!RefRes.isUsable())
12166 continue;
12167 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012168 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12169 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012170 if (!PostUpdateRes.isUsable())
12171 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012172 ExprPostUpdates.push_back(
12173 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012174 }
12175 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012176 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012177 Vars.push_back((VD || CurContext->isDependentContext())
12178 ? RefExpr->IgnoreParens()
12179 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012180 SrcExprs.push_back(PseudoSrcExpr);
12181 DstExprs.push_back(PseudoDstExpr);
12182 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012183 }
12184
12185 if (Vars.empty())
12186 return nullptr;
12187
12188 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012189 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012190 buildPreInits(Context, ExprCaptures),
12191 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012192}
12193
Alexey Bataev758e55e2013-09-06 18:03:48 +000012194OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12195 SourceLocation StartLoc,
12196 SourceLocation LParenLoc,
12197 SourceLocation EndLoc) {
12198 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012199 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012200 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012201 SourceLocation ELoc;
12202 SourceRange ERange;
12203 Expr *SimpleRefExpr = RefExpr;
12204 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012205 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012206 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012207 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012208 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012209 ValueDecl *D = Res.first;
12210 if (!D)
12211 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012212
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012213 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12215 // in a Construct]
12216 // Variables with the predetermined data-sharing attributes may not be
12217 // listed in data-sharing attributes clauses, except for the cases
12218 // listed below. For these exceptions only, listing a predetermined
12219 // variable in a data-sharing attribute clause is allowed and overrides
12220 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012221 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012222 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12223 DVar.RefExpr) {
12224 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12225 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012226 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012227 continue;
12228 }
12229
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012230 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012231 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012232 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012233 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012234 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12235 ? RefExpr->IgnoreParens()
12236 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012237 }
12238
Alexey Bataeved09d242014-05-28 05:53:51 +000012239 if (Vars.empty())
12240 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012241
12242 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12243}
12244
Alexey Bataevc5e02582014-06-16 07:08:35 +000012245namespace {
12246class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12247 DSAStackTy *Stack;
12248
12249public:
12250 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012251 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12252 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012253 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12254 return false;
12255 if (DVar.CKind != OMPC_unknown)
12256 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012257 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012258 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012259 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012260 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012261 }
12262 return false;
12263 }
12264 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012265 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012266 if (Child && Visit(Child))
12267 return true;
12268 }
12269 return false;
12270 }
Alexey Bataev23b69422014-06-18 07:08:49 +000012271 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012272};
Alexey Bataev23b69422014-06-18 07:08:49 +000012273} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000012274
Alexey Bataev60da77e2016-02-29 05:54:20 +000012275namespace {
12276// Transform MemberExpression for specified FieldDecl of current class to
12277// DeclRefExpr to specified OMPCapturedExprDecl.
12278class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
12279 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000012280 ValueDecl *Field = nullptr;
12281 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012282
12283public:
12284 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
12285 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
12286
12287 ExprResult TransformMemberExpr(MemberExpr *E) {
12288 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
12289 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000012290 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012291 return CapturedExpr;
12292 }
12293 return BaseTransform::TransformMemberExpr(E);
12294 }
12295 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
12296};
12297} // namespace
12298
Alexey Bataev97d18bf2018-04-11 19:21:00 +000012299template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000012300static T filterLookupForUDReductionAndMapper(
12301 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012302 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012303 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012304 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012305 return Res;
12306 }
12307 }
12308 return T();
12309}
12310
Alexey Bataev43b90b72018-09-12 16:31:59 +000012311static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
12312 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
12313
12314 for (auto RD : D->redecls()) {
12315 // Don't bother with extra checks if we already know this one isn't visible.
12316 if (RD == D)
12317 continue;
12318
12319 auto ND = cast<NamedDecl>(RD);
12320 if (LookupResult::isVisible(SemaRef, ND))
12321 return ND;
12322 }
12323
12324 return nullptr;
12325}
12326
12327static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000012328argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000012329 SourceLocation Loc, QualType Ty,
12330 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
12331 // Find all of the associated namespaces and classes based on the
12332 // arguments we have.
12333 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12334 Sema::AssociatedClassSet AssociatedClasses;
12335 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
12336 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
12337 AssociatedClasses);
12338
12339 // C++ [basic.lookup.argdep]p3:
12340 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12341 // and let Y be the lookup set produced by argument dependent
12342 // lookup (defined as follows). If X contains [...] then Y is
12343 // empty. Otherwise Y is the set of declarations found in the
12344 // namespaces associated with the argument types as described
12345 // below. The set of declarations found by the lookup of the name
12346 // is the union of X and Y.
12347 //
12348 // Here, we compute Y and add its members to the overloaded
12349 // candidate set.
12350 for (auto *NS : AssociatedNamespaces) {
12351 // When considering an associated namespace, the lookup is the
12352 // same as the lookup performed when the associated namespace is
12353 // used as a qualifier (3.4.3.2) except that:
12354 //
12355 // -- Any using-directives in the associated namespace are
12356 // ignored.
12357 //
12358 // -- Any namespace-scope friend functions declared in
12359 // associated classes are visible within their respective
12360 // namespaces even if they are not visible during an ordinary
12361 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000012362 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000012363 for (auto *D : R) {
12364 auto *Underlying = D;
12365 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12366 Underlying = USD->getTargetDecl();
12367
Michael Kruse4304e9d2019-02-19 16:38:20 +000012368 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
12369 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000012370 continue;
12371
12372 if (!SemaRef.isVisible(D)) {
12373 D = findAcceptableDecl(SemaRef, D);
12374 if (!D)
12375 continue;
12376 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12377 Underlying = USD->getTargetDecl();
12378 }
12379 Lookups.emplace_back();
12380 Lookups.back().addDecl(Underlying);
12381 }
12382 }
12383}
12384
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012385static ExprResult
12386buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
12387 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
12388 const DeclarationNameInfo &ReductionId, QualType Ty,
12389 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
12390 if (ReductionIdScopeSpec.isInvalid())
12391 return ExprError();
12392 SmallVector<UnresolvedSet<8>, 4> Lookups;
12393 if (S) {
12394 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12395 Lookup.suppressDiagnostics();
12396 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012397 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012398 do {
12399 S = S->getParent();
12400 } while (S && !S->isDeclScope(D));
12401 if (S)
12402 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000012403 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012404 Lookups.back().append(Lookup.begin(), Lookup.end());
12405 Lookup.clear();
12406 }
12407 } else if (auto *ULE =
12408 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
12409 Lookups.push_back(UnresolvedSet<8>());
12410 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012411 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012412 if (D == PrevD)
12413 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000012414 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012415 Lookups.back().addDecl(DRD);
12416 PrevD = D;
12417 }
12418 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000012419 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
12420 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012421 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000012422 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012423 return !D->isInvalidDecl() &&
12424 (D->getType()->isDependentType() ||
12425 D->getType()->isInstantiationDependentType() ||
12426 D->getType()->containsUnexpandedParameterPack());
12427 })) {
12428 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000012429 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000012430 if (Set.empty())
12431 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012432 ResSet.append(Set.begin(), Set.end());
12433 // The last item marks the end of all declarations at the specified scope.
12434 ResSet.addDecl(Set[Set.size() - 1]);
12435 }
12436 return UnresolvedLookupExpr::Create(
12437 SemaRef.Context, /*NamingClass=*/nullptr,
12438 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
12439 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
12440 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000012441 // Lookup inside the classes.
12442 // C++ [over.match.oper]p3:
12443 // For a unary operator @ with an operand of a type whose
12444 // cv-unqualified version is T1, and for a binary operator @ with
12445 // a left operand of a type whose cv-unqualified version is T1 and
12446 // a right operand of a type whose cv-unqualified version is T2,
12447 // three sets of candidate functions, designated member
12448 // candidates, non-member candidates and built-in candidates, are
12449 // constructed as follows:
12450 // -- If T1 is a complete class type or a class currently being
12451 // defined, the set of member candidates is the result of the
12452 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
12453 // the set of member candidates is empty.
12454 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12455 Lookup.suppressDiagnostics();
12456 if (const auto *TyRec = Ty->getAs<RecordType>()) {
12457 // Complete the type if it can be completed.
12458 // If the type is neither complete nor being defined, bail out now.
12459 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
12460 TyRec->getDecl()->getDefinition()) {
12461 Lookup.clear();
12462 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
12463 if (Lookup.empty()) {
12464 Lookups.emplace_back();
12465 Lookups.back().append(Lookup.begin(), Lookup.end());
12466 }
12467 }
12468 }
12469 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000012470 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000012471 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000012472 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12473 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
12474 if (!D->isInvalidDecl() &&
12475 SemaRef.Context.hasSameType(D->getType(), Ty))
12476 return D;
12477 return nullptr;
12478 }))
12479 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
12480 VK_LValue, Loc);
12481 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000012482 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12483 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
12484 if (!D->isInvalidDecl() &&
12485 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
12486 !Ty.isMoreQualifiedThan(D->getType()))
12487 return D;
12488 return nullptr;
12489 })) {
12490 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
12491 /*DetectVirtual=*/false);
12492 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
12493 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
12494 VD->getType().getUnqualifiedType()))) {
12495 if (SemaRef.CheckBaseClassAccess(
12496 Loc, VD->getType(), Ty, Paths.front(),
12497 /*DiagID=*/0) != Sema::AR_inaccessible) {
12498 SemaRef.BuildBasePathArray(Paths, BasePath);
12499 return SemaRef.BuildDeclRefExpr(
12500 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
12501 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012502 }
12503 }
12504 }
12505 }
12506 if (ReductionIdScopeSpec.isSet()) {
12507 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
12508 return ExprError();
12509 }
12510 return ExprEmpty();
12511}
12512
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012513namespace {
12514/// Data for the reduction-based clauses.
12515struct ReductionData {
12516 /// List of original reduction items.
12517 SmallVector<Expr *, 8> Vars;
12518 /// List of private copies of the reduction items.
12519 SmallVector<Expr *, 8> Privates;
12520 /// LHS expressions for the reduction_op expressions.
12521 SmallVector<Expr *, 8> LHSs;
12522 /// RHS expressions for the reduction_op expressions.
12523 SmallVector<Expr *, 8> RHSs;
12524 /// Reduction operation expression.
12525 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000012526 /// Taskgroup descriptors for the corresponding reduction items in
12527 /// in_reduction clauses.
12528 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012529 /// List of captures for clause.
12530 SmallVector<Decl *, 4> ExprCaptures;
12531 /// List of postupdate expressions.
12532 SmallVector<Expr *, 4> ExprPostUpdates;
12533 ReductionData() = delete;
12534 /// Reserves required memory for the reduction data.
12535 ReductionData(unsigned Size) {
12536 Vars.reserve(Size);
12537 Privates.reserve(Size);
12538 LHSs.reserve(Size);
12539 RHSs.reserve(Size);
12540 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000012541 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012542 ExprCaptures.reserve(Size);
12543 ExprPostUpdates.reserve(Size);
12544 }
12545 /// Stores reduction item and reduction operation only (required for dependent
12546 /// reduction item).
12547 void push(Expr *Item, Expr *ReductionOp) {
12548 Vars.emplace_back(Item);
12549 Privates.emplace_back(nullptr);
12550 LHSs.emplace_back(nullptr);
12551 RHSs.emplace_back(nullptr);
12552 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012553 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012554 }
12555 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000012556 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
12557 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012558 Vars.emplace_back(Item);
12559 Privates.emplace_back(Private);
12560 LHSs.emplace_back(LHS);
12561 RHSs.emplace_back(RHS);
12562 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012563 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012564 }
12565};
12566} // namespace
12567
Alexey Bataeve3727102018-04-18 15:57:46 +000012568static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012569 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
12570 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
12571 const Expr *Length = OASE->getLength();
12572 if (Length == nullptr) {
12573 // For array sections of the form [1:] or [:], we would need to analyze
12574 // the lower bound...
12575 if (OASE->getColonLoc().isValid())
12576 return false;
12577
12578 // This is an array subscript which has implicit length 1!
12579 SingleElement = true;
12580 ArraySizes.push_back(llvm::APSInt::get(1));
12581 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012582 Expr::EvalResult Result;
12583 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012584 return false;
12585
Fangrui Song407659a2018-11-30 23:41:18 +000012586 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012587 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
12588 ArraySizes.push_back(ConstantLengthValue);
12589 }
12590
12591 // Get the base of this array section and walk up from there.
12592 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
12593
12594 // We require length = 1 for all array sections except the right-most to
12595 // guarantee that the memory region is contiguous and has no holes in it.
12596 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
12597 Length = TempOASE->getLength();
12598 if (Length == nullptr) {
12599 // For array sections of the form [1:] or [:], we would need to analyze
12600 // the lower bound...
12601 if (OASE->getColonLoc().isValid())
12602 return false;
12603
12604 // This is an array subscript which has implicit length 1!
12605 ArraySizes.push_back(llvm::APSInt::get(1));
12606 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012607 Expr::EvalResult Result;
12608 if (!Length->EvaluateAsInt(Result, Context))
12609 return false;
12610
12611 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
12612 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012613 return false;
12614
12615 ArraySizes.push_back(ConstantLengthValue);
12616 }
12617 Base = TempOASE->getBase()->IgnoreParenImpCasts();
12618 }
12619
12620 // If we have a single element, we don't need to add the implicit lengths.
12621 if (!SingleElement) {
12622 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
12623 // Has implicit length 1!
12624 ArraySizes.push_back(llvm::APSInt::get(1));
12625 Base = TempASE->getBase()->IgnoreParenImpCasts();
12626 }
12627 }
12628
12629 // This array section can be privatized as a single value or as a constant
12630 // sized array.
12631 return true;
12632}
12633
Alexey Bataeve3727102018-04-18 15:57:46 +000012634static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000012635 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
12636 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12637 SourceLocation ColonLoc, SourceLocation EndLoc,
12638 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012639 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012640 DeclarationName DN = ReductionId.getName();
12641 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012642 BinaryOperatorKind BOK = BO_Comma;
12643
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012644 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012645 // OpenMP [2.14.3.6, reduction clause]
12646 // C
12647 // reduction-identifier is either an identifier or one of the following
12648 // operators: +, -, *, &, |, ^, && and ||
12649 // C++
12650 // reduction-identifier is either an id-expression or one of the following
12651 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000012652 switch (OOK) {
12653 case OO_Plus:
12654 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012655 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012656 break;
12657 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012658 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012659 break;
12660 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012661 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012662 break;
12663 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012664 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012665 break;
12666 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012667 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012668 break;
12669 case OO_AmpAmp:
12670 BOK = BO_LAnd;
12671 break;
12672 case OO_PipePipe:
12673 BOK = BO_LOr;
12674 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012675 case OO_New:
12676 case OO_Delete:
12677 case OO_Array_New:
12678 case OO_Array_Delete:
12679 case OO_Slash:
12680 case OO_Percent:
12681 case OO_Tilde:
12682 case OO_Exclaim:
12683 case OO_Equal:
12684 case OO_Less:
12685 case OO_Greater:
12686 case OO_LessEqual:
12687 case OO_GreaterEqual:
12688 case OO_PlusEqual:
12689 case OO_MinusEqual:
12690 case OO_StarEqual:
12691 case OO_SlashEqual:
12692 case OO_PercentEqual:
12693 case OO_CaretEqual:
12694 case OO_AmpEqual:
12695 case OO_PipeEqual:
12696 case OO_LessLess:
12697 case OO_GreaterGreater:
12698 case OO_LessLessEqual:
12699 case OO_GreaterGreaterEqual:
12700 case OO_EqualEqual:
12701 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000012702 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012703 case OO_PlusPlus:
12704 case OO_MinusMinus:
12705 case OO_Comma:
12706 case OO_ArrowStar:
12707 case OO_Arrow:
12708 case OO_Call:
12709 case OO_Subscript:
12710 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000012711 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012712 case NUM_OVERLOADED_OPERATORS:
12713 llvm_unreachable("Unexpected reduction identifier");
12714 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000012715 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012716 if (II->isStr("max"))
12717 BOK = BO_GT;
12718 else if (II->isStr("min"))
12719 BOK = BO_LT;
12720 }
12721 break;
12722 }
12723 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012724 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000012725 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012726 else
12727 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000012728 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000012729
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012730 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
12731 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012732 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012733 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000012734 // OpenMP [2.1, C/C++]
12735 // A list item is a variable or array section, subject to the restrictions
12736 // specified in Section 2.4 on page 42 and in each of the sections
12737 // describing clauses and directives for which a list appears.
12738 // OpenMP [2.14.3.3, Restrictions, p.1]
12739 // A variable that is part of another variable (as an array or
12740 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012741 if (!FirstIter && IR != ER)
12742 ++IR;
12743 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012744 SourceLocation ELoc;
12745 SourceRange ERange;
12746 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012747 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000012748 /*AllowArraySection=*/true);
12749 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012750 // Try to find 'declare reduction' corresponding construct before using
12751 // builtin/overloaded operators.
12752 QualType Type = Context.DependentTy;
12753 CXXCastPath BasePath;
12754 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012755 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012756 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012757 Expr *ReductionOp = nullptr;
12758 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012759 (DeclareReductionRef.isUnset() ||
12760 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012761 ReductionOp = DeclareReductionRef.get();
12762 // It will be analyzed later.
12763 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012764 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012765 ValueDecl *D = Res.first;
12766 if (!D)
12767 continue;
12768
Alexey Bataev88202be2017-07-27 13:20:36 +000012769 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000012770 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012771 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
12772 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000012773 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000012774 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012775 } else if (OASE) {
12776 QualType BaseType =
12777 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
12778 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000012779 Type = ATy->getElementType();
12780 else
12781 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000012782 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012783 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012784 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000012785 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012786 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000012787
Alexey Bataevc5e02582014-06-16 07:08:35 +000012788 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12789 // A variable that appears in a private clause must not have an incomplete
12790 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000012791 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012792 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012793 continue;
12794 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000012795 // A list item that appears in a reduction clause must not be
12796 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012797 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
12798 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012799 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000012800
12801 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012802 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
12803 // If a list-item is a reference type then it must bind to the same object
12804 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000012805 if (!ASE && !OASE) {
12806 if (VD) {
12807 VarDecl *VDDef = VD->getDefinition();
12808 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
12809 DSARefChecker Check(Stack);
12810 if (Check.Visit(VDDef->getInit())) {
12811 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
12812 << getOpenMPClauseName(ClauseKind) << ERange;
12813 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
12814 continue;
12815 }
Alexey Bataeva1764212015-09-30 09:22:36 +000012816 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000012817 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012818
Alexey Bataevbc529672018-09-28 19:33:14 +000012819 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12820 // in a Construct]
12821 // Variables with the predetermined data-sharing attributes may not be
12822 // listed in data-sharing attributes clauses, except for the cases
12823 // listed below. For these exceptions only, listing a predetermined
12824 // variable in a data-sharing attribute clause is allowed and overrides
12825 // the variable's predetermined data-sharing attributes.
12826 // OpenMP [2.14.3.6, Restrictions, p.3]
12827 // Any number of reduction clauses can be specified on the directive,
12828 // but a list item can appear only once in the reduction clauses for that
12829 // directive.
12830 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
12831 if (DVar.CKind == OMPC_reduction) {
12832 S.Diag(ELoc, diag::err_omp_once_referenced)
12833 << getOpenMPClauseName(ClauseKind);
12834 if (DVar.RefExpr)
12835 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
12836 continue;
12837 }
12838 if (DVar.CKind != OMPC_unknown) {
12839 S.Diag(ELoc, diag::err_omp_wrong_dsa)
12840 << getOpenMPClauseName(DVar.CKind)
12841 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000012842 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012843 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000012844 }
Alexey Bataevbc529672018-09-28 19:33:14 +000012845
12846 // OpenMP [2.14.3.6, Restrictions, p.1]
12847 // A list item that appears in a reduction clause of a worksharing
12848 // construct must be shared in the parallel regions to which any of the
12849 // worksharing regions arising from the worksharing construct bind.
12850 if (isOpenMPWorksharingDirective(CurrDir) &&
12851 !isOpenMPParallelDirective(CurrDir) &&
12852 !isOpenMPTeamsDirective(CurrDir)) {
12853 DVar = Stack->getImplicitDSA(D, true);
12854 if (DVar.CKind != OMPC_shared) {
12855 S.Diag(ELoc, diag::err_omp_required_access)
12856 << getOpenMPClauseName(OMPC_reduction)
12857 << getOpenMPClauseName(OMPC_shared);
12858 reportOriginalDsa(S, Stack, D, DVar);
12859 continue;
12860 }
12861 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000012862 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012863
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012864 // Try to find 'declare reduction' corresponding construct before using
12865 // builtin/overloaded operators.
12866 CXXCastPath BasePath;
12867 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012868 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012869 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
12870 if (DeclareReductionRef.isInvalid())
12871 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012872 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012873 (DeclareReductionRef.isUnset() ||
12874 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012875 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012876 continue;
12877 }
12878 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
12879 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012880 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012881 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012882 << Type << ReductionIdRange;
12883 continue;
12884 }
12885
12886 // OpenMP [2.14.3.6, reduction clause, Restrictions]
12887 // The type of a list item that appears in a reduction clause must be valid
12888 // for the reduction-identifier. For a max or min reduction in C, the type
12889 // of the list item must be an allowed arithmetic data type: char, int,
12890 // float, double, or _Bool, possibly modified with long, short, signed, or
12891 // unsigned. For a max or min reduction in C++, the type of the list item
12892 // must be an allowed arithmetic data type: char, wchar_t, int, float,
12893 // double, or bool, possibly modified with long, short, signed, or unsigned.
12894 if (DeclareReductionRef.isUnset()) {
12895 if ((BOK == BO_GT || BOK == BO_LT) &&
12896 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012897 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
12898 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000012899 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012900 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012901 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12902 VarDecl::DeclarationOnly;
12903 S.Diag(D->getLocation(),
12904 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012905 << D;
12906 }
12907 continue;
12908 }
12909 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012910 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000012911 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
12912 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012913 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012914 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12915 VarDecl::DeclarationOnly;
12916 S.Diag(D->getLocation(),
12917 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012918 << D;
12919 }
12920 continue;
12921 }
12922 }
12923
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012924 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012925 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
12926 D->hasAttrs() ? &D->getAttrs() : nullptr);
12927 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
12928 D->hasAttrs() ? &D->getAttrs() : nullptr);
12929 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012930
12931 // Try if we can determine constant lengths for all array sections and avoid
12932 // the VLA.
12933 bool ConstantLengthOASE = false;
12934 if (OASE) {
12935 bool SingleElement;
12936 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000012937 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012938 Context, OASE, SingleElement, ArraySizes);
12939
12940 // If we don't have a single element, we must emit a constant array type.
12941 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012942 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012943 PrivateTy = Context.getConstantArrayType(
12944 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012945 }
12946 }
12947
12948 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000012949 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000012950 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000012951 if (!Context.getTargetInfo().isVLASupported()) {
12952 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
12953 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12954 S.Diag(ELoc, diag::note_vla_unsupported);
12955 } else {
12956 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12957 S.targetDiag(ELoc, diag::note_vla_unsupported);
12958 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000012959 continue;
12960 }
David Majnemer9d168222016-08-05 17:44:54 +000012961 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012962 // Create pseudo array type for private copy. The size for this array will
12963 // be generated during codegen.
12964 // For array subscripts or single variables Private Ty is the same as Type
12965 // (type of the variable or single array element).
12966 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012967 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000012968 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012969 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000012970 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000012971 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012972 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012973 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012974 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012975 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012976 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
12977 D->hasAttrs() ? &D->getAttrs() : nullptr,
12978 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012979 // Add initializer for private variable.
12980 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012981 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
12982 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012983 if (DeclareReductionRef.isUsable()) {
12984 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
12985 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
12986 if (DRD->getInitializer()) {
12987 Init = DRDRef;
12988 RHSVD->setInit(DRDRef);
12989 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012990 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012991 } else {
12992 switch (BOK) {
12993 case BO_Add:
12994 case BO_Xor:
12995 case BO_Or:
12996 case BO_LOr:
12997 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
12998 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012999 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013000 break;
13001 case BO_Mul:
13002 case BO_LAnd:
13003 if (Type->isScalarType() || Type->isAnyComplexType()) {
13004 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013005 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013006 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013007 break;
13008 case BO_And: {
13009 // '&' reduction op - initializer is '~0'.
13010 QualType OrigType = Type;
13011 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13012 Type = ComplexTy->getElementType();
13013 if (Type->isRealFloatingType()) {
13014 llvm::APFloat InitValue =
13015 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13016 /*isIEEE=*/true);
13017 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13018 Type, ELoc);
13019 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013020 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013021 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13022 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13023 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13024 }
13025 if (Init && OrigType->isAnyComplexType()) {
13026 // Init = 0xFFFF + 0xFFFFi;
13027 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013028 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013029 }
13030 Type = OrigType;
13031 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013032 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013033 case BO_LT:
13034 case BO_GT: {
13035 // 'min' reduction op - initializer is 'Largest representable number in
13036 // the reduction list item type'.
13037 // 'max' reduction op - initializer is 'Least representable number in
13038 // the reduction list item type'.
13039 if (Type->isIntegerType() || Type->isPointerType()) {
13040 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013041 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013042 QualType IntTy =
13043 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13044 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013045 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13046 : llvm::APInt::getMinValue(Size)
13047 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13048 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013049 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13050 if (Type->isPointerType()) {
13051 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013052 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013053 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013054 if (CastExpr.isInvalid())
13055 continue;
13056 Init = CastExpr.get();
13057 }
13058 } else if (Type->isRealFloatingType()) {
13059 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13060 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13061 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13062 Type, ELoc);
13063 }
13064 break;
13065 }
13066 case BO_PtrMemD:
13067 case BO_PtrMemI:
13068 case BO_MulAssign:
13069 case BO_Div:
13070 case BO_Rem:
13071 case BO_Sub:
13072 case BO_Shl:
13073 case BO_Shr:
13074 case BO_LE:
13075 case BO_GE:
13076 case BO_EQ:
13077 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013078 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013079 case BO_AndAssign:
13080 case BO_XorAssign:
13081 case BO_OrAssign:
13082 case BO_Assign:
13083 case BO_AddAssign:
13084 case BO_SubAssign:
13085 case BO_DivAssign:
13086 case BO_RemAssign:
13087 case BO_ShlAssign:
13088 case BO_ShrAssign:
13089 case BO_Comma:
13090 llvm_unreachable("Unexpected reduction operation");
13091 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013092 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013093 if (Init && DeclareReductionRef.isUnset())
13094 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13095 else if (!Init)
13096 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013097 if (RHSVD->isInvalidDecl())
13098 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013099 if (!RHSVD->hasInit() &&
13100 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013101 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13102 << Type << ReductionIdRange;
13103 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13104 VarDecl::DeclarationOnly;
13105 S.Diag(D->getLocation(),
13106 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013107 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013108 continue;
13109 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013110 // Store initializer for single element in private copy. Will be used during
13111 // codegen.
13112 PrivateVD->setInit(RHSVD->getInit());
13113 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013114 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013115 ExprResult ReductionOp;
13116 if (DeclareReductionRef.isUsable()) {
13117 QualType RedTy = DeclareReductionRef.get()->getType();
13118 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013119 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13120 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013121 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013122 LHS = S.DefaultLvalueConversion(LHS.get());
13123 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013124 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13125 CK_UncheckedDerivedToBase, LHS.get(),
13126 &BasePath, LHS.get()->getValueKind());
13127 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13128 CK_UncheckedDerivedToBase, RHS.get(),
13129 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013130 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013131 FunctionProtoType::ExtProtoInfo EPI;
13132 QualType Params[] = {PtrRedTy, PtrRedTy};
13133 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13134 auto *OVE = new (Context) OpaqueValueExpr(
13135 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013136 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013137 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013138 ReductionOp =
13139 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013140 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013141 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013142 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013143 if (ReductionOp.isUsable()) {
13144 if (BOK != BO_LT && BOK != BO_GT) {
13145 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013146 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013147 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013148 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013149 auto *ConditionalOp = new (Context)
13150 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13151 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013152 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013153 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013154 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013155 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013156 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013157 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13158 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013159 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013160 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013161 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013162 }
13163
Alexey Bataevfa312f32017-07-21 18:48:21 +000013164 // OpenMP [2.15.4.6, Restrictions, p.2]
13165 // A list item that appears in an in_reduction clause of a task construct
13166 // must appear in a task_reduction clause of a construct associated with a
13167 // taskgroup region that includes the participating task in its taskgroup
13168 // set. The construct associated with the innermost region that meets this
13169 // condition must specify the same reduction-identifier as the in_reduction
13170 // clause.
13171 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013172 SourceRange ParentSR;
13173 BinaryOperatorKind ParentBOK;
13174 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013175 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013176 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013177 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13178 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013179 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013180 Stack->getTopMostTaskgroupReductionData(
13181 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013182 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13183 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13184 if (!IsParentBOK && !IsParentReductionOp) {
13185 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13186 continue;
13187 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013188 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13189 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13190 IsParentReductionOp) {
13191 bool EmitError = true;
13192 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13193 llvm::FoldingSetNodeID RedId, ParentRedId;
13194 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13195 DeclareReductionRef.get()->Profile(RedId, Context,
13196 /*Canonical=*/true);
13197 EmitError = RedId != ParentRedId;
13198 }
13199 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013200 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013201 diag::err_omp_reduction_identifier_mismatch)
13202 << ReductionIdRange << RefExpr->getSourceRange();
13203 S.Diag(ParentSR.getBegin(),
13204 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013205 << ParentSR
13206 << (IsParentBOK ? ParentBOKDSA.RefExpr
13207 : ParentReductionOpDSA.RefExpr)
13208 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013209 continue;
13210 }
13211 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013212 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13213 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013214 }
13215
Alexey Bataev60da77e2016-02-29 05:54:20 +000013216 DeclRefExpr *Ref = nullptr;
13217 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013218 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013219 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013220 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013221 VarsExpr =
13222 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13223 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013224 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013225 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013226 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013227 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013228 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013229 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013230 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013231 if (!RefRes.isUsable())
13232 continue;
13233 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013234 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13235 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013236 if (!PostUpdateRes.isUsable())
13237 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013238 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13239 Stack->getCurrentDirective() == OMPD_taskgroup) {
13240 S.Diag(RefExpr->getExprLoc(),
13241 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000013242 << RefExpr->getSourceRange();
13243 continue;
13244 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013245 RD.ExprPostUpdates.emplace_back(
13246 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000013247 }
13248 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013249 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000013250 // All reduction items are still marked as reduction (to do not increase
13251 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013252 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013253 if (CurrDir == OMPD_taskgroup) {
13254 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013255 Stack->addTaskgroupReductionData(D, ReductionIdRange,
13256 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000013257 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013258 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013259 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013260 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
13261 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013262 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013263 return RD.Vars.empty();
13264}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013265
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013266OMPClause *Sema::ActOnOpenMPReductionClause(
13267 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13268 SourceLocation ColonLoc, SourceLocation EndLoc,
13269 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13270 ArrayRef<Expr *> UnresolvedReductions) {
13271 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013272 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013273 StartLoc, LParenLoc, ColonLoc, EndLoc,
13274 ReductionIdScopeSpec, ReductionId,
13275 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013276 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000013277
Alexey Bataevc5e02582014-06-16 07:08:35 +000013278 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013279 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13280 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13281 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13282 buildPreInits(Context, RD.ExprCaptures),
13283 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000013284}
13285
Alexey Bataev169d96a2017-07-18 20:17:46 +000013286OMPClause *Sema::ActOnOpenMPTaskReductionClause(
13287 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13288 SourceLocation ColonLoc, SourceLocation EndLoc,
13289 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13290 ArrayRef<Expr *> UnresolvedReductions) {
13291 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013292 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
13293 StartLoc, LParenLoc, ColonLoc, EndLoc,
13294 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013295 UnresolvedReductions, RD))
13296 return nullptr;
13297
13298 return OMPTaskReductionClause::Create(
13299 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13300 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13301 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13302 buildPreInits(Context, RD.ExprCaptures),
13303 buildPostUpdate(*this, RD.ExprPostUpdates));
13304}
13305
Alexey Bataevfa312f32017-07-21 18:48:21 +000013306OMPClause *Sema::ActOnOpenMPInReductionClause(
13307 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13308 SourceLocation ColonLoc, SourceLocation EndLoc,
13309 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13310 ArrayRef<Expr *> UnresolvedReductions) {
13311 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013312 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013313 StartLoc, LParenLoc, ColonLoc, EndLoc,
13314 ReductionIdScopeSpec, ReductionId,
13315 UnresolvedReductions, RD))
13316 return nullptr;
13317
13318 return OMPInReductionClause::Create(
13319 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13320 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000013321 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013322 buildPreInits(Context, RD.ExprCaptures),
13323 buildPostUpdate(*this, RD.ExprPostUpdates));
13324}
13325
Alexey Bataevecba70f2016-04-12 11:02:11 +000013326bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
13327 SourceLocation LinLoc) {
13328 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
13329 LinKind == OMPC_LINEAR_unknown) {
13330 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
13331 return true;
13332 }
13333 return false;
13334}
13335
Alexey Bataeve3727102018-04-18 15:57:46 +000013336bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000013337 OpenMPLinearClauseKind LinKind,
13338 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013339 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000013340 // A variable must not have an incomplete type or a reference type.
13341 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
13342 return true;
13343 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
13344 !Type->isReferenceType()) {
13345 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
13346 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
13347 return true;
13348 }
13349 Type = Type.getNonReferenceType();
13350
Joel E. Dennybae586f2019-01-04 22:12:13 +000013351 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13352 // A variable that is privatized must not have a const-qualified type
13353 // unless it is of class type with a mutable member. This restriction does
13354 // not apply to the firstprivate clause.
13355 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000013356 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013357
13358 // A list item must be of integral or pointer type.
13359 Type = Type.getUnqualifiedType().getCanonicalType();
13360 const auto *Ty = Type.getTypePtrOrNull();
13361 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
13362 !Ty->isPointerType())) {
13363 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
13364 if (D) {
13365 bool IsDecl =
13366 !VD ||
13367 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13368 Diag(D->getLocation(),
13369 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13370 << D;
13371 }
13372 return true;
13373 }
13374 return false;
13375}
13376
Alexey Bataev182227b2015-08-20 10:54:39 +000013377OMPClause *Sema::ActOnOpenMPLinearClause(
13378 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
13379 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
13380 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013381 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013382 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000013383 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013384 SmallVector<Decl *, 4> ExprCaptures;
13385 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013386 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000013387 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000013388 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013389 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013390 SourceLocation ELoc;
13391 SourceRange ERange;
13392 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013393 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013394 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013395 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013396 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013397 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013398 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000013399 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013400 ValueDecl *D = Res.first;
13401 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000013402 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000013403
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013404 QualType Type = D->getType();
13405 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000013406
13407 // OpenMP [2.14.3.7, linear clause]
13408 // A list-item cannot appear in more than one linear clause.
13409 // A list-item that appears in a linear clause cannot appear in any
13410 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013411 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000013412 if (DVar.RefExpr) {
13413 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13414 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000013415 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000013416 continue;
13417 }
13418
Alexey Bataevecba70f2016-04-12 11:02:11 +000013419 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000013420 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013421 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000013422
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013423 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000013424 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013425 buildVarDecl(*this, ELoc, Type, D->getName(),
13426 D->hasAttrs() ? &D->getAttrs() : nullptr,
13427 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013428 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013429 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013430 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013431 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013432 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013433 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013434 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013435 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013436 ExprCaptures.push_back(Ref->getDecl());
13437 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13438 ExprResult RefRes = DefaultLvalueConversion(Ref);
13439 if (!RefRes.isUsable())
13440 continue;
13441 ExprResult PostUpdateRes =
13442 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
13443 SimpleRefExpr, RefRes.get());
13444 if (!PostUpdateRes.isUsable())
13445 continue;
13446 ExprPostUpdates.push_back(
13447 IgnoredValueConversions(PostUpdateRes.get()).get());
13448 }
13449 }
13450 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013451 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013452 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013453 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013454 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013455 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013456 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013457 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013458
13459 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013460 Vars.push_back((VD || CurContext->isDependentContext())
13461 ? RefExpr->IgnoreParens()
13462 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013463 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000013464 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000013465 }
13466
13467 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013468 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013469
13470 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000013471 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013472 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
13473 !Step->isInstantiationDependent() &&
13474 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013475 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000013476 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000013477 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013478 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013479 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000013480
Alexander Musman3276a272015-03-21 10:12:56 +000013481 // Build var to save the step value.
13482 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013483 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000013484 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013485 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013486 ExprResult CalcStep =
13487 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013488 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013489
Alexander Musman8dba6642014-04-22 13:09:42 +000013490 // Warn about zero linear step (it would be probably better specified as
13491 // making corresponding variables 'const').
13492 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000013493 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
13494 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000013495 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
13496 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000013497 if (!IsConstant && CalcStep.isUsable()) {
13498 // Calculate the step beforehand instead of doing this on each iteration.
13499 // (This is not used if the number of iterations may be kfold-ed).
13500 CalcStepExpr = CalcStep.get();
13501 }
Alexander Musman8dba6642014-04-22 13:09:42 +000013502 }
13503
Alexey Bataev182227b2015-08-20 10:54:39 +000013504 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
13505 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013506 StepExpr, CalcStepExpr,
13507 buildPreInits(Context, ExprCaptures),
13508 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000013509}
13510
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013511static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
13512 Expr *NumIterations, Sema &SemaRef,
13513 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000013514 // Walk the vars and build update/final expressions for the CodeGen.
13515 SmallVector<Expr *, 8> Updates;
13516 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000013517 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000013518 Expr *Step = Clause.getStep();
13519 Expr *CalcStep = Clause.getCalcStep();
13520 // OpenMP [2.14.3.7, linear clause]
13521 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000013522 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000013523 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013524 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000013525 Step = cast<BinaryOperator>(CalcStep)->getLHS();
13526 bool HasErrors = false;
13527 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013528 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000013529 OpenMPLinearClauseKind LinKind = Clause.getModifier();
13530 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013531 SourceLocation ELoc;
13532 SourceRange ERange;
13533 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013534 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013535 ValueDecl *D = Res.first;
13536 if (Res.second || !D) {
13537 Updates.push_back(nullptr);
13538 Finals.push_back(nullptr);
13539 HasErrors = true;
13540 continue;
13541 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013542 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000013543 // OpenMP [2.15.11, distribute simd Construct]
13544 // A list item may not appear in a linear clause, unless it is the loop
13545 // iteration variable.
13546 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
13547 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
13548 SemaRef.Diag(ELoc,
13549 diag::err_omp_linear_distribute_var_non_loop_iteration);
13550 Updates.push_back(nullptr);
13551 Finals.push_back(nullptr);
13552 HasErrors = true;
13553 continue;
13554 }
Alexander Musman3276a272015-03-21 10:12:56 +000013555 Expr *InitExpr = *CurInit;
13556
13557 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000013558 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013559 Expr *CapturedRef;
13560 if (LinKind == OMPC_LINEAR_uval)
13561 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
13562 else
13563 CapturedRef =
13564 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
13565 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
13566 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000013567
13568 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013569 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000013570 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000013571 Update = buildCounterUpdate(
13572 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
13573 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013574 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013575 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013576 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013577 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013578
13579 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013580 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000013581 if (!Info.first)
13582 Final =
13583 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000013584 InitExpr, NumIterations, Step, /*Subtract=*/false,
13585 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013586 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013587 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013588 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013589 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013590
Alexander Musman3276a272015-03-21 10:12:56 +000013591 if (!Update.isUsable() || !Final.isUsable()) {
13592 Updates.push_back(nullptr);
13593 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000013594 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013595 HasErrors = true;
13596 } else {
13597 Updates.push_back(Update.get());
13598 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000013599 if (!Info.first)
13600 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000013601 }
Richard Trieucc3949d2016-02-18 22:34:54 +000013602 ++CurInit;
13603 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000013604 }
Alexey Bataev195ae902019-08-08 13:42:45 +000013605 if (Expr *S = Clause.getStep())
13606 UsedExprs.push_back(S);
13607 // Fill the remaining part with the nullptr.
13608 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013609 Clause.setUpdates(Updates);
13610 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000013611 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000013612 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000013613}
13614
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013615OMPClause *Sema::ActOnOpenMPAlignedClause(
13616 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
13617 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013618 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013619 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000013620 assert(RefExpr && "NULL expr in OpenMP linear clause.");
13621 SourceLocation ELoc;
13622 SourceRange ERange;
13623 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013624 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000013625 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013626 // It will be analyzed later.
13627 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013628 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000013629 ValueDecl *D = Res.first;
13630 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013631 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013632
Alexey Bataev1efd1662016-03-29 10:59:56 +000013633 QualType QType = D->getType();
13634 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013635
13636 // OpenMP [2.8.1, simd construct, Restrictions]
13637 // The type of list items appearing in the aligned clause must be
13638 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013639 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013640 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000013641 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013642 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000013643 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013644 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000013645 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013646 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000013647 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013648 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000013649 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013650 continue;
13651 }
13652
13653 // OpenMP [2.8.1, simd construct, Restrictions]
13654 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013655 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000013656 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013657 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
13658 << getOpenMPClauseName(OMPC_aligned);
13659 continue;
13660 }
13661
Alexey Bataev1efd1662016-03-29 10:59:56 +000013662 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013663 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000013664 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13665 Vars.push_back(DefaultFunctionArrayConversion(
13666 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
13667 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013668 }
13669
13670 // OpenMP [2.8.1, simd construct, Description]
13671 // The parameter of the aligned clause, alignment, must be a constant
13672 // positive integer expression.
13673 // If no optional parameter is specified, implementation-defined default
13674 // alignments for SIMD instructions on the target platforms are assumed.
13675 if (Alignment != nullptr) {
13676 ExprResult AlignResult =
13677 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
13678 if (AlignResult.isInvalid())
13679 return nullptr;
13680 Alignment = AlignResult.get();
13681 }
13682 if (Vars.empty())
13683 return nullptr;
13684
13685 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
13686 EndLoc, Vars, Alignment);
13687}
13688
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013689OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
13690 SourceLocation StartLoc,
13691 SourceLocation LParenLoc,
13692 SourceLocation EndLoc) {
13693 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013694 SmallVector<Expr *, 8> SrcExprs;
13695 SmallVector<Expr *, 8> DstExprs;
13696 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000013697 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013698 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
13699 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013700 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013701 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013702 SrcExprs.push_back(nullptr);
13703 DstExprs.push_back(nullptr);
13704 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013705 continue;
13706 }
13707
Alexey Bataeved09d242014-05-28 05:53:51 +000013708 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013709 // OpenMP [2.1, C/C++]
13710 // A list item is a variable name.
13711 // OpenMP [2.14.4.1, Restrictions, p.1]
13712 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000013713 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013714 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013715 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
13716 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013717 continue;
13718 }
13719
13720 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013721 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013722
13723 QualType Type = VD->getType();
13724 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
13725 // It will be analyzed later.
13726 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013727 SrcExprs.push_back(nullptr);
13728 DstExprs.push_back(nullptr);
13729 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013730 continue;
13731 }
13732
13733 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
13734 // A list item that appears in a copyin clause must be threadprivate.
13735 if (!DSAStack->isThreadPrivate(VD)) {
13736 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000013737 << getOpenMPClauseName(OMPC_copyin)
13738 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013739 continue;
13740 }
13741
13742 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13743 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000013744 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013745 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013746 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
13747 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013748 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000013749 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013750 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013751 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000013752 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013753 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000013754 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013755 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013756 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013757 // For arrays generate assignment operation for single element and replace
13758 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013759 ExprResult AssignmentOp =
13760 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
13761 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013762 if (AssignmentOp.isInvalid())
13763 continue;
13764 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013765 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013766 if (AssignmentOp.isInvalid())
13767 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013768
13769 DSAStack->addDSA(VD, DE, OMPC_copyin);
13770 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013771 SrcExprs.push_back(PseudoSrcExpr);
13772 DstExprs.push_back(PseudoDstExpr);
13773 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013774 }
13775
Alexey Bataeved09d242014-05-28 05:53:51 +000013776 if (Vars.empty())
13777 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013778
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013779 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
13780 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013781}
13782
Alexey Bataevbae9a792014-06-27 10:37:06 +000013783OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
13784 SourceLocation StartLoc,
13785 SourceLocation LParenLoc,
13786 SourceLocation EndLoc) {
13787 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000013788 SmallVector<Expr *, 8> SrcExprs;
13789 SmallVector<Expr *, 8> DstExprs;
13790 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000013791 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000013792 assert(RefExpr && "NULL expr in OpenMP linear clause.");
13793 SourceLocation ELoc;
13794 SourceRange ERange;
13795 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013796 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000013797 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000013798 // It will be analyzed later.
13799 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013800 SrcExprs.push_back(nullptr);
13801 DstExprs.push_back(nullptr);
13802 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013803 }
Alexey Bataeve122da12016-03-17 10:50:17 +000013804 ValueDecl *D = Res.first;
13805 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000013806 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013807
Alexey Bataeve122da12016-03-17 10:50:17 +000013808 QualType Type = D->getType();
13809 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013810
13811 // OpenMP [2.14.4.2, Restrictions, p.2]
13812 // A list item that appears in a copyprivate clause may not appear in a
13813 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000013814 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013815 DSAStackTy::DSAVarData DVar =
13816 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013817 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
13818 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000013819 Diag(ELoc, diag::err_omp_wrong_dsa)
13820 << getOpenMPClauseName(DVar.CKind)
13821 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013822 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013823 continue;
13824 }
13825
13826 // OpenMP [2.11.4.2, Restrictions, p.1]
13827 // All list items that appear in a copyprivate clause must be either
13828 // threadprivate or private in the enclosing context.
13829 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000013830 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013831 if (DVar.CKind == OMPC_shared) {
13832 Diag(ELoc, diag::err_omp_required_access)
13833 << getOpenMPClauseName(OMPC_copyprivate)
13834 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000013835 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013836 continue;
13837 }
13838 }
13839 }
13840
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013841 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000013842 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013843 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013844 << getOpenMPClauseName(OMPC_copyprivate) << Type
13845 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013846 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000013847 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013848 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000013849 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013850 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000013851 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013852 continue;
13853 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013854
Alexey Bataevbae9a792014-06-27 10:37:06 +000013855 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13856 // A variable of class type (or array thereof) that appears in a
13857 // copyin clause requires an accessible, unambiguous copy assignment
13858 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013859 Type = Context.getBaseElementType(Type.getNonReferenceType())
13860 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013861 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013862 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000013863 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013864 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
13865 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013866 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000013867 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013868 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
13869 ExprResult AssignmentOp = BuildBinOp(
13870 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013871 if (AssignmentOp.isInvalid())
13872 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013873 AssignmentOp =
13874 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013875 if (AssignmentOp.isInvalid())
13876 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013877
13878 // No need to mark vars as copyprivate, they are already threadprivate or
13879 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000013880 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000013881 Vars.push_back(
13882 VD ? RefExpr->IgnoreParens()
13883 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000013884 SrcExprs.push_back(PseudoSrcExpr);
13885 DstExprs.push_back(PseudoDstExpr);
13886 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000013887 }
13888
13889 if (Vars.empty())
13890 return nullptr;
13891
Alexey Bataeva63048e2015-03-23 06:18:07 +000013892 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13893 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013894}
13895
Alexey Bataev6125da92014-07-21 11:26:11 +000013896OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
13897 SourceLocation StartLoc,
13898 SourceLocation LParenLoc,
13899 SourceLocation EndLoc) {
13900 if (VarList.empty())
13901 return nullptr;
13902
13903 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
13904}
Alexey Bataevdea47612014-07-23 07:46:59 +000013905
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013906OMPClause *
13907Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
13908 SourceLocation DepLoc, SourceLocation ColonLoc,
13909 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13910 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013911 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013912 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013913 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013914 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000013915 return nullptr;
13916 }
13917 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013918 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
13919 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000013920 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013921 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013922 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13923 /*Last=*/OMPC_DEPEND_unknown, Except)
13924 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013925 return nullptr;
13926 }
13927 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000013928 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013929 llvm::APSInt DepCounter(/*BitWidth=*/32);
13930 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000013931 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
13932 if (const Expr *OrderedCountExpr =
13933 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013934 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
13935 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013936 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013937 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013938 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000013939 assert(RefExpr && "NULL expr in OpenMP shared clause.");
13940 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
13941 // It will be analyzed later.
13942 Vars.push_back(RefExpr);
13943 continue;
13944 }
13945
13946 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000013947 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000013948 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000013949 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013950 DepCounter >= TotalDepCount) {
13951 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
13952 continue;
13953 }
13954 ++DepCounter;
13955 // OpenMP [2.13.9, Summary]
13956 // depend(dependence-type : vec), where dependence-type is:
13957 // 'sink' and where vec is the iteration vector, which has the form:
13958 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
13959 // where n is the value specified by the ordered clause in the loop
13960 // directive, xi denotes the loop iteration variable of the i-th nested
13961 // loop associated with the loop directive, and di is a constant
13962 // non-negative integer.
13963 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013964 // It will be analyzed later.
13965 Vars.push_back(RefExpr);
13966 continue;
13967 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013968 SimpleExpr = SimpleExpr->IgnoreImplicit();
13969 OverloadedOperatorKind OOK = OO_None;
13970 SourceLocation OOLoc;
13971 Expr *LHS = SimpleExpr;
13972 Expr *RHS = nullptr;
13973 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
13974 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
13975 OOLoc = BO->getOperatorLoc();
13976 LHS = BO->getLHS()->IgnoreParenImpCasts();
13977 RHS = BO->getRHS()->IgnoreParenImpCasts();
13978 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
13979 OOK = OCE->getOperator();
13980 OOLoc = OCE->getOperatorLoc();
13981 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
13982 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
13983 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
13984 OOK = MCE->getMethodDecl()
13985 ->getNameInfo()
13986 .getName()
13987 .getCXXOverloadedOperator();
13988 OOLoc = MCE->getCallee()->getExprLoc();
13989 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
13990 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013991 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013992 SourceLocation ELoc;
13993 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000013994 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013995 if (Res.second) {
13996 // It will be analyzed later.
13997 Vars.push_back(RefExpr);
13998 }
13999 ValueDecl *D = Res.first;
14000 if (!D)
14001 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014002
Alexey Bataev17daedf2018-02-15 22:42:57 +000014003 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14004 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14005 continue;
14006 }
14007 if (RHS) {
14008 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14009 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14010 if (RHSRes.isInvalid())
14011 continue;
14012 }
14013 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014014 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014015 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014016 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014017 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014018 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014019 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14020 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014021 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014022 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014023 continue;
14024 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014025 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014026 } else {
14027 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14028 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14029 (ASE &&
14030 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14031 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14032 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14033 << RefExpr->getSourceRange();
14034 continue;
14035 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014036
14037 ExprResult Res;
14038 {
14039 Sema::TentativeAnalysisScope Trap(*this);
14040 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14041 RefExpr->IgnoreParenImpCasts());
14042 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014043 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14044 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14045 << RefExpr->getSourceRange();
14046 continue;
14047 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014048 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014049 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014050 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014051
14052 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14053 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014054 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014055 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14056 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14057 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14058 }
14059 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14060 Vars.empty())
14061 return nullptr;
14062
Alexey Bataev8b427062016-05-25 12:36:08 +000014063 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014064 DepKind, DepLoc, ColonLoc, Vars,
14065 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014066 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14067 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014068 DSAStack->addDoacrossDependClause(C, OpsOffs);
14069 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014070}
Michael Wonge710d542015-08-07 16:16:36 +000014071
14072OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14073 SourceLocation LParenLoc,
14074 SourceLocation EndLoc) {
14075 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014076 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014077
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014078 // OpenMP [2.9.1, Restrictions]
14079 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014080 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014081 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014082 return nullptr;
14083
Alexey Bataev931e19b2017-10-02 16:32:39 +000014084 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014085 OpenMPDirectiveKind CaptureRegion =
14086 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14087 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014088 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014089 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014090 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14091 HelperValStmt = buildPreInits(Context, Captures);
14092 }
14093
Alexey Bataev8451efa2018-01-15 19:06:12 +000014094 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14095 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014096}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014097
Alexey Bataeve3727102018-04-18 15:57:46 +000014098static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014099 DSAStackTy *Stack, QualType QTy,
14100 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014101 NamedDecl *ND;
14102 if (QTy->isIncompleteType(&ND)) {
14103 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14104 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014105 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014106 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14107 !QTy.isTrivialType(SemaRef.Context))
14108 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014109 return true;
14110}
14111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014112/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014113/// (array section or array subscript) does NOT specify the whole size of the
14114/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014115static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014116 const Expr *E,
14117 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014118 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014119
14120 // If this is an array subscript, it refers to the whole size if the size of
14121 // the dimension is constant and equals 1. Also, an array section assumes the
14122 // format of an array subscript if no colon is used.
14123 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014124 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014125 return ATy->getSize().getSExtValue() != 1;
14126 // Size can't be evaluated statically.
14127 return false;
14128 }
14129
14130 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014131 const Expr *LowerBound = OASE->getLowerBound();
14132 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014133
14134 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014135 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014136 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014137 Expr::EvalResult Result;
14138 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014139 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014140
14141 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014142 if (ConstLowerBound.getSExtValue())
14143 return true;
14144 }
14145
14146 // If we don't have a length we covering the whole dimension.
14147 if (!Length)
14148 return false;
14149
14150 // If the base is a pointer, we don't have a way to get the size of the
14151 // pointee.
14152 if (BaseQTy->isPointerType())
14153 return false;
14154
14155 // We can only check if the length is the same as the size of the dimension
14156 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014157 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014158 if (!CATy)
14159 return false;
14160
Fangrui Song407659a2018-11-30 23:41:18 +000014161 Expr::EvalResult Result;
14162 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014163 return false; // Can't get the integer value as a constant.
14164
Fangrui Song407659a2018-11-30 23:41:18 +000014165 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014166 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14167}
14168
14169// Return true if it can be proven that the provided array expression (array
14170// section or array subscript) does NOT specify a single element of the array
14171// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014172static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014173 const Expr *E,
14174 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014175 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014176
14177 // An array subscript always refer to a single element. Also, an array section
14178 // assumes the format of an array subscript if no colon is used.
14179 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14180 return false;
14181
14182 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014183 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014184
14185 // If we don't have a length we have to check if the array has unitary size
14186 // for this dimension. Also, we should always expect a length if the base type
14187 // is pointer.
14188 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014189 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014190 return ATy->getSize().getSExtValue() != 1;
14191 // We cannot assume anything.
14192 return false;
14193 }
14194
14195 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014196 Expr::EvalResult Result;
14197 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014198 return false; // Can't get the integer value as a constant.
14199
Fangrui Song407659a2018-11-30 23:41:18 +000014200 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014201 return ConstLength.getSExtValue() != 1;
14202}
14203
Samuel Antao661c0902016-05-26 17:39:58 +000014204// Return the expression of the base of the mappable expression or null if it
14205// cannot be determined and do all the necessary checks to see if the expression
14206// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014207// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014208static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014209 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014210 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014211 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014212 SourceLocation ELoc = E->getExprLoc();
14213 SourceRange ERange = E->getSourceRange();
14214
14215 // The base of elements of list in a map clause have to be either:
14216 // - a reference to variable or field.
14217 // - a member expression.
14218 // - an array expression.
14219 //
14220 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14221 // reference to 'r'.
14222 //
14223 // If we have:
14224 //
14225 // struct SS {
14226 // Bla S;
14227 // foo() {
14228 // #pragma omp target map (S.Arr[:12]);
14229 // }
14230 // }
14231 //
14232 // We want to retrieve the member expression 'this->S';
14233
Alexey Bataeve3727102018-04-18 15:57:46 +000014234 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014235
Samuel Antao5de996e2016-01-22 20:21:36 +000014236 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14237 // If a list item is an array section, it must specify contiguous storage.
14238 //
14239 // For this restriction it is sufficient that we make sure only references
14240 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014241 // exist except in the rightmost expression (unless they cover the whole
14242 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000014243 //
14244 // r.ArrS[3:5].Arr[6:7]
14245 //
14246 // r.ArrS[3:5].x
14247 //
14248 // but these would be valid:
14249 // r.ArrS[3].Arr[6:7]
14250 //
14251 // r.ArrS[3].x
14252
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014253 bool AllowUnitySizeArraySection = true;
14254 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014255
Dmitry Polukhin644a9252016-03-11 07:58:34 +000014256 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014257 E = E->IgnoreParenImpCasts();
14258
14259 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
14260 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000014261 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014262
14263 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014264
14265 // If we got a reference to a declaration, we should not expect any array
14266 // section before that.
14267 AllowUnitySizeArraySection = false;
14268 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014269
14270 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014271 CurComponents.emplace_back(CurE, CurE->getDecl());
14272 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014273 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000014274
14275 if (isa<CXXThisExpr>(BaseE))
14276 // We found a base expression: this->Val.
14277 RelevantExpr = CurE;
14278 else
14279 E = BaseE;
14280
14281 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014282 if (!NoDiagnose) {
14283 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
14284 << CurE->getSourceRange();
14285 return nullptr;
14286 }
14287 if (RelevantExpr)
14288 return nullptr;
14289 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014290 }
14291
14292 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
14293
14294 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
14295 // A bit-field cannot appear in a map clause.
14296 //
14297 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014298 if (!NoDiagnose) {
14299 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
14300 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
14301 return nullptr;
14302 }
14303 if (RelevantExpr)
14304 return nullptr;
14305 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014306 }
14307
14308 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14309 // If the type of a list item is a reference to a type T then the type
14310 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014311 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014312
14313 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
14314 // A list item cannot be a variable that is a member of a structure with
14315 // a union type.
14316 //
Alexey Bataeve3727102018-04-18 15:57:46 +000014317 if (CurType->isUnionType()) {
14318 if (!NoDiagnose) {
14319 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
14320 << CurE->getSourceRange();
14321 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014322 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014323 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014324 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014325
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014326 // If we got a member expression, we should not expect any array section
14327 // before that:
14328 //
14329 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
14330 // If a list item is an element of a structure, only the rightmost symbol
14331 // of the variable reference can be an array section.
14332 //
14333 AllowUnitySizeArraySection = false;
14334 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014335
14336 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014337 CurComponents.emplace_back(CurE, FD);
14338 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014339 E = CurE->getBase()->IgnoreParenImpCasts();
14340
14341 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014342 if (!NoDiagnose) {
14343 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14344 << 0 << CurE->getSourceRange();
14345 return nullptr;
14346 }
14347 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014348 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014349
14350 // If we got an array subscript that express the whole dimension we
14351 // can have any array expressions before. If it only expressing part of
14352 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000014353 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014354 E->getType()))
14355 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014356
Patrick Lystere13b1e32019-01-02 19:28:48 +000014357 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14358 Expr::EvalResult Result;
14359 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
14360 if (!Result.Val.getInt().isNullValue()) {
14361 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14362 diag::err_omp_invalid_map_this_expr);
14363 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14364 diag::note_omp_invalid_subscript_on_this_ptr_map);
14365 }
14366 }
14367 RelevantExpr = TE;
14368 }
14369
Samuel Antao90927002016-04-26 14:54:23 +000014370 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014371 CurComponents.emplace_back(CurE, nullptr);
14372 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014373 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000014374 E = CurE->getBase()->IgnoreParenImpCasts();
14375
Alexey Bataev27041fa2017-12-05 15:22:49 +000014376 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014377 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14378
Samuel Antao5de996e2016-01-22 20:21:36 +000014379 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14380 // If the type of a list item is a reference to a type T then the type
14381 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000014382 if (CurType->isReferenceType())
14383 CurType = CurType->getPointeeType();
14384
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014385 bool IsPointer = CurType->isAnyPointerType();
14386
14387 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014388 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14389 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014390 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014391 }
14392
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014393 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000014394 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014395 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000014396 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014397
Samuel Antaodab51bb2016-07-18 23:22:11 +000014398 if (AllowWholeSizeArraySection) {
14399 // Any array section is currently allowed. Allowing a whole size array
14400 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014401 //
14402 // If this array section refers to the whole dimension we can still
14403 // accept other array sections before this one, except if the base is a
14404 // pointer. Otherwise, only unitary sections are accepted.
14405 if (NotWhole || IsPointer)
14406 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000014407 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014408 // A unity or whole array section is not allowed and that is not
14409 // compatible with the properties of the current array section.
14410 SemaRef.Diag(
14411 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
14412 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014413 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014414 }
Samuel Antao90927002016-04-26 14:54:23 +000014415
Patrick Lystere13b1e32019-01-02 19:28:48 +000014416 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14417 Expr::EvalResult ResultR;
14418 Expr::EvalResult ResultL;
14419 if (CurE->getLength()->EvaluateAsInt(ResultR,
14420 SemaRef.getASTContext())) {
14421 if (!ResultR.Val.getInt().isOneValue()) {
14422 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14423 diag::err_omp_invalid_map_this_expr);
14424 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14425 diag::note_omp_invalid_length_on_this_ptr_mapping);
14426 }
14427 }
14428 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
14429 ResultL, SemaRef.getASTContext())) {
14430 if (!ResultL.Val.getInt().isNullValue()) {
14431 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14432 diag::err_omp_invalid_map_this_expr);
14433 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14434 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
14435 }
14436 }
14437 RelevantExpr = TE;
14438 }
14439
Samuel Antao90927002016-04-26 14:54:23 +000014440 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014441 CurComponents.emplace_back(CurE, nullptr);
14442 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014443 if (!NoDiagnose) {
14444 // If nothing else worked, this is not a valid map clause expression.
14445 SemaRef.Diag(
14446 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
14447 << ERange;
14448 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000014449 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014450 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014451 }
14452
14453 return RelevantExpr;
14454}
14455
14456// Return true if expression E associated with value VD has conflicts with other
14457// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000014458static bool checkMapConflicts(
14459 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000014460 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000014461 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
14462 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014463 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000014464 SourceLocation ELoc = E->getExprLoc();
14465 SourceRange ERange = E->getSourceRange();
14466
14467 // In order to easily check the conflicts we need to match each component of
14468 // the expression under test with the components of the expressions that are
14469 // already in the stack.
14470
Samuel Antao5de996e2016-01-22 20:21:36 +000014471 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014472 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014473 "Map clause expression with unexpected base!");
14474
14475 // Variables to help detecting enclosing problems in data environment nests.
14476 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000014477 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014478
Samuel Antao90927002016-04-26 14:54:23 +000014479 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
14480 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000014481 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
14482 ERange, CKind, &EnclosingExpr,
14483 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
14484 StackComponents,
14485 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014486 assert(!StackComponents.empty() &&
14487 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014488 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014489 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000014490 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014491
Samuel Antao90927002016-04-26 14:54:23 +000014492 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000014493 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000014494
Samuel Antao5de996e2016-01-22 20:21:36 +000014495 // Expressions must start from the same base. Here we detect at which
14496 // point both expressions diverge from each other and see if we can
14497 // detect if the memory referred to both expressions is contiguous and
14498 // do not overlap.
14499 auto CI = CurComponents.rbegin();
14500 auto CE = CurComponents.rend();
14501 auto SI = StackComponents.rbegin();
14502 auto SE = StackComponents.rend();
14503 for (; CI != CE && SI != SE; ++CI, ++SI) {
14504
14505 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
14506 // At most one list item can be an array item derived from a given
14507 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000014508 if (CurrentRegionOnly &&
14509 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
14510 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
14511 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
14512 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
14513 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000014514 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000014515 << CI->getAssociatedExpression()->getSourceRange();
14516 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
14517 diag::note_used_here)
14518 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000014519 return true;
14520 }
14521
14522 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000014523 if (CI->getAssociatedExpression()->getStmtClass() !=
14524 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000014525 break;
14526
14527 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000014528 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000014529 break;
14530 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000014531 // Check if the extra components of the expressions in the enclosing
14532 // data environment are redundant for the current base declaration.
14533 // If they are, the maps completely overlap, which is legal.
14534 for (; SI != SE; ++SI) {
14535 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000014536 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000014537 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000014538 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014539 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000014540 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014541 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000014542 Type =
14543 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14544 }
14545 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000014546 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000014547 SemaRef, SI->getAssociatedExpression(), Type))
14548 break;
14549 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014550
14551 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14552 // List items of map clauses in the same construct must not share
14553 // original storage.
14554 //
14555 // If the expressions are exactly the same or one is a subset of the
14556 // other, it means they are sharing storage.
14557 if (CI == CE && SI == SE) {
14558 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014559 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000014560 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014561 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014562 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014563 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14564 << ERange;
14565 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014566 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14567 << RE->getSourceRange();
14568 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014569 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014570 // If we find the same expression in the enclosing data environment,
14571 // that is legal.
14572 IsEnclosedByDataEnvironmentExpr = true;
14573 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000014574 }
14575
Samuel Antao90927002016-04-26 14:54:23 +000014576 QualType DerivedType =
14577 std::prev(CI)->getAssociatedDeclaration()->getType();
14578 SourceLocation DerivedLoc =
14579 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000014580
14581 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14582 // If the type of a list item is a reference to a type T then the type
14583 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000014584 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014585
14586 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
14587 // A variable for which the type is pointer and an array section
14588 // derived from that variable must not appear as list items of map
14589 // clauses of the same construct.
14590 //
14591 // Also, cover one of the cases in:
14592 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
14593 // If any part of the original storage of a list item has corresponding
14594 // storage in the device data environment, all of the original storage
14595 // must have corresponding storage in the device data environment.
14596 //
14597 if (DerivedType->isAnyPointerType()) {
14598 if (CI == CE || SI == SE) {
14599 SemaRef.Diag(
14600 DerivedLoc,
14601 diag::err_omp_pointer_mapped_along_with_derived_section)
14602 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000014603 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14604 << RE->getSourceRange();
14605 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000014606 }
14607 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000014608 SI->getAssociatedExpression()->getStmtClass() ||
14609 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
14610 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014611 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000014612 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000014613 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000014614 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14615 << RE->getSourceRange();
14616 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014617 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014618 }
14619
14620 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14621 // List items of map clauses in the same construct must not share
14622 // original storage.
14623 //
14624 // An expression is a subset of the other.
14625 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014626 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000014627 if (CI != CE || SI != SE) {
14628 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
14629 // a pointer.
14630 auto Begin =
14631 CI != CE ? CurComponents.begin() : StackComponents.begin();
14632 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
14633 auto It = Begin;
14634 while (It != End && !It->getAssociatedDeclaration())
14635 std::advance(It, 1);
14636 assert(It != End &&
14637 "Expected at least one component with the declaration.");
14638 if (It != Begin && It->getAssociatedDeclaration()
14639 ->getType()
14640 .getCanonicalType()
14641 ->isAnyPointerType()) {
14642 IsEnclosedByDataEnvironmentExpr = false;
14643 EnclosingExpr = nullptr;
14644 return false;
14645 }
14646 }
Samuel Antao661c0902016-05-26 17:39:58 +000014647 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014648 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014649 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014650 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14651 << ERange;
14652 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014653 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14654 << RE->getSourceRange();
14655 return true;
14656 }
14657
14658 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000014659 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000014660 if (!CurrentRegionOnly && SI != SE)
14661 EnclosingExpr = RE;
14662
14663 // The current expression is a subset of the expression in the data
14664 // environment.
14665 IsEnclosedByDataEnvironmentExpr |=
14666 (!CurrentRegionOnly && CI != CE && SI == SE);
14667
14668 return false;
14669 });
14670
14671 if (CurrentRegionOnly)
14672 return FoundError;
14673
14674 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
14675 // If any part of the original storage of a list item has corresponding
14676 // storage in the device data environment, all of the original storage must
14677 // have corresponding storage in the device data environment.
14678 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
14679 // If a list item is an element of a structure, and a different element of
14680 // the structure has a corresponding list item in the device data environment
14681 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000014682 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000014683 // data environment prior to the task encountering the construct.
14684 //
14685 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
14686 SemaRef.Diag(ELoc,
14687 diag::err_omp_original_storage_is_shared_and_does_not_contain)
14688 << ERange;
14689 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
14690 << EnclosingExpr->getSourceRange();
14691 return true;
14692 }
14693
14694 return FoundError;
14695}
14696
Michael Kruse4304e9d2019-02-19 16:38:20 +000014697// Look up the user-defined mapper given the mapper name and mapped type, and
14698// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000014699static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
14700 CXXScopeSpec &MapperIdScopeSpec,
14701 const DeclarationNameInfo &MapperId,
14702 QualType Type,
14703 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000014704 if (MapperIdScopeSpec.isInvalid())
14705 return ExprError();
14706 // Find all user-defined mappers with the given MapperId.
14707 SmallVector<UnresolvedSet<8>, 4> Lookups;
14708 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
14709 Lookup.suppressDiagnostics();
14710 if (S) {
14711 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
14712 NamedDecl *D = Lookup.getRepresentativeDecl();
14713 while (S && !S->isDeclScope(D))
14714 S = S->getParent();
14715 if (S)
14716 S = S->getParent();
14717 Lookups.emplace_back();
14718 Lookups.back().append(Lookup.begin(), Lookup.end());
14719 Lookup.clear();
14720 }
14721 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
14722 // Extract the user-defined mappers with the given MapperId.
14723 Lookups.push_back(UnresolvedSet<8>());
14724 for (NamedDecl *D : ULE->decls()) {
14725 auto *DMD = cast<OMPDeclareMapperDecl>(D);
14726 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
14727 Lookups.back().addDecl(DMD);
14728 }
14729 }
14730 // Defer the lookup for dependent types. The results will be passed through
14731 // UnresolvedMapper on instantiation.
14732 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
14733 Type->isInstantiationDependentType() ||
14734 Type->containsUnexpandedParameterPack() ||
14735 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
14736 return !D->isInvalidDecl() &&
14737 (D->getType()->isDependentType() ||
14738 D->getType()->isInstantiationDependentType() ||
14739 D->getType()->containsUnexpandedParameterPack());
14740 })) {
14741 UnresolvedSet<8> URS;
14742 for (const UnresolvedSet<8> &Set : Lookups) {
14743 if (Set.empty())
14744 continue;
14745 URS.append(Set.begin(), Set.end());
14746 }
14747 return UnresolvedLookupExpr::Create(
14748 SemaRef.Context, /*NamingClass=*/nullptr,
14749 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
14750 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
14751 }
14752 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14753 // The type must be of struct, union or class type in C and C++
14754 if (!Type->isStructureOrClassType() && !Type->isUnionType())
14755 return ExprEmpty();
14756 SourceLocation Loc = MapperId.getLoc();
14757 // Perform argument dependent lookup.
14758 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
14759 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
14760 // Return the first user-defined mapper with the desired type.
14761 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14762 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
14763 if (!D->isInvalidDecl() &&
14764 SemaRef.Context.hasSameType(D->getType(), Type))
14765 return D;
14766 return nullptr;
14767 }))
14768 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
14769 // Find the first user-defined mapper with a type derived from the desired
14770 // type.
14771 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14772 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
14773 if (!D->isInvalidDecl() &&
14774 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
14775 !Type.isMoreQualifiedThan(D->getType()))
14776 return D;
14777 return nullptr;
14778 })) {
14779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
14780 /*DetectVirtual=*/false);
14781 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
14782 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
14783 VD->getType().getUnqualifiedType()))) {
14784 if (SemaRef.CheckBaseClassAccess(
14785 Loc, VD->getType(), Type, Paths.front(),
14786 /*DiagID=*/0) != Sema::AR_inaccessible) {
14787 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
14788 }
14789 }
14790 }
14791 }
14792 // Report error if a mapper is specified, but cannot be found.
14793 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
14794 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
14795 << Type << MapperId.getName();
14796 return ExprError();
14797 }
14798 return ExprEmpty();
14799}
14800
Samuel Antao661c0902016-05-26 17:39:58 +000014801namespace {
14802// Utility struct that gathers all the related lists associated with a mappable
14803// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014804struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000014805 // The list of expressions.
14806 ArrayRef<Expr *> VarList;
14807 // The list of processed expressions.
14808 SmallVector<Expr *, 16> ProcessedVarList;
14809 // The mappble components for each expression.
14810 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
14811 // The base declaration of the variable.
14812 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000014813 // The reference to the user-defined mapper associated with every expression.
14814 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000014815
14816 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
14817 // We have a list of components and base declarations for each entry in the
14818 // variable list.
14819 VarComponents.reserve(VarList.size());
14820 VarBaseDeclarations.reserve(VarList.size());
14821 }
14822};
14823}
14824
14825// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000014826// \a CKind. In the check process the valid expressions, mappable expression
14827// components, variables, and user-defined mappers are extracted and used to
14828// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
14829// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
14830// and \a MapperId are expected to be valid if the clause kind is 'map'.
14831static void checkMappableExpressionList(
14832 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
14833 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014834 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
14835 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014836 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000014837 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014838 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
14839 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000014840 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000014841
14842 // If the identifier of user-defined mapper is not specified, it is "default".
14843 // We do not change the actual name in this clause to distinguish whether a
14844 // mapper is specified explicitly, i.e., it is not explicitly specified when
14845 // MapperId.getName() is empty.
14846 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
14847 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
14848 MapperId.setName(DeclNames.getIdentifier(
14849 &SemaRef.getASTContext().Idents.get("default")));
14850 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014851
14852 // Iterators to find the current unresolved mapper expression.
14853 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
14854 bool UpdateUMIt = false;
14855 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014856
Samuel Antao90927002016-04-26 14:54:23 +000014857 // Keep track of the mappable components and base declarations in this clause.
14858 // Each entry in the list is going to have a list of components associated. We
14859 // record each set of the components so that we can build the clause later on.
14860 // In the end we should have the same amount of declarations and component
14861 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000014862
Alexey Bataeve3727102018-04-18 15:57:46 +000014863 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014864 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014865 SourceLocation ELoc = RE->getExprLoc();
14866
Michael Kruse4304e9d2019-02-19 16:38:20 +000014867 // Find the current unresolved mapper expression.
14868 if (UpdateUMIt && UMIt != UMEnd) {
14869 UMIt++;
14870 assert(
14871 UMIt != UMEnd &&
14872 "Expect the size of UnresolvedMappers to match with that of VarList");
14873 }
14874 UpdateUMIt = true;
14875 if (UMIt != UMEnd)
14876 UnresolvedMapper = *UMIt;
14877
Alexey Bataeve3727102018-04-18 15:57:46 +000014878 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014879
14880 if (VE->isValueDependent() || VE->isTypeDependent() ||
14881 VE->isInstantiationDependent() ||
14882 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000014883 // Try to find the associated user-defined mapper.
14884 ExprResult ER = buildUserDefinedMapperRef(
14885 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14886 VE->getType().getCanonicalType(), UnresolvedMapper);
14887 if (ER.isInvalid())
14888 continue;
14889 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000014890 // We can only analyze this information once the missing information is
14891 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000014892 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014893 continue;
14894 }
14895
Alexey Bataeve3727102018-04-18 15:57:46 +000014896 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014897
Samuel Antao5de996e2016-01-22 20:21:36 +000014898 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000014899 SemaRef.Diag(ELoc,
14900 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000014901 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014902 continue;
14903 }
14904
Samuel Antao90927002016-04-26 14:54:23 +000014905 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
14906 ValueDecl *CurDeclaration = nullptr;
14907
14908 // Obtain the array or member expression bases if required. Also, fill the
14909 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000014910 const Expr *BE = checkMapClauseExpressionBase(
14911 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000014912 if (!BE)
14913 continue;
14914
Samuel Antao90927002016-04-26 14:54:23 +000014915 assert(!CurComponents.empty() &&
14916 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014917
Patrick Lystere13b1e32019-01-02 19:28:48 +000014918 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
14919 // Add store "this" pointer to class in DSAStackTy for future checking
14920 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000014921 // Try to find the associated user-defined mapper.
14922 ExprResult ER = buildUserDefinedMapperRef(
14923 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14924 VE->getType().getCanonicalType(), UnresolvedMapper);
14925 if (ER.isInvalid())
14926 continue;
14927 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000014928 // Skip restriction checking for variable or field declarations
14929 MVLI.ProcessedVarList.push_back(RE);
14930 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14931 MVLI.VarComponents.back().append(CurComponents.begin(),
14932 CurComponents.end());
14933 MVLI.VarBaseDeclarations.push_back(nullptr);
14934 continue;
14935 }
14936
Samuel Antao90927002016-04-26 14:54:23 +000014937 // For the following checks, we rely on the base declaration which is
14938 // expected to be associated with the last component. The declaration is
14939 // expected to be a variable or a field (if 'this' is being mapped).
14940 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
14941 assert(CurDeclaration && "Null decl on map clause.");
14942 assert(
14943 CurDeclaration->isCanonicalDecl() &&
14944 "Expecting components to have associated only canonical declarations.");
14945
14946 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000014947 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000014948
14949 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000014950 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014951
14952 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000014953 // threadprivate variables cannot appear in a map clause.
14954 // OpenMP 4.5 [2.10.5, target update Construct]
14955 // threadprivate variables cannot appear in a from clause.
14956 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014957 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014958 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
14959 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000014960 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014961 continue;
14962 }
14963
Samuel Antao5de996e2016-01-22 20:21:36 +000014964 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
14965 // A list item cannot appear in both a map clause and a data-sharing
14966 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000014967
Samuel Antao5de996e2016-01-22 20:21:36 +000014968 // Check conflicts with other map clause expressions. We check the conflicts
14969 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000014970 // environment, because the restrictions are different. We only have to
14971 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000014972 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014973 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014974 break;
Samuel Antao661c0902016-05-26 17:39:58 +000014975 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014976 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014977 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014978 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014979
Samuel Antao661c0902016-05-26 17:39:58 +000014980 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000014981 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14982 // If the type of a list item is a reference to a type T then the type will
14983 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000014984 auto I = llvm::find_if(
14985 CurComponents,
14986 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
14987 return MC.getAssociatedDeclaration();
14988 });
14989 assert(I != CurComponents.end() && "Null decl on map clause.");
14990 QualType Type =
14991 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014992
Samuel Antao661c0902016-05-26 17:39:58 +000014993 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
14994 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000014995 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000014996 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014997 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000014998 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000014999 continue;
15000
Samuel Antao661c0902016-05-26 17:39:58 +000015001 if (CKind == OMPC_map) {
15002 // target enter data
15003 // OpenMP [2.10.2, Restrictions, p. 99]
15004 // A map-type must be specified in all map clauses and must be either
15005 // to or alloc.
15006 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15007 if (DKind == OMPD_target_enter_data &&
15008 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15009 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15010 << (IsMapTypeImplicit ? 1 : 0)
15011 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15012 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015013 continue;
15014 }
Samuel Antao661c0902016-05-26 17:39:58 +000015015
15016 // target exit_data
15017 // OpenMP [2.10.3, Restrictions, p. 102]
15018 // A map-type must be specified in all map clauses and must be either
15019 // from, release, or delete.
15020 if (DKind == OMPD_target_exit_data &&
15021 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15022 MapType == OMPC_MAP_delete)) {
15023 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15024 << (IsMapTypeImplicit ? 1 : 0)
15025 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15026 << getOpenMPDirectiveName(DKind);
15027 continue;
15028 }
15029
15030 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15031 // A list item cannot appear in both a map clause and a data-sharing
15032 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015033 //
15034 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15035 // A list item cannot appear in both a map clause and a data-sharing
15036 // attribute clause on the same construct unless the construct is a
15037 // combined construct.
15038 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15039 isOpenMPTargetExecutionDirective(DKind)) ||
15040 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015041 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015042 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015043 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015044 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015045 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015046 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015047 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015048 continue;
15049 }
15050 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015051 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015052
Michael Kruse01f670d2019-02-22 22:29:42 +000015053 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015054 ExprResult ER = buildUserDefinedMapperRef(
15055 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15056 Type.getCanonicalType(), UnresolvedMapper);
15057 if (ER.isInvalid())
15058 continue;
15059 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015060
Samuel Antao90927002016-04-26 14:54:23 +000015061 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015062 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015063
15064 // Store the components in the stack so that they can be used to check
15065 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015066 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15067 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015068
15069 // Save the components and declaration to create the clause. For purposes of
15070 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015071 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015072 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15073 MVLI.VarComponents.back().append(CurComponents.begin(),
15074 CurComponents.end());
15075 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15076 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015077 }
Samuel Antao661c0902016-05-26 17:39:58 +000015078}
15079
Michael Kruse4304e9d2019-02-19 16:38:20 +000015080OMPClause *Sema::ActOnOpenMPMapClause(
15081 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15082 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15083 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15084 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15085 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15086 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15087 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15088 OMPC_MAP_MODIFIER_unknown,
15089 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015090 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15091
15092 // Process map-type-modifiers, flag errors for duplicate modifiers.
15093 unsigned Count = 0;
15094 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15095 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15096 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15097 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15098 continue;
15099 }
15100 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015101 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015102 Modifiers[Count] = MapTypeModifiers[I];
15103 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15104 ++Count;
15105 }
15106
Michael Kruse4304e9d2019-02-19 16:38:20 +000015107 MappableVarListInfo MVLI(VarList);
15108 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015109 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15110 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015111
Samuel Antao5de996e2016-01-22 20:21:36 +000015112 // We need to produce a map clause even if we don't have variables so that
15113 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015114 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15115 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15116 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15117 MapperIdScopeSpec.getWithLocInContext(Context),
15118 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015119}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015120
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015121QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15122 TypeResult ParsedType) {
15123 assert(ParsedType.isUsable());
15124
15125 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15126 if (ReductionType.isNull())
15127 return QualType();
15128
15129 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15130 // A type name in a declare reduction directive cannot be a function type, an
15131 // array type, a reference type, or a type qualified with const, volatile or
15132 // restrict.
15133 if (ReductionType.hasQualifiers()) {
15134 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15135 return QualType();
15136 }
15137
15138 if (ReductionType->isFunctionType()) {
15139 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15140 return QualType();
15141 }
15142 if (ReductionType->isReferenceType()) {
15143 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15144 return QualType();
15145 }
15146 if (ReductionType->isArrayType()) {
15147 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15148 return QualType();
15149 }
15150 return ReductionType;
15151}
15152
15153Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15154 Scope *S, DeclContext *DC, DeclarationName Name,
15155 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15156 AccessSpecifier AS, Decl *PrevDeclInScope) {
15157 SmallVector<Decl *, 8> Decls;
15158 Decls.reserve(ReductionTypes.size());
15159
15160 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015161 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015162 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15163 // A reduction-identifier may not be re-declared in the current scope for the
15164 // same type or for a type that is compatible according to the base language
15165 // rules.
15166 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15167 OMPDeclareReductionDecl *PrevDRD = nullptr;
15168 bool InCompoundScope = true;
15169 if (S != nullptr) {
15170 // Find previous declaration with the same name not referenced in other
15171 // declarations.
15172 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15173 InCompoundScope =
15174 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15175 LookupName(Lookup, S);
15176 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15177 /*AllowInlineNamespace=*/false);
15178 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015179 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015180 while (Filter.hasNext()) {
15181 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15182 if (InCompoundScope) {
15183 auto I = UsedAsPrevious.find(PrevDecl);
15184 if (I == UsedAsPrevious.end())
15185 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015186 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015187 UsedAsPrevious[D] = true;
15188 }
15189 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15190 PrevDecl->getLocation();
15191 }
15192 Filter.done();
15193 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015194 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015195 if (!PrevData.second) {
15196 PrevDRD = PrevData.first;
15197 break;
15198 }
15199 }
15200 }
15201 } else if (PrevDeclInScope != nullptr) {
15202 auto *PrevDRDInScope = PrevDRD =
15203 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15204 do {
15205 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15206 PrevDRDInScope->getLocation();
15207 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15208 } while (PrevDRDInScope != nullptr);
15209 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015210 for (const auto &TyData : ReductionTypes) {
15211 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015212 bool Invalid = false;
15213 if (I != PreviousRedeclTypes.end()) {
15214 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15215 << TyData.first;
15216 Diag(I->second, diag::note_previous_definition);
15217 Invalid = true;
15218 }
15219 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15220 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15221 Name, TyData.first, PrevDRD);
15222 DC->addDecl(DRD);
15223 DRD->setAccess(AS);
15224 Decls.push_back(DRD);
15225 if (Invalid)
15226 DRD->setInvalidDecl();
15227 else
15228 PrevDRD = DRD;
15229 }
15230
15231 return DeclGroupPtrTy::make(
15232 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15233}
15234
15235void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15236 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15237
15238 // Enter new function scope.
15239 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015240 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015241 getCurFunction()->setHasOMPDeclareReductionCombiner();
15242
15243 if (S != nullptr)
15244 PushDeclContext(S, DRD);
15245 else
15246 CurContext = DRD;
15247
Faisal Valid143a0c2017-04-01 21:30:49 +000015248 PushExpressionEvaluationContext(
15249 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015250
15251 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015252 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
15253 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
15254 // uses semantics of argument handles by value, but it should be passed by
15255 // reference. C lang does not support references, so pass all parameters as
15256 // pointers.
15257 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015258 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015259 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015260 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
15261 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
15262 // uses semantics of argument handles by value, but it should be passed by
15263 // reference. C lang does not support references, so pass all parameters as
15264 // pointers.
15265 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015266 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015267 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
15268 if (S != nullptr) {
15269 PushOnScopeChains(OmpInParm, S);
15270 PushOnScopeChains(OmpOutParm, S);
15271 } else {
15272 DRD->addDecl(OmpInParm);
15273 DRD->addDecl(OmpOutParm);
15274 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015275 Expr *InE =
15276 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
15277 Expr *OutE =
15278 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
15279 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015280}
15281
15282void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
15283 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15284 DiscardCleanupsInEvaluationContext();
15285 PopExpressionEvaluationContext();
15286
15287 PopDeclContext();
15288 PopFunctionScopeInfo();
15289
15290 if (Combiner != nullptr)
15291 DRD->setCombiner(Combiner);
15292 else
15293 DRD->setInvalidDecl();
15294}
15295
Alexey Bataev070f43a2017-09-06 14:49:58 +000015296VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015297 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15298
15299 // Enter new function scope.
15300 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015301 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015302
15303 if (S != nullptr)
15304 PushDeclContext(S, DRD);
15305 else
15306 CurContext = DRD;
15307
Faisal Valid143a0c2017-04-01 21:30:49 +000015308 PushExpressionEvaluationContext(
15309 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015310
15311 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015312 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
15313 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
15314 // uses semantics of argument handles by value, but it should be passed by
15315 // reference. C lang does not support references, so pass all parameters as
15316 // pointers.
15317 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015318 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015319 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015320 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
15321 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
15322 // uses semantics of argument handles by value, but it should be passed by
15323 // reference. C lang does not support references, so pass all parameters as
15324 // pointers.
15325 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015326 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015327 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015328 if (S != nullptr) {
15329 PushOnScopeChains(OmpPrivParm, S);
15330 PushOnScopeChains(OmpOrigParm, S);
15331 } else {
15332 DRD->addDecl(OmpPrivParm);
15333 DRD->addDecl(OmpOrigParm);
15334 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015335 Expr *OrigE =
15336 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
15337 Expr *PrivE =
15338 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
15339 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000015340 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015341}
15342
Alexey Bataev070f43a2017-09-06 14:49:58 +000015343void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
15344 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015345 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15346 DiscardCleanupsInEvaluationContext();
15347 PopExpressionEvaluationContext();
15348
15349 PopDeclContext();
15350 PopFunctionScopeInfo();
15351
Alexey Bataev070f43a2017-09-06 14:49:58 +000015352 if (Initializer != nullptr) {
15353 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
15354 } else if (OmpPrivParm->hasInit()) {
15355 DRD->setInitializer(OmpPrivParm->getInit(),
15356 OmpPrivParm->isDirectInit()
15357 ? OMPDeclareReductionDecl::DirectInit
15358 : OMPDeclareReductionDecl::CopyInit);
15359 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015360 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000015361 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015362}
15363
15364Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
15365 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015366 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015367 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015368 if (S)
15369 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
15370 /*AddToContext=*/false);
15371 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015372 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000015373 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015374 }
15375 return DeclReductions;
15376}
15377
Michael Kruse251e1482019-02-01 20:25:04 +000015378TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
15379 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15380 QualType T = TInfo->getType();
15381 if (D.isInvalidType())
15382 return true;
15383
15384 if (getLangOpts().CPlusPlus) {
15385 // Check that there are no default arguments (C++ only).
15386 CheckExtraCXXDefaultArguments(D);
15387 }
15388
15389 return CreateParsedType(T, TInfo);
15390}
15391
15392QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
15393 TypeResult ParsedType) {
15394 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
15395
15396 QualType MapperType = GetTypeFromParser(ParsedType.get());
15397 assert(!MapperType.isNull() && "Expect valid mapper type");
15398
15399 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15400 // The type must be of struct, union or class type in C and C++
15401 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
15402 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
15403 return QualType();
15404 }
15405 return MapperType;
15406}
15407
15408OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
15409 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
15410 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
15411 Decl *PrevDeclInScope) {
15412 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
15413 forRedeclarationInCurContext());
15414 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15415 // A mapper-identifier may not be redeclared in the current scope for the
15416 // same type or for a type that is compatible according to the base language
15417 // rules.
15418 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15419 OMPDeclareMapperDecl *PrevDMD = nullptr;
15420 bool InCompoundScope = true;
15421 if (S != nullptr) {
15422 // Find previous declaration with the same name not referenced in other
15423 // declarations.
15424 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15425 InCompoundScope =
15426 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15427 LookupName(Lookup, S);
15428 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15429 /*AllowInlineNamespace=*/false);
15430 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
15431 LookupResult::Filter Filter = Lookup.makeFilter();
15432 while (Filter.hasNext()) {
15433 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
15434 if (InCompoundScope) {
15435 auto I = UsedAsPrevious.find(PrevDecl);
15436 if (I == UsedAsPrevious.end())
15437 UsedAsPrevious[PrevDecl] = false;
15438 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
15439 UsedAsPrevious[D] = true;
15440 }
15441 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15442 PrevDecl->getLocation();
15443 }
15444 Filter.done();
15445 if (InCompoundScope) {
15446 for (const auto &PrevData : UsedAsPrevious) {
15447 if (!PrevData.second) {
15448 PrevDMD = PrevData.first;
15449 break;
15450 }
15451 }
15452 }
15453 } else if (PrevDeclInScope) {
15454 auto *PrevDMDInScope = PrevDMD =
15455 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
15456 do {
15457 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
15458 PrevDMDInScope->getLocation();
15459 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
15460 } while (PrevDMDInScope != nullptr);
15461 }
15462 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
15463 bool Invalid = false;
15464 if (I != PreviousRedeclTypes.end()) {
15465 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
15466 << MapperType << Name;
15467 Diag(I->second, diag::note_previous_definition);
15468 Invalid = true;
15469 }
15470 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
15471 MapperType, VN, PrevDMD);
15472 DC->addDecl(DMD);
15473 DMD->setAccess(AS);
15474 if (Invalid)
15475 DMD->setInvalidDecl();
15476
15477 // Enter new function scope.
15478 PushFunctionScope();
15479 setFunctionHasBranchProtectedScope();
15480
15481 CurContext = DMD;
15482
15483 return DMD;
15484}
15485
15486void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
15487 Scope *S,
15488 QualType MapperType,
15489 SourceLocation StartLoc,
15490 DeclarationName VN) {
15491 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
15492 if (S)
15493 PushOnScopeChains(VD, S);
15494 else
15495 DMD->addDecl(VD);
15496 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
15497 DMD->setMapperVarRef(MapperVarRefExpr);
15498}
15499
15500Sema::DeclGroupPtrTy
15501Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
15502 ArrayRef<OMPClause *> ClauseList) {
15503 PopDeclContext();
15504 PopFunctionScopeInfo();
15505
15506 if (D) {
15507 if (S)
15508 PushOnScopeChains(D, S, /*AddToContext=*/false);
15509 D->CreateClauses(Context, ClauseList);
15510 }
15511
15512 return DeclGroupPtrTy::make(DeclGroupRef(D));
15513}
15514
David Majnemer9d168222016-08-05 17:44:54 +000015515OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000015516 SourceLocation StartLoc,
15517 SourceLocation LParenLoc,
15518 SourceLocation EndLoc) {
15519 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015520 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015521
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015522 // OpenMP [teams Constrcut, Restrictions]
15523 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015524 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000015525 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015526 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015527
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015528 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015529 OpenMPDirectiveKind CaptureRegion =
15530 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
15531 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015532 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015533 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015534 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15535 HelperValStmt = buildPreInits(Context, Captures);
15536 }
15537
15538 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
15539 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000015540}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015541
15542OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
15543 SourceLocation StartLoc,
15544 SourceLocation LParenLoc,
15545 SourceLocation EndLoc) {
15546 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015547 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015548
15549 // OpenMP [teams Constrcut, Restrictions]
15550 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015551 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000015552 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015553 return nullptr;
15554
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015555 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015556 OpenMPDirectiveKind CaptureRegion =
15557 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
15558 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015559 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015560 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015561 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15562 HelperValStmt = buildPreInits(Context, Captures);
15563 }
15564
15565 return new (Context) OMPThreadLimitClause(
15566 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015567}
Alexey Bataeva0569352015-12-01 10:17:31 +000015568
15569OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
15570 SourceLocation StartLoc,
15571 SourceLocation LParenLoc,
15572 SourceLocation EndLoc) {
15573 Expr *ValExpr = Priority;
15574
15575 // OpenMP [2.9.1, task Constrcut]
15576 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015577 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000015578 /*StrictlyPositive=*/false))
15579 return nullptr;
15580
15581 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15582}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015583
15584OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
15585 SourceLocation StartLoc,
15586 SourceLocation LParenLoc,
15587 SourceLocation EndLoc) {
15588 Expr *ValExpr = Grainsize;
15589
15590 // OpenMP [2.9.2, taskloop Constrcut]
15591 // The parameter of the grainsize clause must be a positive integer
15592 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015593 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015594 /*StrictlyPositive=*/true))
15595 return nullptr;
15596
15597 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15598}
Alexey Bataev382967a2015-12-08 12:06:20 +000015599
15600OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
15601 SourceLocation StartLoc,
15602 SourceLocation LParenLoc,
15603 SourceLocation EndLoc) {
15604 Expr *ValExpr = NumTasks;
15605
15606 // OpenMP [2.9.2, taskloop Constrcut]
15607 // The parameter of the num_tasks clause must be a positive integer
15608 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015609 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000015610 /*StrictlyPositive=*/true))
15611 return nullptr;
15612
15613 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15614}
15615
Alexey Bataev28c75412015-12-15 08:19:24 +000015616OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
15617 SourceLocation LParenLoc,
15618 SourceLocation EndLoc) {
15619 // OpenMP [2.13.2, critical construct, Description]
15620 // ... where hint-expression is an integer constant expression that evaluates
15621 // to a valid lock hint.
15622 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
15623 if (HintExpr.isInvalid())
15624 return nullptr;
15625 return new (Context)
15626 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
15627}
15628
Carlo Bertollib4adf552016-01-15 18:50:31 +000015629OMPClause *Sema::ActOnOpenMPDistScheduleClause(
15630 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15631 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
15632 SourceLocation EndLoc) {
15633 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
15634 std::string Values;
15635 Values += "'";
15636 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
15637 Values += "'";
15638 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15639 << Values << getOpenMPClauseName(OMPC_dist_schedule);
15640 return nullptr;
15641 }
15642 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000015643 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000015644 if (ChunkSize) {
15645 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15646 !ChunkSize->isInstantiationDependent() &&
15647 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015648 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000015649 ExprResult Val =
15650 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
15651 if (Val.isInvalid())
15652 return nullptr;
15653
15654 ValExpr = Val.get();
15655
15656 // OpenMP [2.7.1, Restrictions]
15657 // chunk_size must be a loop invariant integer expression with a positive
15658 // value.
15659 llvm::APSInt Result;
15660 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
15661 if (Result.isSigned() && !Result.isStrictlyPositive()) {
15662 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
15663 << "dist_schedule" << ChunkSize->getSourceRange();
15664 return nullptr;
15665 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000015666 } else if (getOpenMPCaptureRegionForClause(
15667 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
15668 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000015669 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015670 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015671 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000015672 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15673 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000015674 }
15675 }
15676 }
15677
15678 return new (Context)
15679 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000015680 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000015681}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015682
15683OMPClause *Sema::ActOnOpenMPDefaultmapClause(
15684 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
15685 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
15686 SourceLocation KindLoc, SourceLocation EndLoc) {
15687 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000015688 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015689 std::string Value;
15690 SourceLocation Loc;
15691 Value += "'";
15692 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
15693 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000015694 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015695 Loc = MLoc;
15696 } else {
15697 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000015698 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015699 Loc = KindLoc;
15700 }
15701 Value += "'";
15702 Diag(Loc, diag::err_omp_unexpected_clause_value)
15703 << Value << getOpenMPClauseName(OMPC_defaultmap);
15704 return nullptr;
15705 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000015706 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015707
15708 return new (Context)
15709 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
15710}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015711
15712bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
15713 DeclContext *CurLexicalContext = getCurLexicalContext();
15714 if (!CurLexicalContext->isFileContext() &&
15715 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000015716 !CurLexicalContext->isExternCXXContext() &&
15717 !isa<CXXRecordDecl>(CurLexicalContext) &&
15718 !isa<ClassTemplateDecl>(CurLexicalContext) &&
15719 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
15720 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015721 Diag(Loc, diag::err_omp_region_not_file_context);
15722 return false;
15723 }
Kelvin Libc38e632018-09-10 02:07:09 +000015724 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015725 return true;
15726}
15727
15728void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000015729 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015730 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000015731 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015732}
15733
Alexey Bataev729e2422019-08-23 16:11:14 +000015734NamedDecl *
15735Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
15736 const DeclarationNameInfo &Id,
15737 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015738 LookupResult Lookup(*this, Id, LookupOrdinaryName);
15739 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
15740
15741 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000015742 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015743 Lookup.suppressDiagnostics();
15744
15745 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000015746 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015747 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000015748 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015749 CTK_ErrorRecovery)) {
15750 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
15751 << Id.getName());
15752 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000015753 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015754 }
15755
15756 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000015757 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015758 }
15759
15760 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000015761 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
15762 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015763 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000015764 return nullptr;
15765 }
15766 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
15767 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
15768 return ND;
15769}
15770
15771void Sema::ActOnOpenMPDeclareTargetName(
15772 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
15773 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
15774 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
15775 isa<FunctionTemplateDecl>(ND)) &&
15776 "Expected variable, function or function template.");
15777
15778 // Diagnose marking after use as it may lead to incorrect diagnosis and
15779 // codegen.
15780 if (LangOpts.OpenMP >= 50 &&
15781 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
15782 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
15783
15784 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
15785 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
15786 if (DevTy.hasValue() && *DevTy != DT) {
15787 Diag(Loc, diag::err_omp_device_type_mismatch)
15788 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
15789 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
15790 return;
15791 }
15792 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
15793 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
15794 if (!Res) {
15795 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
15796 SourceRange(Loc, Loc));
15797 ND->addAttr(A);
15798 if (ASTMutationListener *ML = Context.getASTMutationListener())
15799 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
15800 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
15801 } else if (*Res != MT) {
15802 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000015803 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015804}
15805
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015806static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
15807 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000015808 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015809 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000015810 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000015811 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
15812 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
15813 if (SemaRef.LangOpts.OpenMP >= 50 &&
15814 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
15815 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
15816 VD->hasGlobalStorage()) {
15817 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
15818 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
15819 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
15820 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
15821 // If a lambda declaration and definition appears between a
15822 // declare target directive and the matching end declare target
15823 // directive, all variables that are captured by the lambda
15824 // expression must also appear in a to clause.
15825 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000015826 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000015827 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
15828 << VD << 0 << SR;
15829 return;
15830 }
15831 }
15832 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000015833 return;
15834 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
15835 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015836}
15837
15838static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
15839 Sema &SemaRef, DSAStackTy *Stack,
15840 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000015841 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015842 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
15843 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015844}
15845
Kelvin Li1ce87c72017-12-12 20:08:12 +000015846void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
15847 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015848 if (!D || D->isInvalidDecl())
15849 return;
15850 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015851 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000015852 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000015853 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000015854 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
15855 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000015856 return;
15857 // 2.10.6: threadprivate variable cannot appear in a declare target
15858 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015859 if (DSAStack->isThreadPrivate(VD)) {
15860 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000015861 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015862 return;
15863 }
15864 }
Alexey Bataev97b72212018-08-14 18:31:20 +000015865 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
15866 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015867 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000015868 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
15869 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015870 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000015871 Diag(IdLoc, diag::err_omp_function_in_link_clause);
15872 Diag(FD->getLocation(), diag::note_defined_here) << FD;
15873 return;
15874 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015875 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000015876 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
15877 OMPDeclareTargetDeclAttr::getDeviceType(FD);
15878 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
15879 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015880 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000015881 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
15882 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
15883 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000015884 }
Alexey Bataev30a78212018-09-11 13:59:10 +000015885 if (auto *VD = dyn_cast<ValueDecl>(D)) {
15886 // Problem if any with var declared with incomplete type will be reported
15887 // as normal, so no need to check it here.
15888 if ((E || !VD->getType()->isIncompleteType()) &&
15889 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
15890 return;
15891 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
15892 // Checking declaration inside declare target region.
15893 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
15894 isa<FunctionTemplateDecl>(D)) {
15895 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000015896 Context, OMPDeclareTargetDeclAttr::MT_To,
15897 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000015898 D->addAttr(A);
15899 if (ASTMutationListener *ML = Context.getASTMutationListener())
15900 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
15901 }
15902 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015903 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015904 }
Alexey Bataev30a78212018-09-11 13:59:10 +000015905 if (!E)
15906 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015907 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
15908}
Samuel Antao661c0902016-05-26 17:39:58 +000015909
15910OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000015911 CXXScopeSpec &MapperIdScopeSpec,
15912 DeclarationNameInfo &MapperId,
15913 const OMPVarListLocTy &Locs,
15914 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000015915 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015916 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
15917 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000015918 if (MVLI.ProcessedVarList.empty())
15919 return nullptr;
15920
Michael Kruse01f670d2019-02-22 22:29:42 +000015921 return OMPToClause::Create(
15922 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15923 MVLI.VarComponents, MVLI.UDMapperList,
15924 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000015925}
Samuel Antaoec172c62016-05-26 17:49:04 +000015926
15927OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000015928 CXXScopeSpec &MapperIdScopeSpec,
15929 DeclarationNameInfo &MapperId,
15930 const OMPVarListLocTy &Locs,
15931 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015932 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015933 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
15934 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000015935 if (MVLI.ProcessedVarList.empty())
15936 return nullptr;
15937
Michael Kruse0336c752019-02-25 20:34:15 +000015938 return OMPFromClause::Create(
15939 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15940 MVLI.VarComponents, MVLI.UDMapperList,
15941 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000015942}
Carlo Bertolli2404b172016-07-13 15:37:16 +000015943
15944OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015945 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000015946 MappableVarListInfo MVLI(VarList);
15947 SmallVector<Expr *, 8> PrivateCopies;
15948 SmallVector<Expr *, 8> Inits;
15949
Alexey Bataeve3727102018-04-18 15:57:46 +000015950 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015951 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
15952 SourceLocation ELoc;
15953 SourceRange ERange;
15954 Expr *SimpleRefExpr = RefExpr;
15955 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15956 if (Res.second) {
15957 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000015958 MVLI.ProcessedVarList.push_back(RefExpr);
15959 PrivateCopies.push_back(nullptr);
15960 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015961 }
15962 ValueDecl *D = Res.first;
15963 if (!D)
15964 continue;
15965
15966 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000015967 Type = Type.getNonReferenceType().getUnqualifiedType();
15968
15969 auto *VD = dyn_cast<VarDecl>(D);
15970
15971 // Item should be a pointer or reference to pointer.
15972 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015973 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
15974 << 0 << RefExpr->getSourceRange();
15975 continue;
15976 }
Samuel Antaocc10b852016-07-28 14:23:26 +000015977
15978 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000015979 auto VDPrivate =
15980 buildVarDecl(*this, ELoc, Type, D->getName(),
15981 D->hasAttrs() ? &D->getAttrs() : nullptr,
15982 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000015983 if (VDPrivate->isInvalidDecl())
15984 continue;
15985
15986 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000015987 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000015988 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15989
15990 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000015991 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000015992 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000015993 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
15994 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000015995 AddInitializerToDecl(VDPrivate,
15996 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000015997 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000015998
15999 // If required, build a capture to implement the privatization initialized
16000 // with the current list item value.
16001 DeclRefExpr *Ref = nullptr;
16002 if (!VD)
16003 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16004 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16005 PrivateCopies.push_back(VDPrivateRefExpr);
16006 Inits.push_back(VDInitRefExpr);
16007
16008 // We need to add a data sharing attribute for this variable to make sure it
16009 // is correctly captured. A variable that shows up in a use_device_ptr has
16010 // similar properties of a first private variable.
16011 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16012
16013 // Create a mappable component for the list item. List items in this clause
16014 // only need a component.
16015 MVLI.VarBaseDeclarations.push_back(D);
16016 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16017 MVLI.VarComponents.back().push_back(
16018 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016019 }
16020
Samuel Antaocc10b852016-07-28 14:23:26 +000016021 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016022 return nullptr;
16023
Samuel Antaocc10b852016-07-28 14:23:26 +000016024 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016025 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16026 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016027}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016028
16029OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016030 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016031 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016032 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016033 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016034 SourceLocation ELoc;
16035 SourceRange ERange;
16036 Expr *SimpleRefExpr = RefExpr;
16037 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16038 if (Res.second) {
16039 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016040 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016041 }
16042 ValueDecl *D = Res.first;
16043 if (!D)
16044 continue;
16045
16046 QualType Type = D->getType();
16047 // item should be a pointer or array or reference to pointer or array
16048 if (!Type.getNonReferenceType()->isPointerType() &&
16049 !Type.getNonReferenceType()->isArrayType()) {
16050 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16051 << 0 << RefExpr->getSourceRange();
16052 continue;
16053 }
Samuel Antao6890b092016-07-28 14:25:09 +000016054
16055 // Check if the declaration in the clause does not show up in any data
16056 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016057 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016058 if (isOpenMPPrivate(DVar.CKind)) {
16059 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16060 << getOpenMPClauseName(DVar.CKind)
16061 << getOpenMPClauseName(OMPC_is_device_ptr)
16062 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016063 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016064 continue;
16065 }
16066
Alexey Bataeve3727102018-04-18 15:57:46 +000016067 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016068 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016069 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016070 [&ConflictExpr](
16071 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16072 OpenMPClauseKind) -> bool {
16073 ConflictExpr = R.front().getAssociatedExpression();
16074 return true;
16075 })) {
16076 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16077 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16078 << ConflictExpr->getSourceRange();
16079 continue;
16080 }
16081
16082 // Store the components in the stack so that they can be used to check
16083 // against other clauses later on.
16084 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16085 DSAStack->addMappableExpressionComponents(
16086 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16087
16088 // Record the expression we've just processed.
16089 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16090
16091 // Create a mappable component for the list item. List items in this clause
16092 // only need a component. We use a null declaration to signal fields in
16093 // 'this'.
16094 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16095 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16096 "Unexpected device pointer expression!");
16097 MVLI.VarBaseDeclarations.push_back(
16098 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16099 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16100 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016101 }
16102
Samuel Antao6890b092016-07-28 14:25:09 +000016103 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016104 return nullptr;
16105
Michael Kruse4304e9d2019-02-19 16:38:20 +000016106 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16107 MVLI.VarBaseDeclarations,
16108 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016109}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016110
16111OMPClause *Sema::ActOnOpenMPAllocateClause(
16112 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16113 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16114 if (Allocator) {
16115 // OpenMP [2.11.4 allocate Clause, Description]
16116 // allocator is an expression of omp_allocator_handle_t type.
16117 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16118 return nullptr;
16119
16120 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16121 if (AllocatorRes.isInvalid())
16122 return nullptr;
16123 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16124 DSAStack->getOMPAllocatorHandleT(),
16125 Sema::AA_Initializing,
16126 /*AllowExplicit=*/true);
16127 if (AllocatorRes.isInvalid())
16128 return nullptr;
16129 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016130 } else {
16131 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16132 // allocate clauses that appear on a target construct or on constructs in a
16133 // target region must specify an allocator expression unless a requires
16134 // directive with the dynamic_allocators clause is present in the same
16135 // compilation unit.
16136 if (LangOpts.OpenMPIsDevice &&
16137 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16138 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016139 }
16140 // Analyze and build list of variables.
16141 SmallVector<Expr *, 8> Vars;
16142 for (Expr *RefExpr : VarList) {
16143 assert(RefExpr && "NULL expr in OpenMP private clause.");
16144 SourceLocation ELoc;
16145 SourceRange ERange;
16146 Expr *SimpleRefExpr = RefExpr;
16147 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16148 if (Res.second) {
16149 // It will be analyzed later.
16150 Vars.push_back(RefExpr);
16151 }
16152 ValueDecl *D = Res.first;
16153 if (!D)
16154 continue;
16155
16156 auto *VD = dyn_cast<VarDecl>(D);
16157 DeclRefExpr *Ref = nullptr;
16158 if (!VD && !CurContext->isDependentContext())
16159 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16160 Vars.push_back((VD || CurContext->isDependentContext())
16161 ? RefExpr->IgnoreParens()
16162 : Ref);
16163 }
16164
16165 if (Vars.empty())
16166 return nullptr;
16167
16168 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16169 ColonLoc, EndLoc, Vars);
16170}