blob: 19057eb39863ab9a80d75e7739820fbabf810b06 [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;
142 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 bool NowaitRegion = false;
144 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000145 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000146 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000147 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000148 /// Reference to the taskgroup task_reduction reference expression.
149 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000150 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000151 /// List of globals marked as declare target link in this target region
152 /// (isOpenMPTargetExecutionDirective(Directive) == true).
153 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000154 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000155 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000156 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
157 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000158 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000159 };
160
Alexey Bataeve3727102018-04-18 15:57:46 +0000161 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000162
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000163 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000164 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000165 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
166 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000167 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000168 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000169 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000170 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000171 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000172 /// true if all the vaiables in the target executable directives must be
173 /// captured by reference.
174 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000175 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000176 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177
Richard Smith375dec52019-05-30 23:21:14 +0000178 /// Iterators over the stack iterate in order from innermost to outermost
179 /// directive.
180 using const_iterator = StackTy::const_reverse_iterator;
181 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000182 return Stack.empty() ? const_iterator()
183 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000184 }
185 const_iterator end() const {
186 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
187 }
188 using iterator = StackTy::reverse_iterator;
189 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000190 return Stack.empty() ? iterator()
191 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000192 }
193 iterator end() {
194 return Stack.empty() ? iterator() : Stack.back().first.rend();
195 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000196
Richard Smith375dec52019-05-30 23:21:14 +0000197 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000198
Alexey Bataev4b465392017-04-26 15:06:24 +0000199 bool isStackEmpty() const {
200 return Stack.empty() ||
201 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000202 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000203 }
Richard Smith375dec52019-05-30 23:21:14 +0000204 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000205 return isStackEmpty() ? 0
206 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000207 }
208
209 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000210 size_t Size = getStackSize();
211 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000212 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000213 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000214 }
215 const SharingMapTy *getTopOfStackOrNull() const {
216 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
217 }
218 SharingMapTy &getTopOfStack() {
219 assert(!isStackEmpty() && "no current directive");
220 return *getTopOfStackOrNull();
221 }
222 const SharingMapTy &getTopOfStack() const {
223 return const_cast<DSAStackTy&>(*this).getTopOfStack();
224 }
225
226 SharingMapTy *getSecondOnStackOrNull() {
227 size_t Size = getStackSize();
228 if (Size <= 1)
229 return nullptr;
230 return &Stack.back().first[Size - 2];
231 }
232 const SharingMapTy *getSecondOnStackOrNull() const {
233 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
234 }
235
236 /// Get the stack element at a certain level (previously returned by
237 /// \c getNestingLevel).
238 ///
239 /// Note that nesting levels count from outermost to innermost, and this is
240 /// the reverse of our iteration order where new inner levels are pushed at
241 /// the front of the stack.
242 SharingMapTy &getStackElemAtLevel(unsigned Level) {
243 assert(Level < getStackSize() && "no such stack element");
244 return Stack.back().first[Level];
245 }
246 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
247 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
248 }
249
250 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
251
252 /// Checks if the variable is a local for OpenMP region.
253 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000254
Kelvin Li1408f912018-09-26 04:28:39 +0000255 /// Vector of previously declared requires directives
256 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000257 /// omp_allocator_handle_t type.
258 QualType OMPAllocatorHandleT;
259 /// Expression for the predefined allocators.
260 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
261 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000262 /// Vector of previously encountered target directives
263 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000264
Alexey Bataev758e55e2013-09-06 18:03:48 +0000265public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000266 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000267
Alexey Bataev27ef9512019-03-20 20:14:22 +0000268 /// Sets omp_allocator_handle_t type.
269 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
270 /// Gets omp_allocator_handle_t type.
271 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
272 /// Sets the given default allocator.
273 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
274 Expr *Allocator) {
275 OMPPredefinedAllocators[AllocatorKind] = Allocator;
276 }
277 /// Returns the specified default allocator.
278 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
279 return OMPPredefinedAllocators[AllocatorKind];
280 }
281
Alexey Bataevaac108a2015-06-23 04:51:00 +0000282 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000283 OpenMPClauseKind getClauseParsingMode() const {
284 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
285 return ClauseKindMode;
286 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000287 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000288
Richard Smith0621a8f2019-05-31 00:45:10 +0000289 bool isBodyComplete() const {
290 const SharingMapTy *Top = getTopOfStackOrNull();
291 return Top && Top->BodyComplete;
292 }
293 void setBodyComplete() {
294 getTopOfStack().BodyComplete = true;
295 }
296
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000297 bool isForceVarCapturing() const { return ForceCapturing; }
298 void setForceVarCapturing(bool V) { ForceCapturing = V; }
299
Alexey Bataev60705422018-10-30 15:50:12 +0000300 void setForceCaptureByReferenceInTargetExecutable(bool V) {
301 ForceCaptureByReferenceInTargetExecutable = V;
302 }
303 bool isForceCaptureByReferenceInTargetExecutable() const {
304 return ForceCaptureByReferenceInTargetExecutable;
305 }
306
Alexey Bataev758e55e2013-09-06 18:03:48 +0000307 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000308 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000309 assert(!IgnoredStackElements &&
310 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000311 if (Stack.empty() ||
312 Stack.back().second != CurrentNonCapturingFunctionScope)
313 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
314 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
315 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000316 }
317
318 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000319 assert(!IgnoredStackElements &&
320 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000321 assert(!Stack.back().first.empty() &&
322 "Data-sharing attributes stack is empty!");
323 Stack.back().first.pop_back();
324 }
325
Richard Smith0621a8f2019-05-31 00:45:10 +0000326 /// RAII object to temporarily leave the scope of a directive when we want to
327 /// logically operate in its parent.
328 class ParentDirectiveScope {
329 DSAStackTy &Self;
330 bool Active;
331 public:
332 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
333 : Self(Self), Active(false) {
334 if (Activate)
335 enable();
336 }
337 ~ParentDirectiveScope() { disable(); }
338 void disable() {
339 if (Active) {
340 --Self.IgnoredStackElements;
341 Active = false;
342 }
343 }
344 void enable() {
345 if (!Active) {
346 ++Self.IgnoredStackElements;
347 Active = true;
348 }
349 }
350 };
351
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000352 /// Marks that we're started loop parsing.
353 void loopInit() {
354 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
355 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000356 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000357 }
358 /// Start capturing of the variables in the loop context.
359 void loopStart() {
360 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
361 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000362 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000363 }
364 /// true, if variables are captured, false otherwise.
365 bool isLoopStarted() const {
366 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
367 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000368 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000369 }
370 /// Marks (or clears) declaration as possibly loop counter.
371 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000372 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000373 D ? D->getCanonicalDecl() : D;
374 }
375 /// Gets the possible loop counter decl.
376 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000377 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000378 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000379 /// Start new OpenMP region stack in new non-capturing function.
380 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000381 assert(!IgnoredStackElements &&
382 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000383 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
384 assert(!isa<CapturingScopeInfo>(CurFnScope));
385 CurrentNonCapturingFunctionScope = CurFnScope;
386 }
387 /// Pop region stack for non-capturing function.
388 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000389 assert(!IgnoredStackElements &&
390 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 if (!Stack.empty() && Stack.back().second == OldFSI) {
392 assert(Stack.back().first.empty());
393 Stack.pop_back();
394 }
395 CurrentNonCapturingFunctionScope = nullptr;
396 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
397 if (!isa<CapturingScopeInfo>(FSI)) {
398 CurrentNonCapturingFunctionScope = FSI;
399 break;
400 }
401 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402 }
403
Alexey Bataeve3727102018-04-18 15:57:46 +0000404 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000405 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000406 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000407 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000408 getCriticalWithHint(const DeclarationNameInfo &Name) const {
409 auto I = Criticals.find(Name.getAsString());
410 if (I != Criticals.end())
411 return I->second;
412 return std::make_pair(nullptr, llvm::APSInt());
413 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000414 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000415 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000416 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000417 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000419 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000420 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000421 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000422 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000423 /// \return The index of the loop control variable in the list of associated
424 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000425 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000426 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000427 /// parent region.
428 /// \return The index of the loop control variable in the list of associated
429 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000430 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000432 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000433 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000434
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000436 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000437 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000438
Alexey Bataevfa312f32017-07-21 18:48:21 +0000439 /// Adds additional information for the reduction items with the reduction id
440 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000441 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000442 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000443 /// Adds additional information for the reduction items with the reduction id
444 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000445 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000446 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000447 /// Returns the location and reduction operation from the innermost parent
448 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000449 const DSAVarData
450 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
451 BinaryOperatorKind &BOK,
452 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000453 /// Returns the location and reduction operation from the innermost parent
454 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000455 const DSAVarData
456 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
457 const Expr *&ReductionRef,
458 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000459 /// Return reduction reference expression for the current taskgroup.
460 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000461 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000462 "taskgroup reference expression requested for non taskgroup "
463 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000464 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000465 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000466 /// Checks if the given \p VD declaration is actually a taskgroup reduction
467 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000468 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000469 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
470 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000471 ->getDecl() == VD;
472 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000473
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000474 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000475 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000476 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000477 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000478 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000479 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000480 /// match specified \a CPred predicate in any directive which matches \a DPred
481 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000482 const DSAVarData
483 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
484 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
485 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000487 /// match specified \a CPred predicate in any innermost directive which
488 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000489 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000490 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000491 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
492 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000493 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000494 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000495 /// attributes which match specified \a CPred predicate at the specified
496 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000497 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000498 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000499 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000501 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000502 /// specified \a DPred predicate.
503 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000504 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000505 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000506
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000507 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000508 bool hasDirective(
509 const llvm::function_ref<bool(
510 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
511 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000512 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000515 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000516 const SharingMapTy *Top = getTopOfStackOrNull();
517 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000518 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000519 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000520 OpenMPDirectiveKind getDirective(unsigned Level) const {
521 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000522 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000523 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000524 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000525 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000526 const SharingMapTy *Parent = getSecondOnStackOrNull();
527 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000528 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000529
Kelvin Li1408f912018-09-26 04:28:39 +0000530 /// Add requires decl to internal vector
531 void addRequiresDecl(OMPRequiresDecl *RD) {
532 RequiresDecls.push_back(RD);
533 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000534
Alexey Bataev318f431b2019-03-22 15:25:12 +0000535 /// Checks if the defined 'requires' directive has specified type of clause.
536 template <typename ClauseType>
537 bool hasRequiresDeclWithClause() {
538 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
539 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
540 return isa<ClauseType>(C);
541 });
542 });
543 }
544
Kelvin Li1408f912018-09-26 04:28:39 +0000545 /// Checks for a duplicate clause amongst previously declared requires
546 /// directives
547 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
548 bool IsDuplicate = false;
549 for (OMPClause *CNew : ClauseList) {
550 for (const OMPRequiresDecl *D : RequiresDecls) {
551 for (const OMPClause *CPrev : D->clauselists()) {
552 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
553 SemaRef.Diag(CNew->getBeginLoc(),
554 diag::err_omp_requires_clause_redeclaration)
555 << getOpenMPClauseName(CNew->getClauseKind());
556 SemaRef.Diag(CPrev->getBeginLoc(),
557 diag::note_omp_requires_previous_clause)
558 << getOpenMPClauseName(CPrev->getClauseKind());
559 IsDuplicate = true;
560 }
561 }
562 }
563 }
564 return IsDuplicate;
565 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000566
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000567 /// Add location of previously encountered target to internal vector
568 void addTargetDirLocation(SourceLocation LocStart) {
569 TargetLocations.push_back(LocStart);
570 }
571
572 // Return previously encountered target region locations.
573 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
574 return TargetLocations;
575 }
576
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000577 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000578 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000579 getTopOfStack().DefaultAttr = DSA_none;
580 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000581 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000582 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000583 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000584 getTopOfStack().DefaultAttr = DSA_shared;
585 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000586 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000587 /// Set default data mapping attribute to 'tofrom:scalar'.
588 void setDefaultDMAToFromScalar(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000589 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
590 getTopOfStack().DefaultMapAttrLoc = Loc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000591 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000592
593 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000594 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000595 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000596 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000597 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000598 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000599 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000600 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000601 DefaultMapAttributes getDefaultDMA() const {
602 return isStackEmpty() ? DMA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000603 : getTopOfStack().DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000604 }
605 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000606 return getStackElemAtLevel(Level).DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000607 }
608 SourceLocation getDefaultDMALocation() const {
609 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000610 : getTopOfStack().DefaultMapAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000611 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000612
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000613 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000614 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000615 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000616 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000617 }
618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000620 void setOrderedRegion(bool IsOrdered, const Expr *Param,
621 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000622 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000623 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000624 else
Richard Smith375dec52019-05-30 23:21:14 +0000625 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000626 }
627 /// Returns true, if region is ordered (has associated 'ordered' clause),
628 /// false - otherwise.
629 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000630 if (const SharingMapTy *Top = getTopOfStackOrNull())
631 return Top->OrderedRegion.hasValue();
632 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000633 }
634 /// Returns optional parameter for the ordered region.
635 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000636 if (const SharingMapTy *Top = getTopOfStackOrNull())
637 if (Top->OrderedRegion.hasValue())
638 return Top->OrderedRegion.getValue();
639 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000640 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000641 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000642 /// 'ordered' clause), false - otherwise.
643 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000644 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
645 return Parent->OrderedRegion.hasValue();
646 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000647 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000648 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000649 std::pair<const Expr *, OMPOrderedClause *>
650 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000651 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
652 if (Parent->OrderedRegion.hasValue())
653 return Parent->OrderedRegion.getValue();
654 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000655 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000656 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000657 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000658 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000659 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000660 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000661 /// 'nowait' clause), false - otherwise.
662 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000663 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
664 return Parent->NowaitRegion;
665 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000666 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000667 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000668 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000669 if (SharingMapTy *Parent = getSecondOnStackOrNull())
670 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000671 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000672 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000673 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000674 const SharingMapTy *Top = getTopOfStackOrNull();
675 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000676 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000677
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000678 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000679 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000680 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev4b465392017-04-26 15:06:24 +0000681 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000682 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000683 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000684 const SharingMapTy *Top = getTopOfStackOrNull();
685 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000686 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000687
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000688 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000689 /// region.
690 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000691 if (SharingMapTy *Parent = getSecondOnStackOrNull())
692 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000693 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000694 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000695 bool hasInnerTeamsRegion() const {
696 return getInnerTeamsRegionLoc().isValid();
697 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000698 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000699 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000700 const SharingMapTy *Top = getTopOfStackOrNull();
701 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000702 }
703
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000704 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000705 const SharingMapTy *Top = getTopOfStackOrNull();
706 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000707 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000708 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000709 const SharingMapTy *Top = getTopOfStackOrNull();
710 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000711 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000712
Samuel Antao4c8035b2016-12-12 18:00:20 +0000713 /// Do the check specified in \a Check to all component lists and return true
714 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000715 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000716 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000717 const llvm::function_ref<
718 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000719 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000720 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000721 if (isStackEmpty())
722 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000723 auto SI = begin();
724 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000725
726 if (SI == SE)
727 return false;
728
Alexey Bataeve3727102018-04-18 15:57:46 +0000729 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000730 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000731 else
732 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000733
734 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000735 auto MI = SI->MappedExprComponents.find(VD);
736 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000737 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
738 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000739 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000740 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000741 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000742 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000743 }
744
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000745 /// Do the check specified in \a Check to all component lists at a given level
746 /// and return true if any issue is found.
747 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000748 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000749 const llvm::function_ref<
750 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000751 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000752 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000753 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000754 return false;
755
Richard Smith375dec52019-05-30 23:21:14 +0000756 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
757 auto MI = StackElem.MappedExprComponents.find(VD);
758 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000759 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
760 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000761 if (Check(L, MI->second.Kind))
762 return true;
763 return false;
764 }
765
Samuel Antao4c8035b2016-12-12 18:00:20 +0000766 /// Create a new mappable expression component list associated with a given
767 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000768 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000769 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000770 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
771 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000772 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000773 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000774 MEC.Components.resize(MEC.Components.size() + 1);
775 MEC.Components.back().append(Components.begin(), Components.end());
776 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000777 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000778
779 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000780 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000781 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000782 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000783 void addDoacrossDependClause(OMPDependClause *C,
784 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000785 SharingMapTy *Parent = getSecondOnStackOrNull();
786 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
787 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000788 }
789 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
790 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000791 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000792 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000793 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000794 return llvm::make_range(Ref.begin(), Ref.end());
795 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000796 return llvm::make_range(StackElem.DoacrossDepends.end(),
797 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000798 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000799
800 // Store types of classes which have been explicitly mapped
801 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000802 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000803 StackElem.MappedClassesQualTypes.insert(QT);
804 }
805
806 // Return set of mapped classes types
807 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000808 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000809 return StackElem.MappedClassesQualTypes.count(QT) != 0;
810 }
811
Alexey Bataeva495c642019-03-11 19:51:42 +0000812 /// Adds global declare target to the parent target region.
813 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
814 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
815 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
816 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000817 for (auto &Elem : *this) {
818 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
819 Elem.DeclareTargetLinkVarDecls.push_back(E);
820 return;
821 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000822 }
823 }
824
825 /// Returns the list of globals with declare target link if current directive
826 /// is target.
827 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
828 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
829 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000830 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000831 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000832};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000833
834bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
835 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
836}
837
838bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000839 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
840 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000841}
Alexey Bataeve3727102018-04-18 15:57:46 +0000842
Alexey Bataeved09d242014-05-28 05:53:51 +0000843} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000844
Alexey Bataeve3727102018-04-18 15:57:46 +0000845static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000846 if (const auto *FE = dyn_cast<FullExpr>(E))
847 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000848
Alexey Bataeve3727102018-04-18 15:57:46 +0000849 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000850 E = MTE->GetTemporaryExpr();
851
Alexey Bataeve3727102018-04-18 15:57:46 +0000852 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000853 E = Binder->getSubExpr();
854
Alexey Bataeve3727102018-04-18 15:57:46 +0000855 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000856 E = ICE->getSubExprAsWritten();
857 return E->IgnoreParens();
858}
859
Alexey Bataeve3727102018-04-18 15:57:46 +0000860static Expr *getExprAsWritten(Expr *E) {
861 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
862}
863
864static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
865 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
866 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000867 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000868 const auto *VD = dyn_cast<VarDecl>(D);
869 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000870 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000871 VD = VD->getCanonicalDecl();
872 D = VD;
873 } else {
874 assert(FD);
875 FD = FD->getCanonicalDecl();
876 D = FD;
877 }
878 return D;
879}
880
Alexey Bataeve3727102018-04-18 15:57:46 +0000881static ValueDecl *getCanonicalDecl(ValueDecl *D) {
882 return const_cast<ValueDecl *>(
883 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
884}
885
Richard Smith375dec52019-05-30 23:21:14 +0000886DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000887 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000888 D = getCanonicalDecl(D);
889 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000890 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000891 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000892 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000893 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
894 // in a region but not in construct]
895 // File-scope or namespace-scope variables referenced in called routines
896 // in the region are shared unless they appear in a threadprivate
897 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000898 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000899 DVar.CKind = OMPC_shared;
900
901 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
902 // in a region but not in construct]
903 // Variables with static storage duration that are declared in called
904 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000905 if (VD && VD->hasGlobalStorage())
906 DVar.CKind = OMPC_shared;
907
908 // Non-static data members are shared by default.
909 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000910 DVar.CKind = OMPC_shared;
911
Alexey Bataev758e55e2013-09-06 18:03:48 +0000912 return DVar;
913 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000914
Alexey Bataevec3da872014-01-31 05:15:34 +0000915 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
916 // in a Construct, C/C++, predetermined, p.1]
917 // Variables with automatic storage duration that are declared in a scope
918 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000919 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
920 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000921 DVar.CKind = OMPC_private;
922 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000923 }
924
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000925 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000926 // Explicitly specified attributes and local variables with predetermined
927 // attributes.
928 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000929 const DSAInfo &Data = Iter->SharingMap.lookup(D);
930 DVar.RefExpr = Data.RefExpr.getPointer();
931 DVar.PrivateCopy = Data.PrivateCopy;
932 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000933 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000934 return DVar;
935 }
936
937 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
938 // in a Construct, C/C++, implicitly determined, p.1]
939 // In a parallel or task construct, the data-sharing attributes of these
940 // variables are determined by the default clause, if present.
941 switch (Iter->DefaultAttr) {
942 case DSA_shared:
943 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000944 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000945 return DVar;
946 case DSA_none:
947 return DVar;
948 case DSA_unspecified:
949 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
950 // in a Construct, implicitly determined, p.2]
951 // In a parallel construct, if no default clause is present, these
952 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000953 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000954 if (isOpenMPParallelDirective(DVar.DKind) ||
955 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000956 DVar.CKind = OMPC_shared;
957 return DVar;
958 }
959
960 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
961 // in a Construct, implicitly determined, p.4]
962 // In a task construct, if no default clause is present, a variable that in
963 // the enclosing context is determined to be shared by all implicit tasks
964 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000965 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000966 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +0000967 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000968 do {
969 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000970 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000971 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000972 // In a task construct, if no default clause is present, a variable
973 // whose data-sharing attribute is not determined by the rules above is
974 // firstprivate.
975 DVarTemp = getDSA(I, D);
976 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000977 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000978 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000979 return DVar;
980 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000981 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000982 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000983 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000984 return DVar;
985 }
986 }
987 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
988 // in a Construct, implicitly determined, p.3]
989 // For constructs other than task, if no default clause is present, these
990 // variables inherit their data-sharing attributes from the enclosing
991 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000992 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000993}
994
Alexey Bataeve3727102018-04-18 15:57:46 +0000995const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
996 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000997 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000998 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +0000999 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001000 auto It = StackElem.AlignedMap.find(D);
1001 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001002 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001003 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001004 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001005 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001006 assert(It->second && "Unexpected nullptr expr in the aligned map");
1007 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001008}
1009
Alexey Bataeve3727102018-04-18 15:57:46 +00001010void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001011 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001012 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001013 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001014 StackElem.LCVMap.try_emplace(
1015 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001016}
1017
Alexey Bataeve3727102018-04-18 15:57:46 +00001018const DSAStackTy::LCDeclInfo
1019DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001020 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001021 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001022 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001023 auto It = StackElem.LCVMap.find(D);
1024 if (It != StackElem.LCVMap.end())
1025 return It->second;
1026 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001027}
1028
Alexey Bataeve3727102018-04-18 15:57:46 +00001029const DSAStackTy::LCDeclInfo
1030DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001031 const SharingMapTy *Parent = getSecondOnStackOrNull();
1032 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001033 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001034 auto It = Parent->LCVMap.find(D);
1035 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001036 return It->second;
1037 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001038}
1039
Alexey Bataeve3727102018-04-18 15:57:46 +00001040const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001041 const SharingMapTy *Parent = getSecondOnStackOrNull();
1042 assert(Parent && "Data-sharing attributes stack is empty");
1043 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001044 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001045 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001046 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001047 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001048 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001049}
1050
Alexey Bataeve3727102018-04-18 15:57:46 +00001051void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001052 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001053 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001055 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001056 Data.Attributes = A;
1057 Data.RefExpr.setPointer(E);
1058 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001059 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001060 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001061 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1062 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1063 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1064 (isLoopControlVariable(D).first && A == OMPC_private));
1065 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1066 Data.RefExpr.setInt(/*IntVal=*/true);
1067 return;
1068 }
1069 const bool IsLastprivate =
1070 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1071 Data.Attributes = A;
1072 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1073 Data.PrivateCopy = PrivateCopy;
1074 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001075 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001076 Data.Attributes = A;
1077 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1078 Data.PrivateCopy = nullptr;
1079 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 }
1081}
1082
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001083/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001084static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001085 StringRef Name, const AttrVec *Attrs = nullptr,
1086 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001087 DeclContext *DC = SemaRef.CurContext;
1088 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1089 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001090 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001091 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1092 if (Attrs) {
1093 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1094 I != E; ++I)
1095 Decl->addAttr(*I);
1096 }
1097 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001098 if (OrigRef) {
1099 Decl->addAttr(
1100 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1101 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001102 return Decl;
1103}
1104
1105static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1106 SourceLocation Loc,
1107 bool RefersToCapture = false) {
1108 D->setReferenced();
1109 D->markUsed(S.Context);
1110 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1111 SourceLocation(), D, RefersToCapture, Loc, Ty,
1112 VK_LValue);
1113}
1114
Alexey Bataeve3727102018-04-18 15:57:46 +00001115void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001116 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001117 D = getCanonicalDecl(D);
1118 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001119 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001120 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001121 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001122 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001123 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001124 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001125 "Additional reduction info may be specified only once for reduction "
1126 "items.");
1127 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001128 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001129 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001130 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001131 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1132 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001133 TaskgroupReductionRef =
1134 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001135 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001136}
1137
Alexey Bataeve3727102018-04-18 15:57:46 +00001138void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001139 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001140 D = getCanonicalDecl(D);
1141 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001142 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001143 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001144 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001145 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001146 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001147 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001148 "Additional reduction info may be specified only once for reduction "
1149 "items.");
1150 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001151 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001152 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001153 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001154 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1155 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001156 TaskgroupReductionRef =
1157 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001158 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001159}
1160
Alexey Bataeve3727102018-04-18 15:57:46 +00001161const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1162 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1163 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001164 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001165 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001166 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001167 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001168 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001169 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001170 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001171 if (!ReductionData.ReductionOp ||
1172 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001173 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001174 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001175 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001176 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1177 "expression for the descriptor is not "
1178 "set.");
1179 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001180 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1181 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001182 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001183 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001184}
1185
Alexey Bataeve3727102018-04-18 15:57:46 +00001186const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1187 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1188 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001189 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001190 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001191 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001192 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001193 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001194 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001195 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001196 if (!ReductionData.ReductionOp ||
1197 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001198 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001199 SR = ReductionData.ReductionRange;
1200 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001201 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1202 "expression for the descriptor is not "
1203 "set.");
1204 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001205 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1206 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001207 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001208 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001209}
1210
Richard Smith375dec52019-05-30 23:21:14 +00001211bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001212 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001213 for (const_iterator E = end(); I != E; ++I) {
1214 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1215 isOpenMPTargetExecutionDirective(I->Directive)) {
1216 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1217 Scope *CurScope = getCurScope();
1218 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1219 CurScope = CurScope->getParent();
1220 return CurScope != TopScope;
1221 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001222 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001223 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001224}
1225
Joel E. Dennyd2649292019-01-04 22:11:56 +00001226static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1227 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001228 bool *IsClassType = nullptr) {
1229 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001230 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001231 bool IsConstant = Type.isConstant(Context);
1232 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001233 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1234 ? Type->getAsCXXRecordDecl()
1235 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001236 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1237 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1238 RD = CTD->getTemplatedDecl();
1239 if (IsClassType)
1240 *IsClassType = RD;
1241 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1242 RD->hasDefinition() && RD->hasMutableFields());
1243}
1244
Joel E. Dennyd2649292019-01-04 22:11:56 +00001245static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1246 QualType Type, OpenMPClauseKind CKind,
1247 SourceLocation ELoc,
1248 bool AcceptIfMutable = true,
1249 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001250 ASTContext &Context = SemaRef.getASTContext();
1251 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001252 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1253 unsigned Diag = ListItemNotVar
1254 ? diag::err_omp_const_list_item
1255 : IsClassType ? diag::err_omp_const_not_mutable_variable
1256 : diag::err_omp_const_variable;
1257 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1258 if (!ListItemNotVar && D) {
1259 const VarDecl *VD = dyn_cast<VarDecl>(D);
1260 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1261 VarDecl::DeclarationOnly;
1262 SemaRef.Diag(D->getLocation(),
1263 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1264 << D;
1265 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001266 return true;
1267 }
1268 return false;
1269}
1270
Alexey Bataeve3727102018-04-18 15:57:46 +00001271const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1272 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001273 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001274 DSAVarData DVar;
1275
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001276 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001277 auto TI = Threadprivates.find(D);
1278 if (TI != Threadprivates.end()) {
1279 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001280 DVar.CKind = OMPC_threadprivate;
1281 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001282 }
1283 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001284 DVar.RefExpr = buildDeclRefExpr(
1285 SemaRef, VD, D->getType().getNonReferenceType(),
1286 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1287 DVar.CKind = OMPC_threadprivate;
1288 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001289 return DVar;
1290 }
1291 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1292 // in a Construct, C/C++, predetermined, p.1]
1293 // Variables appearing in threadprivate directives are threadprivate.
1294 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1295 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1296 SemaRef.getLangOpts().OpenMPUseTLS &&
1297 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1298 (VD && VD->getStorageClass() == SC_Register &&
1299 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1300 DVar.RefExpr = buildDeclRefExpr(
1301 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1302 DVar.CKind = OMPC_threadprivate;
1303 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1304 return DVar;
1305 }
1306 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1307 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1308 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001309 const_iterator IterTarget =
1310 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1311 return isOpenMPTargetExecutionDirective(Data.Directive);
1312 });
1313 if (IterTarget != end()) {
1314 const_iterator ParentIterTarget = IterTarget + 1;
1315 for (const_iterator Iter = begin();
1316 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001317 if (isOpenMPLocal(VD, Iter)) {
1318 DVar.RefExpr =
1319 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1320 D->getLocation());
1321 DVar.CKind = OMPC_threadprivate;
1322 return DVar;
1323 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001324 }
Richard Smith375dec52019-05-30 23:21:14 +00001325 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001326 auto DSAIter = IterTarget->SharingMap.find(D);
1327 if (DSAIter != IterTarget->SharingMap.end() &&
1328 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1329 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1330 DVar.CKind = OMPC_threadprivate;
1331 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001332 }
Richard Smith375dec52019-05-30 23:21:14 +00001333 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001334 if (!SemaRef.isOpenMPCapturedByRef(
1335 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001336 DVar.RefExpr =
1337 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1338 IterTarget->ConstructLoc);
1339 DVar.CKind = OMPC_threadprivate;
1340 return DVar;
1341 }
1342 }
1343 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001344 }
1345
Alexey Bataev4b465392017-04-26 15:06:24 +00001346 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001347 // Not in OpenMP execution region and top scope was already checked.
1348 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001349
Alexey Bataev758e55e2013-09-06 18:03:48 +00001350 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001351 // in a Construct, C/C++, predetermined, p.4]
1352 // Static data members are shared.
1353 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1354 // in a Construct, C/C++, predetermined, p.7]
1355 // Variables with static storage duration that are declared in a scope
1356 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001357 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001358 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001359 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001360 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001361 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001362
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001363 DVar.CKind = OMPC_shared;
1364 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001365 }
1366
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001367 // The predetermined shared attribute for const-qualified types having no
1368 // mutable members was removed after OpenMP 3.1.
1369 if (SemaRef.LangOpts.OpenMP <= 31) {
1370 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1371 // in a Construct, C/C++, predetermined, p.6]
1372 // Variables with const qualified type having no mutable member are
1373 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001374 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001375 // Variables with const-qualified type having no mutable member may be
1376 // listed in a firstprivate clause, even if they are static data members.
1377 DSAVarData DVarTemp = hasInnermostDSA(
1378 D,
1379 [](OpenMPClauseKind C) {
1380 return C == OMPC_firstprivate || C == OMPC_shared;
1381 },
1382 MatchesAlways, FromParent);
1383 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1384 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001385
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001386 DVar.CKind = OMPC_shared;
1387 return DVar;
1388 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001389 }
1390
Alexey Bataev758e55e2013-09-06 18:03:48 +00001391 // Explicitly specified attributes and local variables with predetermined
1392 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001393 const_iterator I = begin();
1394 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001395 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001396 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001397 auto It = I->SharingMap.find(D);
1398 if (It != I->SharingMap.end()) {
1399 const DSAInfo &Data = It->getSecond();
1400 DVar.RefExpr = Data.RefExpr.getPointer();
1401 DVar.PrivateCopy = Data.PrivateCopy;
1402 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001403 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001404 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001405 }
1406
1407 return DVar;
1408}
1409
Alexey Bataeve3727102018-04-18 15:57:46 +00001410const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1411 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001412 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001413 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001414 return getDSA(I, D);
1415 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001416 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001417 const_iterator StartI = begin();
1418 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001419 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001420 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001421 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001422}
1423
Alexey Bataeve3727102018-04-18 15:57:46 +00001424const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001425DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001426 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1427 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001428 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001429 if (isStackEmpty())
1430 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001431 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001432 const_iterator I = begin();
1433 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001434 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001435 ++I;
1436 for (; I != EndI; ++I) {
1437 if (!DPred(I->Directive) &&
1438 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001439 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001440 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001441 DSAVarData DVar = getDSA(NewI, D);
1442 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001443 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001444 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001445 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001446}
1447
Alexey Bataeve3727102018-04-18 15:57:46 +00001448const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001449 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1450 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001451 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001452 if (isStackEmpty())
1453 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001454 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001455 const_iterator StartI = begin();
1456 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001457 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001458 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001459 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001460 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001461 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001462 DSAVarData DVar = getDSA(NewI, D);
1463 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001464}
1465
Alexey Bataevaac108a2015-06-23 04:51:00 +00001466bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001467 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1468 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001469 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001470 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001471 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001472 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1473 auto I = StackElem.SharingMap.find(D);
1474 if (I != StackElem.SharingMap.end() &&
1475 I->getSecond().RefExpr.getPointer() &&
1476 CPred(I->getSecond().Attributes) &&
1477 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001478 return true;
1479 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001480 auto LI = StackElem.LCVMap.find(D);
1481 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001482 return CPred(OMPC_private);
1483 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001484}
1485
Samuel Antao4be30e92015-10-02 17:14:03 +00001486bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001487 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1488 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001489 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001490 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001491 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1492 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001493}
1494
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001495bool DSAStackTy::hasDirective(
1496 const llvm::function_ref<bool(OpenMPDirectiveKind,
1497 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001498 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001499 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001500 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001501 size_t Skip = FromParent ? 2 : 1;
1502 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1503 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001504 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1505 return true;
1506 }
1507 return false;
1508}
1509
Alexey Bataev758e55e2013-09-06 18:03:48 +00001510void Sema::InitDataSharingAttributesStack() {
1511 VarDataSharingAttributesStack = new DSAStackTy(*this);
1512}
1513
1514#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1515
Alexey Bataev4b465392017-04-26 15:06:24 +00001516void Sema::pushOpenMPFunctionRegion() {
1517 DSAStack->pushFunction();
1518}
1519
1520void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1521 DSAStack->popFunction(OldFSI);
1522}
1523
Alexey Bataevc416e642019-02-08 18:02:25 +00001524static bool isOpenMPDeviceDelayedContext(Sema &S) {
1525 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1526 "Expected OpenMP device compilation.");
1527 return !S.isInOpenMPTargetExecutionDirective() &&
1528 !S.isInOpenMPDeclareTargetContext();
1529}
1530
1531/// Do we know that we will eventually codegen the given function?
1532static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1533 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1534 "Expected OpenMP device compilation.");
1535 // Templates are emitted when they're instantiated.
1536 if (FD->isDependentContext())
1537 return false;
1538
1539 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1540 FD->getCanonicalDecl()))
1541 return true;
1542
1543 // Otherwise, the function is known-emitted if it's in our set of
1544 // known-emitted functions.
1545 return S.DeviceKnownEmittedFns.count(FD) > 0;
1546}
1547
1548Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1549 unsigned DiagID) {
1550 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1551 "Expected OpenMP device compilation.");
1552 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1553 !isKnownEmitted(*this, getCurFunctionDecl()))
1554 ? DeviceDiagBuilder::K_Deferred
1555 : DeviceDiagBuilder::K_Immediate,
1556 Loc, DiagID, getCurFunctionDecl(), *this);
1557}
1558
1559void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1560 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1561 "Expected OpenMP device compilation.");
1562 assert(Callee && "Callee may not be null.");
1563 FunctionDecl *Caller = getCurFunctionDecl();
1564
1565 // If the caller is known-emitted, mark the callee as known-emitted.
1566 // Otherwise, mark the call in our call graph so we can traverse it later.
1567 if (!isOpenMPDeviceDelayedContext(*this) ||
1568 (Caller && isKnownEmitted(*this, Caller)))
1569 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1570 else if (Caller)
1571 DeviceCallGraph[Caller].insert({Callee, Loc});
1572}
1573
Alexey Bataev123ad192019-02-27 20:29:45 +00001574void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1575 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1576 "OpenMP device compilation mode is expected.");
1577 QualType Ty = E->getType();
1578 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001579 ((Ty->isFloat128Type() ||
1580 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1581 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001582 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1583 !Context.getTargetInfo().hasInt128Type()))
1584 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1585 << Ty << E->getSourceRange();
1586}
1587
Alexey Bataeve3727102018-04-18 15:57:46 +00001588bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001589 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1590
Alexey Bataeve3727102018-04-18 15:57:46 +00001591 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001592 bool IsByRef = true;
1593
1594 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001595 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001596 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001597
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001598 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001599 // This table summarizes how a given variable should be passed to the device
1600 // given its type and the clauses where it appears. This table is based on
1601 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1602 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1603 //
1604 // =========================================================================
1605 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1606 // | |(tofrom:scalar)| | pvt | | | |
1607 // =========================================================================
1608 // | scl | | | | - | | bycopy|
1609 // | scl | | - | x | - | - | bycopy|
1610 // | scl | | x | - | - | - | null |
1611 // | scl | x | | | - | | byref |
1612 // | scl | x | - | x | - | - | bycopy|
1613 // | scl | x | x | - | - | - | null |
1614 // | scl | | - | - | - | x | byref |
1615 // | scl | x | - | - | - | x | byref |
1616 //
1617 // | agg | n.a. | | | - | | byref |
1618 // | agg | n.a. | - | x | - | - | byref |
1619 // | agg | n.a. | x | - | - | - | null |
1620 // | agg | n.a. | - | - | - | x | byref |
1621 // | agg | n.a. | - | - | - | x[] | byref |
1622 //
1623 // | ptr | n.a. | | | - | | bycopy|
1624 // | ptr | n.a. | - | x | - | - | bycopy|
1625 // | ptr | n.a. | x | - | - | - | null |
1626 // | ptr | n.a. | - | - | - | x | byref |
1627 // | ptr | n.a. | - | - | - | x[] | bycopy|
1628 // | ptr | n.a. | - | - | x | | bycopy|
1629 // | ptr | n.a. | - | - | x | x | bycopy|
1630 // | ptr | n.a. | - | - | x | x[] | bycopy|
1631 // =========================================================================
1632 // Legend:
1633 // scl - scalar
1634 // ptr - pointer
1635 // agg - aggregate
1636 // x - applies
1637 // - - invalid in this combination
1638 // [] - mapped with an array section
1639 // byref - should be mapped by reference
1640 // byval - should be mapped by value
1641 // null - initialize a local variable to null on the device
1642 //
1643 // Observations:
1644 // - All scalar declarations that show up in a map clause have to be passed
1645 // by reference, because they may have been mapped in the enclosing data
1646 // environment.
1647 // - If the scalar value does not fit the size of uintptr, it has to be
1648 // passed by reference, regardless the result in the table above.
1649 // - For pointers mapped by value that have either an implicit map or an
1650 // array section, the runtime library may pass the NULL value to the
1651 // device instead of the value passed to it by the compiler.
1652
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001653 if (Ty->isReferenceType())
1654 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001655
1656 // Locate map clauses and see if the variable being captured is referred to
1657 // in any of those clauses. Here we only care about variables, not fields,
1658 // because fields are part of aggregates.
1659 bool IsVariableUsedInMapClause = false;
1660 bool IsVariableAssociatedWithSection = false;
1661
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001662 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001663 D, Level,
1664 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1665 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001666 MapExprComponents,
1667 OpenMPClauseKind WhereFoundClauseKind) {
1668 // Only the map clause information influences how a variable is
1669 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001670 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001671 if (WhereFoundClauseKind != OMPC_map)
1672 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001673
1674 auto EI = MapExprComponents.rbegin();
1675 auto EE = MapExprComponents.rend();
1676
1677 assert(EI != EE && "Invalid map expression!");
1678
1679 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1680 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1681
1682 ++EI;
1683 if (EI == EE)
1684 return false;
1685
1686 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1687 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1688 isa<MemberExpr>(EI->getAssociatedExpression())) {
1689 IsVariableAssociatedWithSection = true;
1690 // There is nothing more we need to know about this variable.
1691 return true;
1692 }
1693
1694 // Keep looking for more map info.
1695 return false;
1696 });
1697
1698 if (IsVariableUsedInMapClause) {
1699 // If variable is identified in a map clause it is always captured by
1700 // reference except if it is a pointer that is dereferenced somehow.
1701 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1702 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001703 // By default, all the data that has a scalar type is mapped by copy
1704 // (except for reduction variables).
1705 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001706 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1707 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001708 !Ty->isScalarType() ||
1709 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1710 DSAStack->hasExplicitDSA(
1711 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001712 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001713 }
1714
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001715 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001716 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001717 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1718 !Ty->isAnyPointerType()) ||
1719 !DSAStack->hasExplicitDSA(
1720 D,
1721 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1722 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001723 // If the variable is artificial and must be captured by value - try to
1724 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001725 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1726 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001727 }
1728
Samuel Antao86ace552016-04-27 22:40:57 +00001729 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001730 // and alignment, because the runtime library only deals with uintptr types.
1731 // If it does not fit the uintptr size, we need to pass the data by reference
1732 // instead.
1733 if (!IsByRef &&
1734 (Ctx.getTypeSizeInChars(Ty) >
1735 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001736 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001737 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001738 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001739
1740 return IsByRef;
1741}
1742
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001743unsigned Sema::getOpenMPNestingLevel() const {
1744 assert(getLangOpts().OpenMP);
1745 return DSAStack->getNestingLevel();
1746}
1747
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001748bool Sema::isInOpenMPTargetExecutionDirective() const {
1749 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1750 !DSAStack->isClauseParsingMode()) ||
1751 DSAStack->hasDirective(
1752 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1753 SourceLocation) -> bool {
1754 return isOpenMPTargetExecutionDirective(K);
1755 },
1756 false);
1757}
1758
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001759VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1760 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001761 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001762 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001763
Richard Smith0621a8f2019-05-31 00:45:10 +00001764 // If we want to determine whether the variable should be captured from the
1765 // perspective of the current capturing scope, and we've already left all the
1766 // capturing scopes of the top directive on the stack, check from the
1767 // perspective of its parent directive (if any) instead.
1768 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1769 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1770
Samuel Antao4be30e92015-10-02 17:14:03 +00001771 // If we are attempting to capture a global variable in a directive with
1772 // 'target' we return true so that this global is also mapped to the device.
1773 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001774 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001775 if (VD && !VD->hasLocalStorage() &&
1776 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1777 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001778 // Try to mark variable as declare target if it is used in capturing
1779 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001780 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001781 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001782 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001783 } else if (isInOpenMPTargetExecutionDirective()) {
1784 // If the declaration is enclosed in a 'declare target' directive,
1785 // then it should not be captured.
1786 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001787 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001788 return nullptr;
1789 return VD;
1790 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001791 }
Alexey Bataev60705422018-10-30 15:50:12 +00001792 // Capture variables captured by reference in lambdas for target-based
1793 // directives.
Richard Smith0621a8f2019-05-31 00:45:10 +00001794 // FIXME: Triggering capture from here is completely inappropriate.
Alexey Bataev60705422018-10-30 15:50:12 +00001795 if (VD && !DSAStack->isClauseParsingMode()) {
1796 if (const auto *RD = VD->getType()
1797 .getCanonicalType()
1798 .getNonReferenceType()
1799 ->getAsCXXRecordDecl()) {
1800 bool SavedForceCaptureByReferenceInTargetExecutable =
1801 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1802 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Richard Smith0621a8f2019-05-31 00:45:10 +00001803 InParentDirectiveRAII.disable();
Alexey Bataevd1840e52018-11-16 21:13:33 +00001804 if (RD->isLambda()) {
1805 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1806 FieldDecl *ThisCapture;
1807 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001808 for (const LambdaCapture &LC : RD->captures()) {
1809 if (LC.getCaptureKind() == LCK_ByRef) {
1810 VarDecl *VD = LC.getCapturedVar();
1811 DeclContext *VDC = VD->getDeclContext();
1812 if (!VDC->Encloses(CurContext))
1813 continue;
1814 DSAStackTy::DSAVarData DVarPrivate =
1815 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1816 // Do not capture already captured variables.
1817 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1818 DVarPrivate.CKind == OMPC_unknown &&
1819 !DSAStack->checkMappableExprComponentListsForDecl(
1820 D, /*CurrentRegionOnly=*/true,
1821 [](OMPClauseMappableExprCommon::
1822 MappableExprComponentListRef,
1823 OpenMPClauseKind) { return true; }))
1824 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1825 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001826 QualType ThisTy = getCurrentThisType();
1827 if (!ThisTy.isNull() &&
1828 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1829 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001830 }
1831 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001832 }
Richard Smith0621a8f2019-05-31 00:45:10 +00001833 if (CheckScopeInfo && DSAStack->isBodyComplete())
1834 InParentDirectiveRAII.enable();
Alexey Bataev60705422018-10-30 15:50:12 +00001835 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1836 SavedForceCaptureByReferenceInTargetExecutable);
1837 }
1838 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001839
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001840 if (CheckScopeInfo) {
1841 bool OpenMPFound = false;
1842 for (unsigned I = StopAt + 1; I > 0; --I) {
1843 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1844 if(!isa<CapturingScopeInfo>(FSI))
1845 return nullptr;
1846 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1847 if (RSI->CapRegionKind == CR_OpenMP) {
1848 OpenMPFound = true;
1849 break;
1850 }
1851 }
1852 if (!OpenMPFound)
1853 return nullptr;
1854 }
1855
Alexey Bataev48977c32015-08-04 08:10:48 +00001856 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1857 (!DSAStack->isClauseParsingMode() ||
1858 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001859 auto &&Info = DSAStack->isLoopControlVariable(D);
1860 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001861 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001862 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001863 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001864 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001865 DSAStackTy::DSAVarData DVarPrivate =
1866 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001867 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001868 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001869 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1870 [](OpenMPDirectiveKind) { return true; },
1871 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001872 // The variable is not private or it is the variable in the directive with
1873 // default(none) clause and not used in any clause.
1874 if (DVarPrivate.CKind != OMPC_unknown ||
1875 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001876 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001877 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001878 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001879}
1880
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001881void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1882 unsigned Level) const {
1883 SmallVector<OpenMPDirectiveKind, 4> Regions;
1884 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1885 FunctionScopesIndex -= Regions.size();
1886}
1887
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001888void Sema::startOpenMPLoop() {
1889 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1890 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1891 DSAStack->loopInit();
1892}
1893
Alexey Bataeve3727102018-04-18 15:57:46 +00001894bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001895 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001896 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1897 if (DSAStack->getAssociatedLoops() > 0 &&
1898 !DSAStack->isLoopStarted()) {
1899 DSAStack->resetPossibleLoopCounter(D);
1900 DSAStack->loopStart();
1901 return true;
1902 }
1903 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1904 DSAStack->isLoopControlVariable(D).first) &&
1905 !DSAStack->hasExplicitDSA(
1906 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1907 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1908 return true;
1909 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001910 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001911 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001912 (DSAStack->isClauseParsingMode() &&
1913 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001914 // Consider taskgroup reduction descriptor variable a private to avoid
1915 // possible capture in the region.
1916 (DSAStack->hasExplicitDirective(
1917 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1918 Level) &&
1919 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001920}
1921
Alexey Bataeve3727102018-04-18 15:57:46 +00001922void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1923 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001924 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1925 D = getCanonicalDecl(D);
1926 OpenMPClauseKind OMPC = OMPC_unknown;
1927 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1928 const unsigned NewLevel = I - 1;
1929 if (DSAStack->hasExplicitDSA(D,
1930 [&OMPC](const OpenMPClauseKind K) {
1931 if (isOpenMPPrivate(K)) {
1932 OMPC = K;
1933 return true;
1934 }
1935 return false;
1936 },
1937 NewLevel))
1938 break;
1939 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1940 D, NewLevel,
1941 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1942 OpenMPClauseKind) { return true; })) {
1943 OMPC = OMPC_map;
1944 break;
1945 }
1946 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1947 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001948 OMPC = OMPC_map;
1949 if (D->getType()->isScalarType() &&
1950 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1951 DefaultMapAttributes::DMA_tofrom_scalar)
1952 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001953 break;
1954 }
1955 }
1956 if (OMPC != OMPC_unknown)
1957 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1958}
1959
Alexey Bataeve3727102018-04-18 15:57:46 +00001960bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1961 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001962 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1963 // Return true if the current level is no longer enclosed in a target region.
1964
Alexey Bataeve3727102018-04-18 15:57:46 +00001965 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001966 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001967 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1968 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001969}
1970
Alexey Bataeved09d242014-05-28 05:53:51 +00001971void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001972
1973void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1974 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001975 Scope *CurScope, SourceLocation Loc) {
1976 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001977 PushExpressionEvaluationContext(
1978 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001979}
1980
Alexey Bataevaac108a2015-06-23 04:51:00 +00001981void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1982 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001983}
1984
Alexey Bataevaac108a2015-06-23 04:51:00 +00001985void Sema::EndOpenMPClause() {
1986 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001987}
1988
Alexey Bataeve106f252019-04-01 14:25:31 +00001989static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
1990 ArrayRef<OMPClause *> Clauses);
1991
Alexey Bataev758e55e2013-09-06 18:03:48 +00001992void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001993 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1994 // A variable of class type (or array thereof) that appears in a lastprivate
1995 // clause requires an accessible, unambiguous default constructor for the
1996 // class type, unless the list item is also specified in a firstprivate
1997 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001998 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1999 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002000 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2001 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002002 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002003 if (DE->isValueDependent() || DE->isTypeDependent()) {
2004 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002005 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002006 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002007 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002008 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002009 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002010 const DSAStackTy::DSAVarData DVar =
2011 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002012 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002013 // Generate helper private variable and initialize it with the
2014 // default value. The address of the original variable is replaced
2015 // by the address of the new private variable in CodeGen. This new
2016 // variable is not added to IdResolver, so the code in the OpenMP
2017 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002018 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002019 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002020 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002021 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002022 if (VDPrivate->isInvalidDecl()) {
2023 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002024 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002025 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002026 PrivateCopies.push_back(buildDeclRefExpr(
2027 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002028 } else {
2029 // The variable is also a firstprivate, so initialization sequence
2030 // for private copy is generated already.
2031 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002032 }
2033 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002034 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002035 }
2036 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002037 // Check allocate clauses.
2038 if (!CurContext->isDependentContext())
2039 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002040 }
2041
Alexey Bataev758e55e2013-09-06 18:03:48 +00002042 DSAStack->pop();
2043 DiscardCleanupsInEvaluationContext();
2044 PopExpressionEvaluationContext();
2045}
2046
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002047static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2048 Expr *NumIterations, Sema &SemaRef,
2049 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002050
Alexey Bataeva769e072013-03-22 06:34:35 +00002051namespace {
2052
Alexey Bataeve3727102018-04-18 15:57:46 +00002053class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002054private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002055 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002056
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002057public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002058 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002059 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002060 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002061 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002062 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002063 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2064 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002065 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002066 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002067 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002068
2069 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2070 return llvm::make_unique<VarDeclFilterCCC>(*this);
2071 }
2072
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002073};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002074
Alexey Bataeve3727102018-04-18 15:57:46 +00002075class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002076private:
2077 Sema &SemaRef;
2078
2079public:
2080 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2081 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2082 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002083 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2084 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002085 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2086 SemaRef.getCurScope());
2087 }
2088 return false;
2089 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002090
2091 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2092 return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
2093 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002094};
2095
Alexey Bataeved09d242014-05-28 05:53:51 +00002096} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002097
2098ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2099 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002100 const DeclarationNameInfo &Id,
2101 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002102 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2103 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2104
2105 if (Lookup.isAmbiguous())
2106 return ExprError();
2107
2108 VarDecl *VD;
2109 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002110 VarDeclFilterCCC CCC(*this);
2111 if (TypoCorrection Corrected =
2112 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2113 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002114 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002115 PDiag(Lookup.empty()
2116 ? diag::err_undeclared_var_use_suggest
2117 : diag::err_omp_expected_var_arg_suggest)
2118 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002119 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002120 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002121 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2122 : diag::err_omp_expected_var_arg)
2123 << Id.getName();
2124 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002125 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002126 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2127 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2128 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2129 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002130 }
2131 Lookup.suppressDiagnostics();
2132
2133 // OpenMP [2.9.2, Syntax, C/C++]
2134 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002135 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002136 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002137 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002138 bool IsDecl =
2139 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002140 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002141 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2142 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002143 return ExprError();
2144 }
2145
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002146 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002147 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002148 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2149 // A threadprivate directive for file-scope variables must appear outside
2150 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002151 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2152 !getCurLexicalContext()->isTranslationUnit()) {
2153 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002154 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002155 bool IsDecl =
2156 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2157 Diag(VD->getLocation(),
2158 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2159 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002160 return ExprError();
2161 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002162 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2163 // A threadprivate directive for static class member variables must appear
2164 // in the class definition, in the same scope in which the member
2165 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002166 if (CanonicalVD->isStaticDataMember() &&
2167 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2168 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002169 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002170 bool IsDecl =
2171 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2172 Diag(VD->getLocation(),
2173 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2174 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002175 return ExprError();
2176 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002177 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2178 // A threadprivate directive for namespace-scope variables must appear
2179 // outside any definition or declaration other than the namespace
2180 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002181 if (CanonicalVD->getDeclContext()->isNamespace() &&
2182 (!getCurLexicalContext()->isFileContext() ||
2183 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2184 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002185 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002186 bool IsDecl =
2187 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2188 Diag(VD->getLocation(),
2189 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2190 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002191 return ExprError();
2192 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002193 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2194 // A threadprivate directive for static block-scope variables must appear
2195 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002196 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002197 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002198 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002199 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002200 bool IsDecl =
2201 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2202 Diag(VD->getLocation(),
2203 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2204 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002205 return ExprError();
2206 }
2207
2208 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2209 // A threadprivate directive must lexically precede all references to any
2210 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002211 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2212 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002213 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002214 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002215 return ExprError();
2216 }
2217
2218 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002219 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2220 SourceLocation(), VD,
2221 /*RefersToEnclosingVariableOrCapture=*/false,
2222 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002223}
2224
Alexey Bataeved09d242014-05-28 05:53:51 +00002225Sema::DeclGroupPtrTy
2226Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2227 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002228 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002229 CurContext->addDecl(D);
2230 return DeclGroupPtrTy::make(DeclGroupRef(D));
2231 }
David Blaikie0403cb12016-01-15 23:43:25 +00002232 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002233}
2234
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002235namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002236class LocalVarRefChecker final
2237 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002238 Sema &SemaRef;
2239
2240public:
2241 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002242 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002243 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002244 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002245 diag::err_omp_local_var_in_threadprivate_init)
2246 << E->getSourceRange();
2247 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2248 << VD << VD->getSourceRange();
2249 return true;
2250 }
2251 }
2252 return false;
2253 }
2254 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002255 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002256 if (Child && Visit(Child))
2257 return true;
2258 }
2259 return false;
2260 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002261 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002262};
2263} // namespace
2264
Alexey Bataeved09d242014-05-28 05:53:51 +00002265OMPThreadPrivateDecl *
2266Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002267 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002268 for (Expr *RefExpr : VarList) {
2269 auto *DE = cast<DeclRefExpr>(RefExpr);
2270 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002271 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002272
Alexey Bataev376b4a42016-02-09 09:41:09 +00002273 // Mark variable as used.
2274 VD->setReferenced();
2275 VD->markUsed(Context);
2276
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002277 QualType QType = VD->getType();
2278 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2279 // It will be analyzed later.
2280 Vars.push_back(DE);
2281 continue;
2282 }
2283
Alexey Bataeva769e072013-03-22 06:34:35 +00002284 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2285 // A threadprivate variable must not have an incomplete type.
2286 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002287 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002288 continue;
2289 }
2290
2291 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2292 // A threadprivate variable must not have a reference type.
2293 if (VD->getType()->isReferenceType()) {
2294 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002295 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2296 bool IsDecl =
2297 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2298 Diag(VD->getLocation(),
2299 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2300 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002301 continue;
2302 }
2303
Samuel Antaof8b50122015-07-13 22:54:53 +00002304 // Check if this is a TLS variable. If TLS is not being supported, produce
2305 // the corresponding diagnostic.
2306 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2307 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2308 getLangOpts().OpenMPUseTLS &&
2309 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002310 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2311 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002312 Diag(ILoc, diag::err_omp_var_thread_local)
2313 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002314 bool IsDecl =
2315 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2316 Diag(VD->getLocation(),
2317 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2318 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002319 continue;
2320 }
2321
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002322 // Check if initial value of threadprivate variable reference variable with
2323 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002324 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002325 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002326 if (Checker.Visit(Init))
2327 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002328 }
2329
Alexey Bataeved09d242014-05-28 05:53:51 +00002330 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002331 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002332 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2333 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002334 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002335 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002336 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002337 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002338 if (!Vars.empty()) {
2339 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2340 Vars);
2341 D->setAccess(AS_public);
2342 }
2343 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002344}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002345
Alexey Bataev27ef9512019-03-20 20:14:22 +00002346static OMPAllocateDeclAttr::AllocatorTypeTy
2347getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2348 if (!Allocator)
2349 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2350 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2351 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002352 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002353 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002354 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002355 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002356 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2357 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2358 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002359 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002360 llvm::FoldingSetNodeID AEId, DAEId;
2361 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2362 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2363 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002364 AllocatorKindRes = AllocatorKind;
2365 break;
2366 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002367 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002368 return AllocatorKindRes;
2369}
2370
Alexey Bataeve106f252019-04-01 14:25:31 +00002371static bool checkPreviousOMPAllocateAttribute(
2372 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2373 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2374 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2375 return false;
2376 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2377 Expr *PrevAllocator = A->getAllocator();
2378 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2379 getAllocatorKind(S, Stack, PrevAllocator);
2380 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2381 if (AllocatorsMatch &&
2382 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2383 Allocator && PrevAllocator) {
2384 const Expr *AE = Allocator->IgnoreParenImpCasts();
2385 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2386 llvm::FoldingSetNodeID AEId, PAEId;
2387 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2388 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2389 AllocatorsMatch = AEId == PAEId;
2390 }
2391 if (!AllocatorsMatch) {
2392 SmallString<256> AllocatorBuffer;
2393 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2394 if (Allocator)
2395 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2396 SmallString<256> PrevAllocatorBuffer;
2397 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2398 if (PrevAllocator)
2399 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2400 S.getPrintingPolicy());
2401
2402 SourceLocation AllocatorLoc =
2403 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2404 SourceRange AllocatorRange =
2405 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2406 SourceLocation PrevAllocatorLoc =
2407 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2408 SourceRange PrevAllocatorRange =
2409 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2410 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2411 << (Allocator ? 1 : 0) << AllocatorStream.str()
2412 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2413 << AllocatorRange;
2414 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2415 << PrevAllocatorRange;
2416 return true;
2417 }
2418 return false;
2419}
2420
2421static void
2422applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2423 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2424 Expr *Allocator, SourceRange SR) {
2425 if (VD->hasAttr<OMPAllocateDeclAttr>())
2426 return;
2427 if (Allocator &&
2428 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2429 Allocator->isInstantiationDependent() ||
2430 Allocator->containsUnexpandedParameterPack()))
2431 return;
2432 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2433 Allocator, SR);
2434 VD->addAttr(A);
2435 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2436 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2437}
2438
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002439Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2440 SourceLocation Loc, ArrayRef<Expr *> VarList,
2441 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2442 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2443 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002444 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002445 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2446 // allocate directives that appear in a target region must specify an
2447 // allocator clause unless a requires directive with the dynamic_allocators
2448 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002449 if (LangOpts.OpenMPIsDevice &&
2450 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002451 targetDiag(Loc, diag::err_expected_allocator_clause);
2452 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002453 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002454 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002455 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2456 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002457 SmallVector<Expr *, 8> Vars;
2458 for (Expr *RefExpr : VarList) {
2459 auto *DE = cast<DeclRefExpr>(RefExpr);
2460 auto *VD = cast<VarDecl>(DE->getDecl());
2461
2462 // Check if this is a TLS variable or global register.
2463 if (VD->getTLSKind() != VarDecl::TLS_None ||
2464 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2465 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2466 !VD->isLocalVarDecl()))
2467 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002468
Alexey Bataev282555a2019-03-19 20:33:44 +00002469 // If the used several times in the allocate directive, the same allocator
2470 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002471 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2472 AllocatorKind, Allocator))
2473 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002474
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002475 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2476 // If a list item has a static storage type, the allocator expression in the
2477 // allocator clause must be a constant expression that evaluates to one of
2478 // the predefined memory allocator values.
2479 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002480 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002481 Diag(Allocator->getExprLoc(),
2482 diag::err_omp_expected_predefined_allocator)
2483 << Allocator->getSourceRange();
2484 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2485 VarDecl::DeclarationOnly;
2486 Diag(VD->getLocation(),
2487 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2488 << VD;
2489 continue;
2490 }
2491 }
2492
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002493 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002494 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2495 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002496 }
2497 if (Vars.empty())
2498 return nullptr;
2499 if (!Owner)
2500 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002501 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002502 D->setAccess(AS_public);
2503 Owner->addDecl(D);
2504 return DeclGroupPtrTy::make(DeclGroupRef(D));
2505}
2506
2507Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002508Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2509 ArrayRef<OMPClause *> ClauseList) {
2510 OMPRequiresDecl *D = nullptr;
2511 if (!CurContext->isFileContext()) {
2512 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2513 } else {
2514 D = CheckOMPRequiresDecl(Loc, ClauseList);
2515 if (D) {
2516 CurContext->addDecl(D);
2517 DSAStack->addRequiresDecl(D);
2518 }
2519 }
2520 return DeclGroupPtrTy::make(DeclGroupRef(D));
2521}
2522
2523OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2524 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002525 /// For target specific clauses, the requires directive cannot be
2526 /// specified after the handling of any of the target regions in the
2527 /// current compilation unit.
2528 ArrayRef<SourceLocation> TargetLocations =
2529 DSAStack->getEncounteredTargetLocs();
2530 if (!TargetLocations.empty()) {
2531 for (const OMPClause *CNew : ClauseList) {
2532 // Check if any of the requires clauses affect target regions.
2533 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2534 isa<OMPUnifiedAddressClause>(CNew) ||
2535 isa<OMPReverseOffloadClause>(CNew) ||
2536 isa<OMPDynamicAllocatorsClause>(CNew)) {
2537 Diag(Loc, diag::err_omp_target_before_requires)
2538 << getOpenMPClauseName(CNew->getClauseKind());
2539 for (SourceLocation TargetLoc : TargetLocations) {
2540 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2541 }
2542 }
2543 }
2544 }
2545
Kelvin Li1408f912018-09-26 04:28:39 +00002546 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2547 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2548 ClauseList);
2549 return nullptr;
2550}
2551
Alexey Bataeve3727102018-04-18 15:57:46 +00002552static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2553 const ValueDecl *D,
2554 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002555 bool IsLoopIterVar = false) {
2556 if (DVar.RefExpr) {
2557 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2558 << getOpenMPClauseName(DVar.CKind);
2559 return;
2560 }
2561 enum {
2562 PDSA_StaticMemberShared,
2563 PDSA_StaticLocalVarShared,
2564 PDSA_LoopIterVarPrivate,
2565 PDSA_LoopIterVarLinear,
2566 PDSA_LoopIterVarLastprivate,
2567 PDSA_ConstVarShared,
2568 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002569 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002570 PDSA_LocalVarPrivate,
2571 PDSA_Implicit
2572 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002573 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002574 auto ReportLoc = D->getLocation();
2575 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002576 if (IsLoopIterVar) {
2577 if (DVar.CKind == OMPC_private)
2578 Reason = PDSA_LoopIterVarPrivate;
2579 else if (DVar.CKind == OMPC_lastprivate)
2580 Reason = PDSA_LoopIterVarLastprivate;
2581 else
2582 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002583 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2584 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002585 Reason = PDSA_TaskVarFirstprivate;
2586 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002587 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002588 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002589 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002590 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002591 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002592 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002593 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002594 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002595 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002596 ReportHint = true;
2597 Reason = PDSA_LocalVarPrivate;
2598 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002599 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002600 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002601 << Reason << ReportHint
2602 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2603 } else if (DVar.ImplicitDSALoc.isValid()) {
2604 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2605 << getOpenMPClauseName(DVar.CKind);
2606 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002607}
2608
Alexey Bataev758e55e2013-09-06 18:03:48 +00002609namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002610class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002611 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002612 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002613 bool ErrorFound = false;
2614 CapturedStmt *CS = nullptr;
2615 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2616 llvm::SmallVector<Expr *, 4> ImplicitMap;
2617 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2618 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002619
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002620 void VisitSubCaptures(OMPExecutableDirective *S) {
2621 // Check implicitly captured variables.
2622 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2623 return;
2624 for (const CapturedStmt::Capture &Cap :
2625 S->getInnermostCapturedStmt()->captures()) {
2626 if (!Cap.capturesVariable())
2627 continue;
2628 VarDecl *VD = Cap.getCapturedVar();
2629 // Do not try to map the variable if it or its sub-component was mapped
2630 // already.
2631 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2632 Stack->checkMappableExprComponentListsForDecl(
2633 VD, /*CurrentRegionOnly=*/true,
2634 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2635 OpenMPClauseKind) { return true; }))
2636 continue;
2637 DeclRefExpr *DRE = buildDeclRefExpr(
2638 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2639 Cap.getLocation(), /*RefersToCapture=*/true);
2640 Visit(DRE);
2641 }
2642 }
2643
Alexey Bataev758e55e2013-09-06 18:03:48 +00002644public:
2645 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002646 if (E->isTypeDependent() || E->isValueDependent() ||
2647 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2648 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002649 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002650 // Check the datasharing rules for the expressions in the clauses.
2651 if (!CS) {
2652 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2653 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2654 Visit(CED->getInit());
2655 return;
2656 }
2657 }
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002658 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002659 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002660 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002661 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002662
Alexey Bataeve3727102018-04-18 15:57:46 +00002663 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002664 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002665 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002666 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002667
Alexey Bataevafe50572017-10-06 17:00:28 +00002668 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002669 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002670 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002671 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002672 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2673 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002674 return;
2675
Alexey Bataeve3727102018-04-18 15:57:46 +00002676 SourceLocation ELoc = E->getExprLoc();
2677 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002678 // The default(none) clause requires that each variable that is referenced
2679 // in the construct, and does not have a predetermined data-sharing
2680 // attribute, must have its data-sharing attribute explicitly determined
2681 // by being listed in a data-sharing attribute clause.
2682 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002683 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002684 VarsWithInheritedDSA.count(VD) == 0) {
2685 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002686 return;
2687 }
2688
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002689 if (isOpenMPTargetExecutionDirective(DKind) &&
2690 !Stack->isLoopControlVariable(VD).first) {
2691 if (!Stack->checkMappableExprComponentListsForDecl(
2692 VD, /*CurrentRegionOnly=*/true,
2693 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2694 StackComponents,
2695 OpenMPClauseKind) {
2696 // Variable is used if it has been marked as an array, array
2697 // section or the variable iself.
2698 return StackComponents.size() == 1 ||
2699 std::all_of(
2700 std::next(StackComponents.rbegin()),
2701 StackComponents.rend(),
2702 [](const OMPClauseMappableExprCommon::
2703 MappableComponent &MC) {
2704 return MC.getAssociatedDeclaration() ==
2705 nullptr &&
2706 (isa<OMPArraySectionExpr>(
2707 MC.getAssociatedExpression()) ||
2708 isa<ArraySubscriptExpr>(
2709 MC.getAssociatedExpression()));
2710 });
2711 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002712 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002713 // By default lambdas are captured as firstprivates.
2714 if (const auto *RD =
2715 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002716 IsFirstprivate = RD->isLambda();
2717 IsFirstprivate =
2718 IsFirstprivate ||
2719 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002720 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002721 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002722 ImplicitFirstprivate.emplace_back(E);
2723 else
2724 ImplicitMap.emplace_back(E);
2725 return;
2726 }
2727 }
2728
Alexey Bataev758e55e2013-09-06 18:03:48 +00002729 // OpenMP [2.9.3.6, Restrictions, p.2]
2730 // A list item that appears in a reduction clause of the innermost
2731 // enclosing worksharing or parallel construct may not be accessed in an
2732 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002733 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002734 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2735 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002736 return isOpenMPParallelDirective(K) ||
2737 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2738 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002739 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002740 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002741 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002742 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002743 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002744 return;
2745 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002746
2747 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002748 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002749 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002750 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002751 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002752 return;
2753 }
2754
2755 // Store implicitly used globals with declare target link for parent
2756 // target.
2757 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2758 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2759 Stack->addToParentTargetRegionLinkGlobals(E);
2760 return;
2761 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002762 }
2763 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002764 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002765 if (E->isTypeDependent() || E->isValueDependent() ||
2766 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2767 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002768 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002769 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002770 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002771 if (!FD)
2772 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002773 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002774 // Check if the variable has explicit DSA set and stop analysis if it
2775 // so.
2776 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2777 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002778
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002779 if (isOpenMPTargetExecutionDirective(DKind) &&
2780 !Stack->isLoopControlVariable(FD).first &&
2781 !Stack->checkMappableExprComponentListsForDecl(
2782 FD, /*CurrentRegionOnly=*/true,
2783 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2784 StackComponents,
2785 OpenMPClauseKind) {
2786 return isa<CXXThisExpr>(
2787 cast<MemberExpr>(
2788 StackComponents.back().getAssociatedExpression())
2789 ->getBase()
2790 ->IgnoreParens());
2791 })) {
2792 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2793 // A bit-field cannot appear in a map clause.
2794 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002795 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002796 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002797
2798 // Check to see if the member expression is referencing a class that
2799 // has already been explicitly mapped
2800 if (Stack->isClassPreviouslyMapped(TE->getType()))
2801 return;
2802
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002803 ImplicitMap.emplace_back(E);
2804 return;
2805 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002806
Alexey Bataeve3727102018-04-18 15:57:46 +00002807 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002808 // OpenMP [2.9.3.6, Restrictions, p.2]
2809 // A list item that appears in a reduction clause of the innermost
2810 // enclosing worksharing or parallel construct may not be accessed in
2811 // an explicit task.
2812 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002813 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2814 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002815 return isOpenMPParallelDirective(K) ||
2816 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2817 },
2818 /*FromParent=*/true);
2819 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2820 ErrorFound = true;
2821 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002822 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002823 return;
2824 }
2825
2826 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002827 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002828 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002829 !Stack->isLoopControlVariable(FD).first) {
2830 // Check if there is a captured expression for the current field in the
2831 // region. Do not mark it as firstprivate unless there is no captured
2832 // expression.
2833 // TODO: try to make it firstprivate.
2834 if (DVar.CKind != OMPC_unknown)
2835 ImplicitFirstprivate.push_back(E);
2836 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002837 return;
2838 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002839 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002840 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002841 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002842 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002843 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002844 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002845 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2846 if (!Stack->checkMappableExprComponentListsForDecl(
2847 VD, /*CurrentRegionOnly=*/true,
2848 [&CurComponents](
2849 OMPClauseMappableExprCommon::MappableExprComponentListRef
2850 StackComponents,
2851 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002852 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002853 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002854 for (const auto &SC : llvm::reverse(StackComponents)) {
2855 // Do both expressions have the same kind?
2856 if (CCI->getAssociatedExpression()->getStmtClass() !=
2857 SC.getAssociatedExpression()->getStmtClass())
2858 if (!(isa<OMPArraySectionExpr>(
2859 SC.getAssociatedExpression()) &&
2860 isa<ArraySubscriptExpr>(
2861 CCI->getAssociatedExpression())))
2862 return false;
2863
Alexey Bataeve3727102018-04-18 15:57:46 +00002864 const Decl *CCD = CCI->getAssociatedDeclaration();
2865 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002866 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2867 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2868 if (SCD != CCD)
2869 return false;
2870 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002871 if (CCI == CCE)
2872 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002873 }
2874 return true;
2875 })) {
2876 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002877 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002878 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002879 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002880 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002881 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002882 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002883 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002884 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002885 // for task|target directives.
2886 // Skip analysis of arguments of implicitly defined map clause for target
2887 // directives.
2888 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2889 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002890 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002891 if (CC)
2892 Visit(CC);
2893 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002894 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002895 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002896 // Check implicitly captured variables.
2897 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002898 }
2899 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002900 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002901 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002902 // Check implicitly captured variables in the task-based directives to
2903 // check if they must be firstprivatized.
2904 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002905 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002906 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002907 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002908
Alexey Bataeve3727102018-04-18 15:57:46 +00002909 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002910 ArrayRef<Expr *> getImplicitFirstprivate() const {
2911 return ImplicitFirstprivate;
2912 }
2913 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002914 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002915 return VarsWithInheritedDSA;
2916 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002917
Alexey Bataev7ff55242014-06-19 09:13:45 +00002918 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002919 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2920 // Process declare target link variables for the target directives.
2921 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2922 for (DeclRefExpr *E : Stack->getLinkGlobals())
2923 Visit(E);
2924 }
2925 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002926};
Alexey Bataeved09d242014-05-28 05:53:51 +00002927} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002928
Alexey Bataevbae9a792014-06-27 10:37:06 +00002929void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002930 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002931 case OMPD_parallel:
2932 case OMPD_parallel_for:
2933 case OMPD_parallel_for_simd:
2934 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002935 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002936 case OMPD_teams_distribute:
2937 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002938 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002939 QualType KmpInt32PtrTy =
2940 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002941 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002942 std::make_pair(".global_tid.", KmpInt32PtrTy),
2943 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2944 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002945 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002946 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2947 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002948 break;
2949 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002950 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002951 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002952 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002953 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002954 case OMPD_target_teams_distribute:
2955 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002956 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2957 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2958 QualType KmpInt32PtrTy =
2959 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2960 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002961 FunctionProtoType::ExtProtoInfo EPI;
2962 EPI.Variadic = true;
2963 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2964 Sema::CapturedParamNameType Params[] = {
2965 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002966 std::make_pair(".part_id.", KmpInt32PtrTy),
2967 std::make_pair(".privates.", VoidPtrTy),
2968 std::make_pair(
2969 ".copy_fn.",
2970 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002971 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2972 std::make_pair(StringRef(), QualType()) // __context with shared vars
2973 };
2974 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2975 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002976 // Mark this captured region as inlined, because we don't use outlined
2977 // function directly.
2978 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2979 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002980 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002981 Sema::CapturedParamNameType ParamsTarget[] = {
2982 std::make_pair(StringRef(), QualType()) // __context with shared vars
2983 };
2984 // Start a captured region for 'target' with no implicit parameters.
2985 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2986 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002987 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002988 std::make_pair(".global_tid.", KmpInt32PtrTy),
2989 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2990 std::make_pair(StringRef(), QualType()) // __context with shared vars
2991 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002992 // Start a captured region for 'teams' or 'parallel'. Both regions have
2993 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002994 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002995 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002996 break;
2997 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002998 case OMPD_target:
2999 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003000 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3001 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3002 QualType KmpInt32PtrTy =
3003 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3004 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003005 FunctionProtoType::ExtProtoInfo EPI;
3006 EPI.Variadic = true;
3007 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3008 Sema::CapturedParamNameType Params[] = {
3009 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003010 std::make_pair(".part_id.", KmpInt32PtrTy),
3011 std::make_pair(".privates.", VoidPtrTy),
3012 std::make_pair(
3013 ".copy_fn.",
3014 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003015 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3016 std::make_pair(StringRef(), QualType()) // __context with shared vars
3017 };
3018 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3019 Params);
3020 // Mark this captured region as inlined, because we don't use outlined
3021 // function directly.
3022 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3023 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003024 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003025 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3026 std::make_pair(StringRef(), QualType()));
3027 break;
3028 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003029 case OMPD_simd:
3030 case OMPD_for:
3031 case OMPD_for_simd:
3032 case OMPD_sections:
3033 case OMPD_section:
3034 case OMPD_single:
3035 case OMPD_master:
3036 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003037 case OMPD_taskgroup:
3038 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003039 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003040 case OMPD_ordered:
3041 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003042 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003043 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003044 std::make_pair(StringRef(), QualType()) // __context with shared vars
3045 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003046 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3047 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003048 break;
3049 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003050 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003051 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3052 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3053 QualType KmpInt32PtrTy =
3054 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3055 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003056 FunctionProtoType::ExtProtoInfo EPI;
3057 EPI.Variadic = true;
3058 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003059 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003060 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003061 std::make_pair(".part_id.", KmpInt32PtrTy),
3062 std::make_pair(".privates.", VoidPtrTy),
3063 std::make_pair(
3064 ".copy_fn.",
3065 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003066 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003067 std::make_pair(StringRef(), QualType()) // __context with shared vars
3068 };
3069 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3070 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003071 // Mark this captured region as inlined, because we don't use outlined
3072 // function directly.
3073 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3074 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003075 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003076 break;
3077 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003078 case OMPD_taskloop:
3079 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003080 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003081 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3082 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003083 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003084 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3085 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003086 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003087 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3088 .withConst();
3089 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3090 QualType KmpInt32PtrTy =
3091 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3092 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003093 FunctionProtoType::ExtProtoInfo EPI;
3094 EPI.Variadic = true;
3095 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003096 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003097 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003098 std::make_pair(".part_id.", KmpInt32PtrTy),
3099 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003100 std::make_pair(
3101 ".copy_fn.",
3102 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3103 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3104 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003105 std::make_pair(".ub.", KmpUInt64Ty),
3106 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003107 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003108 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003109 std::make_pair(StringRef(), QualType()) // __context with shared vars
3110 };
3111 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3112 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003113 // Mark this captured region as inlined, because we don't use outlined
3114 // function directly.
3115 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3116 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003117 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003118 break;
3119 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003120 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003121 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003122 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003123 QualType KmpInt32PtrTy =
3124 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3125 Sema::CapturedParamNameType Params[] = {
3126 std::make_pair(".global_tid.", KmpInt32PtrTy),
3127 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003128 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3129 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003130 std::make_pair(StringRef(), QualType()) // __context with shared vars
3131 };
3132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3133 Params);
3134 break;
3135 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003136 case OMPD_target_teams_distribute_parallel_for:
3137 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003138 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003139 QualType KmpInt32PtrTy =
3140 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003141 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003142
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003143 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003144 FunctionProtoType::ExtProtoInfo EPI;
3145 EPI.Variadic = true;
3146 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3147 Sema::CapturedParamNameType Params[] = {
3148 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003149 std::make_pair(".part_id.", KmpInt32PtrTy),
3150 std::make_pair(".privates.", VoidPtrTy),
3151 std::make_pair(
3152 ".copy_fn.",
3153 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003154 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3155 std::make_pair(StringRef(), QualType()) // __context with shared vars
3156 };
3157 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3158 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003159 // Mark this captured region as inlined, because we don't use outlined
3160 // function directly.
3161 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3162 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003163 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003164 Sema::CapturedParamNameType ParamsTarget[] = {
3165 std::make_pair(StringRef(), QualType()) // __context with shared vars
3166 };
3167 // Start a captured region for 'target' with no implicit parameters.
3168 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3169 ParamsTarget);
3170
3171 Sema::CapturedParamNameType ParamsTeams[] = {
3172 std::make_pair(".global_tid.", KmpInt32PtrTy),
3173 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3174 std::make_pair(StringRef(), QualType()) // __context with shared vars
3175 };
3176 // Start a captured region for 'target' with no implicit parameters.
3177 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3178 ParamsTeams);
3179
3180 Sema::CapturedParamNameType ParamsParallel[] = {
3181 std::make_pair(".global_tid.", KmpInt32PtrTy),
3182 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003183 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3184 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003185 std::make_pair(StringRef(), QualType()) // __context with shared vars
3186 };
3187 // Start a captured region for 'teams' or 'parallel'. Both regions have
3188 // the same implicit parameters.
3189 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3190 ParamsParallel);
3191 break;
3192 }
3193
Alexey Bataev46506272017-12-05 17:41:34 +00003194 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003195 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003196 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003197 QualType KmpInt32PtrTy =
3198 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3199
3200 Sema::CapturedParamNameType ParamsTeams[] = {
3201 std::make_pair(".global_tid.", KmpInt32PtrTy),
3202 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3203 std::make_pair(StringRef(), QualType()) // __context with shared vars
3204 };
3205 // Start a captured region for 'target' with no implicit parameters.
3206 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3207 ParamsTeams);
3208
3209 Sema::CapturedParamNameType ParamsParallel[] = {
3210 std::make_pair(".global_tid.", KmpInt32PtrTy),
3211 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003212 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3213 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003214 std::make_pair(StringRef(), QualType()) // __context with shared vars
3215 };
3216 // Start a captured region for 'teams' or 'parallel'. Both regions have
3217 // the same implicit parameters.
3218 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3219 ParamsParallel);
3220 break;
3221 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003222 case OMPD_target_update:
3223 case OMPD_target_enter_data:
3224 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003225 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3226 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3227 QualType KmpInt32PtrTy =
3228 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3229 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003230 FunctionProtoType::ExtProtoInfo EPI;
3231 EPI.Variadic = true;
3232 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3233 Sema::CapturedParamNameType Params[] = {
3234 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003235 std::make_pair(".part_id.", KmpInt32PtrTy),
3236 std::make_pair(".privates.", VoidPtrTy),
3237 std::make_pair(
3238 ".copy_fn.",
3239 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003240 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3241 std::make_pair(StringRef(), QualType()) // __context with shared vars
3242 };
3243 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3244 Params);
3245 // Mark this captured region as inlined, because we don't use outlined
3246 // function directly.
3247 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3248 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003249 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003250 break;
3251 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003252 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003253 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003254 case OMPD_taskyield:
3255 case OMPD_barrier:
3256 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003257 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003258 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003259 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003260 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003261 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003262 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003263 case OMPD_declare_target:
3264 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003265 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003266 llvm_unreachable("OpenMP Directive is not allowed");
3267 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003268 llvm_unreachable("Unknown OpenMP directive");
3269 }
3270}
3271
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003272int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3273 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3274 getOpenMPCaptureRegions(CaptureRegions, DKind);
3275 return CaptureRegions.size();
3276}
3277
Alexey Bataev3392d762016-02-16 11:18:12 +00003278static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003279 Expr *CaptureExpr, bool WithInit,
3280 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003281 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003282 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003283 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003284 QualType Ty = Init->getType();
3285 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003286 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003287 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003288 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003289 Ty = C.getPointerType(Ty);
3290 ExprResult Res =
3291 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3292 if (!Res.isUsable())
3293 return nullptr;
3294 Init = Res.get();
3295 }
Alexey Bataev61205072016-03-02 04:57:40 +00003296 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003297 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003298 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003299 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003300 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003301 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003302 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003303 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003304 return CED;
3305}
3306
Alexey Bataev61205072016-03-02 04:57:40 +00003307static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3308 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003309 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003310 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003311 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003312 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003313 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3314 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003315 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003316 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003317}
3318
Alexey Bataev5a3af132016-03-29 08:58:54 +00003319static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003320 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003321 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003322 OMPCapturedExprDecl *CD = buildCaptureDecl(
3323 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3324 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003325 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3326 CaptureExpr->getExprLoc());
3327 }
3328 ExprResult Res = Ref;
3329 if (!S.getLangOpts().CPlusPlus &&
3330 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003331 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003332 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003333 if (!Res.isUsable())
3334 return ExprError();
3335 }
3336 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003337}
3338
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003339namespace {
3340// OpenMP directives parsed in this section are represented as a
3341// CapturedStatement with an associated statement. If a syntax error
3342// is detected during the parsing of the associated statement, the
3343// compiler must abort processing and close the CapturedStatement.
3344//
3345// Combined directives such as 'target parallel' have more than one
3346// nested CapturedStatements. This RAII ensures that we unwind out
3347// of all the nested CapturedStatements when an error is found.
3348class CaptureRegionUnwinderRAII {
3349private:
3350 Sema &S;
3351 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003352 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003353
3354public:
3355 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3356 OpenMPDirectiveKind DKind)
3357 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3358 ~CaptureRegionUnwinderRAII() {
3359 if (ErrorFound) {
3360 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3361 while (--ThisCaptureLevel >= 0)
3362 S.ActOnCapturedRegionError();
3363 }
3364 }
3365};
3366} // namespace
3367
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003368StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3369 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003370 bool ErrorFound = false;
3371 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3372 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003373 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003374 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003375 return StmtError();
3376 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003377
Alexey Bataev2ba67042017-11-28 21:11:44 +00003378 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3379 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003380 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003381 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003382 SmallVector<const OMPLinearClause *, 4> LCs;
3383 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003384 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003385 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003386 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3387 Clause->getClauseKind() == OMPC_in_reduction) {
3388 // Capture taskgroup task_reduction descriptors inside the tasking regions
3389 // with the corresponding in_reduction items.
3390 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003391 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003392 if (E)
3393 MarkDeclarationsReferencedInExpr(E);
3394 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003395 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003396 Clause->getClauseKind() == OMPC_copyprivate ||
3397 (getLangOpts().OpenMPUseTLS &&
3398 getASTContext().getTargetInfo().isTLSSupported() &&
3399 Clause->getClauseKind() == OMPC_copyin)) {
3400 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003401 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003402 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003403 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003404 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003405 }
3406 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003407 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003408 } else if (CaptureRegions.size() > 1 ||
3409 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003410 if (auto *C = OMPClauseWithPreInit::get(Clause))
3411 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003412 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003413 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003414 MarkDeclarationsReferencedInExpr(E);
3415 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003416 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003417 if (Clause->getClauseKind() == OMPC_schedule)
3418 SC = cast<OMPScheduleClause>(Clause);
3419 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003420 OC = cast<OMPOrderedClause>(Clause);
3421 else if (Clause->getClauseKind() == OMPC_linear)
3422 LCs.push_back(cast<OMPLinearClause>(Clause));
3423 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003424 // OpenMP, 2.7.1 Loop Construct, Restrictions
3425 // The nonmonotonic modifier cannot be specified if an ordered clause is
3426 // specified.
3427 if (SC &&
3428 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3429 SC->getSecondScheduleModifier() ==
3430 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3431 OC) {
3432 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3433 ? SC->getFirstScheduleModifierLoc()
3434 : SC->getSecondScheduleModifierLoc(),
3435 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003436 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003437 ErrorFound = true;
3438 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003439 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003440 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003441 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003442 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003443 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003444 ErrorFound = true;
3445 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003446 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3447 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3448 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003449 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003450 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3451 ErrorFound = true;
3452 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003453 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003454 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003455 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003456 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003457 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003458 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003459 // Mark all variables in private list clauses as used in inner region.
3460 // Required for proper codegen of combined directives.
3461 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003462 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003463 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003464 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3465 // Find the particular capture region for the clause if the
3466 // directive is a combined one with multiple capture regions.
3467 // If the directive is not a combined one, the capture region
3468 // associated with the clause is OMPD_unknown and is generated
3469 // only once.
3470 if (CaptureRegion == ThisCaptureRegion ||
3471 CaptureRegion == OMPD_unknown) {
3472 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003473 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003474 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3475 }
3476 }
3477 }
3478 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003479 if (++CompletedRegions == CaptureRegions.size())
3480 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003481 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003482 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003483 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003484}
3485
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003486static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3487 OpenMPDirectiveKind CancelRegion,
3488 SourceLocation StartLoc) {
3489 // CancelRegion is only needed for cancel and cancellation_point.
3490 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3491 return false;
3492
3493 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3494 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3495 return false;
3496
3497 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3498 << getOpenMPDirectiveName(CancelRegion);
3499 return true;
3500}
3501
Alexey Bataeve3727102018-04-18 15:57:46 +00003502static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003503 OpenMPDirectiveKind CurrentRegion,
3504 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003505 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003506 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003507 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003508 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3509 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003510 bool NestingProhibited = false;
3511 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003512 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003513 enum {
3514 NoRecommend,
3515 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003516 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003517 ShouldBeInTargetRegion,
3518 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003519 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003520 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003521 // OpenMP [2.16, Nesting of Regions]
3522 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003523 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003524 // An ordered construct with the simd clause is the only OpenMP
3525 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003526 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003527 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3528 // message.
3529 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3530 ? diag::err_omp_prohibited_region_simd
3531 : diag::warn_omp_nesting_simd);
3532 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003533 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003534 if (ParentRegion == OMPD_atomic) {
3535 // OpenMP [2.16, Nesting of Regions]
3536 // OpenMP constructs may not be nested inside an atomic region.
3537 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3538 return true;
3539 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003540 if (CurrentRegion == OMPD_section) {
3541 // OpenMP [2.7.2, sections Construct, Restrictions]
3542 // Orphaned section directives are prohibited. That is, the section
3543 // directives must appear within the sections construct and must not be
3544 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003545 if (ParentRegion != OMPD_sections &&
3546 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003547 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3548 << (ParentRegion != OMPD_unknown)
3549 << getOpenMPDirectiveName(ParentRegion);
3550 return true;
3551 }
3552 return false;
3553 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003554 // Allow some constructs (except teams and cancellation constructs) to be
3555 // orphaned (they could be used in functions, called from OpenMP regions
3556 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003557 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003558 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3559 CurrentRegion != OMPD_cancellation_point &&
3560 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003561 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003562 if (CurrentRegion == OMPD_cancellation_point ||
3563 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003564 // OpenMP [2.16, Nesting of Regions]
3565 // A cancellation point construct for which construct-type-clause is
3566 // taskgroup must be nested inside a task construct. A cancellation
3567 // point construct for which construct-type-clause is not taskgroup must
3568 // be closely nested inside an OpenMP construct that matches the type
3569 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003570 // A cancel construct for which construct-type-clause is taskgroup must be
3571 // nested inside a task construct. A cancel construct for which
3572 // construct-type-clause is not taskgroup must be closely nested inside an
3573 // OpenMP construct that matches the type specified in
3574 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003575 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003576 !((CancelRegion == OMPD_parallel &&
3577 (ParentRegion == OMPD_parallel ||
3578 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003579 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003580 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003581 ParentRegion == OMPD_target_parallel_for ||
3582 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003583 ParentRegion == OMPD_teams_distribute_parallel_for ||
3584 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003585 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3586 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003587 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3588 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003589 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003590 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003591 // OpenMP [2.16, Nesting of Regions]
3592 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003593 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003594 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003595 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003596 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3597 // OpenMP [2.16, Nesting of Regions]
3598 // A critical region may not be nested (closely or otherwise) inside a
3599 // critical region with the same name. Note that this restriction is not
3600 // sufficient to prevent deadlock.
3601 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003602 bool DeadLock = Stack->hasDirective(
3603 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3604 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003605 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003606 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3607 PreviousCriticalLoc = Loc;
3608 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003609 }
3610 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003611 },
3612 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003613 if (DeadLock) {
3614 SemaRef.Diag(StartLoc,
3615 diag::err_omp_prohibited_region_critical_same_name)
3616 << CurrentName.getName();
3617 if (PreviousCriticalLoc.isValid())
3618 SemaRef.Diag(PreviousCriticalLoc,
3619 diag::note_omp_previous_critical_region);
3620 return true;
3621 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003622 } else if (CurrentRegion == OMPD_barrier) {
3623 // OpenMP [2.16, Nesting of Regions]
3624 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003625 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003626 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3627 isOpenMPTaskingDirective(ParentRegion) ||
3628 ParentRegion == OMPD_master ||
3629 ParentRegion == OMPD_critical ||
3630 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003631 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003632 !isOpenMPParallelDirective(CurrentRegion) &&
3633 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003634 // OpenMP [2.16, Nesting of Regions]
3635 // A worksharing region may not be closely nested inside a worksharing,
3636 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003637 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3638 isOpenMPTaskingDirective(ParentRegion) ||
3639 ParentRegion == OMPD_master ||
3640 ParentRegion == OMPD_critical ||
3641 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003642 Recommend = ShouldBeInParallelRegion;
3643 } else if (CurrentRegion == OMPD_ordered) {
3644 // OpenMP [2.16, Nesting of Regions]
3645 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003646 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003647 // An ordered region must be closely nested inside a loop region (or
3648 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003649 // OpenMP [2.8.1,simd Construct, Restrictions]
3650 // An ordered construct with the simd clause is the only OpenMP construct
3651 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003652 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003653 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003654 !(isOpenMPSimdDirective(ParentRegion) ||
3655 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003656 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003657 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003658 // OpenMP [2.16, Nesting of Regions]
3659 // If specified, a teams construct must be contained within a target
3660 // construct.
3661 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003662 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003663 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003664 }
Kelvin Libf594a52016-12-17 05:48:59 +00003665 if (!NestingProhibited &&
3666 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3667 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3668 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003669 // OpenMP [2.16, Nesting of Regions]
3670 // distribute, parallel, parallel sections, parallel workshare, and the
3671 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3672 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003673 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3674 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003675 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003676 }
David Majnemer9d168222016-08-05 17:44:54 +00003677 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003678 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003679 // OpenMP 4.5 [2.17 Nesting of Regions]
3680 // The region associated with the distribute construct must be strictly
3681 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003682 NestingProhibited =
3683 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003684 Recommend = ShouldBeInTeamsRegion;
3685 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003686 if (!NestingProhibited &&
3687 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3688 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3689 // OpenMP 4.5 [2.17 Nesting of Regions]
3690 // If a target, target update, target data, target enter data, or
3691 // target exit data construct is encountered during execution of a
3692 // target region, the behavior is unspecified.
3693 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003694 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003695 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003696 if (isOpenMPTargetExecutionDirective(K)) {
3697 OffendingRegion = K;
3698 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003699 }
3700 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003701 },
3702 false /* don't skip top directive */);
3703 CloseNesting = false;
3704 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003705 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003706 if (OrphanSeen) {
3707 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3708 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3709 } else {
3710 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3711 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3712 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3713 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003714 return true;
3715 }
3716 }
3717 return false;
3718}
3719
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003720static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3721 ArrayRef<OMPClause *> Clauses,
3722 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3723 bool ErrorFound = false;
3724 unsigned NamedModifiersNumber = 0;
3725 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3726 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003727 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003728 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003729 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3730 // At most one if clause without a directive-name-modifier can appear on
3731 // the directive.
3732 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3733 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003734 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003735 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3736 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3737 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003738 } else if (CurNM != OMPD_unknown) {
3739 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003740 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003741 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003742 FoundNameModifiers[CurNM] = IC;
3743 if (CurNM == OMPD_unknown)
3744 continue;
3745 // Check if the specified name modifier is allowed for the current
3746 // directive.
3747 // At most one if clause with the particular directive-name-modifier can
3748 // appear on the directive.
3749 bool MatchFound = false;
3750 for (auto NM : AllowedNameModifiers) {
3751 if (CurNM == NM) {
3752 MatchFound = true;
3753 break;
3754 }
3755 }
3756 if (!MatchFound) {
3757 S.Diag(IC->getNameModifierLoc(),
3758 diag::err_omp_wrong_if_directive_name_modifier)
3759 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3760 ErrorFound = true;
3761 }
3762 }
3763 }
3764 // If any if clause on the directive includes a directive-name-modifier then
3765 // all if clauses on the directive must include a directive-name-modifier.
3766 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3767 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003768 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003769 diag::err_omp_no_more_if_clause);
3770 } else {
3771 std::string Values;
3772 std::string Sep(", ");
3773 unsigned AllowedCnt = 0;
3774 unsigned TotalAllowedNum =
3775 AllowedNameModifiers.size() - NamedModifiersNumber;
3776 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3777 ++Cnt) {
3778 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3779 if (!FoundNameModifiers[NM]) {
3780 Values += "'";
3781 Values += getOpenMPDirectiveName(NM);
3782 Values += "'";
3783 if (AllowedCnt + 2 == TotalAllowedNum)
3784 Values += " or ";
3785 else if (AllowedCnt + 1 != TotalAllowedNum)
3786 Values += Sep;
3787 ++AllowedCnt;
3788 }
3789 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003790 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003791 diag::err_omp_unnamed_if_clause)
3792 << (TotalAllowedNum > 1) << Values;
3793 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003794 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003795 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3796 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003797 ErrorFound = true;
3798 }
3799 return ErrorFound;
3800}
3801
Alexey Bataeve106f252019-04-01 14:25:31 +00003802static std::pair<ValueDecl *, bool>
3803getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
3804 SourceRange &ERange, bool AllowArraySection = false) {
3805 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3806 RefExpr->containsUnexpandedParameterPack())
3807 return std::make_pair(nullptr, true);
3808
3809 // OpenMP [3.1, C/C++]
3810 // A list item is a variable name.
3811 // OpenMP [2.9.3.3, Restrictions, p.1]
3812 // A variable that is part of another variable (as an array or
3813 // structure element) cannot appear in a private clause.
3814 RefExpr = RefExpr->IgnoreParens();
3815 enum {
3816 NoArrayExpr = -1,
3817 ArraySubscript = 0,
3818 OMPArraySection = 1
3819 } IsArrayExpr = NoArrayExpr;
3820 if (AllowArraySection) {
3821 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
3822 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
3823 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3824 Base = TempASE->getBase()->IgnoreParenImpCasts();
3825 RefExpr = Base;
3826 IsArrayExpr = ArraySubscript;
3827 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
3828 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
3829 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
3830 Base = TempOASE->getBase()->IgnoreParenImpCasts();
3831 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3832 Base = TempASE->getBase()->IgnoreParenImpCasts();
3833 RefExpr = Base;
3834 IsArrayExpr = OMPArraySection;
3835 }
3836 }
3837 ELoc = RefExpr->getExprLoc();
3838 ERange = RefExpr->getSourceRange();
3839 RefExpr = RefExpr->IgnoreParenImpCasts();
3840 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3841 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
3842 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
3843 (S.getCurrentThisType().isNull() || !ME ||
3844 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
3845 !isa<FieldDecl>(ME->getMemberDecl()))) {
3846 if (IsArrayExpr != NoArrayExpr) {
3847 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
3848 << ERange;
3849 } else {
3850 S.Diag(ELoc,
3851 AllowArraySection
3852 ? diag::err_omp_expected_var_name_member_expr_or_array_item
3853 : diag::err_omp_expected_var_name_member_expr)
3854 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
3855 }
3856 return std::make_pair(nullptr, false);
3857 }
3858 return std::make_pair(
3859 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
3860}
3861
3862static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00003863 ArrayRef<OMPClause *> Clauses) {
3864 assert(!S.CurContext->isDependentContext() &&
3865 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00003866 auto AllocateRange =
3867 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00003868 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
3869 DeclToCopy;
3870 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
3871 return isOpenMPPrivate(C->getClauseKind());
3872 });
3873 for (OMPClause *Cl : PrivateRange) {
3874 MutableArrayRef<Expr *>::iterator I, It, Et;
3875 if (Cl->getClauseKind() == OMPC_private) {
3876 auto *PC = cast<OMPPrivateClause>(Cl);
3877 I = PC->private_copies().begin();
3878 It = PC->varlist_begin();
3879 Et = PC->varlist_end();
3880 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
3881 auto *PC = cast<OMPFirstprivateClause>(Cl);
3882 I = PC->private_copies().begin();
3883 It = PC->varlist_begin();
3884 Et = PC->varlist_end();
3885 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
3886 auto *PC = cast<OMPLastprivateClause>(Cl);
3887 I = PC->private_copies().begin();
3888 It = PC->varlist_begin();
3889 Et = PC->varlist_end();
3890 } else if (Cl->getClauseKind() == OMPC_linear) {
3891 auto *PC = cast<OMPLinearClause>(Cl);
3892 I = PC->privates().begin();
3893 It = PC->varlist_begin();
3894 Et = PC->varlist_end();
3895 } else if (Cl->getClauseKind() == OMPC_reduction) {
3896 auto *PC = cast<OMPReductionClause>(Cl);
3897 I = PC->privates().begin();
3898 It = PC->varlist_begin();
3899 Et = PC->varlist_end();
3900 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
3901 auto *PC = cast<OMPTaskReductionClause>(Cl);
3902 I = PC->privates().begin();
3903 It = PC->varlist_begin();
3904 Et = PC->varlist_end();
3905 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
3906 auto *PC = cast<OMPInReductionClause>(Cl);
3907 I = PC->privates().begin();
3908 It = PC->varlist_begin();
3909 Et = PC->varlist_end();
3910 } else {
3911 llvm_unreachable("Expected private clause.");
3912 }
3913 for (Expr *E : llvm::make_range(It, Et)) {
3914 if (!*I) {
3915 ++I;
3916 continue;
3917 }
3918 SourceLocation ELoc;
3919 SourceRange ERange;
3920 Expr *SimpleRefExpr = E;
3921 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3922 /*AllowArraySection=*/true);
3923 DeclToCopy.try_emplace(Res.first,
3924 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
3925 ++I;
3926 }
3927 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003928 for (OMPClause *C : AllocateRange) {
3929 auto *AC = cast<OMPAllocateClause>(C);
3930 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3931 getAllocatorKind(S, Stack, AC->getAllocator());
3932 // OpenMP, 2.11.4 allocate Clause, Restrictions.
3933 // For task, taskloop or target directives, allocation requests to memory
3934 // allocators with the trait access set to thread result in unspecified
3935 // behavior.
3936 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
3937 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
3938 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
3939 S.Diag(AC->getAllocator()->getExprLoc(),
3940 diag::warn_omp_allocate_thread_on_task_target_directive)
3941 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00003942 }
3943 for (Expr *E : AC->varlists()) {
3944 SourceLocation ELoc;
3945 SourceRange ERange;
3946 Expr *SimpleRefExpr = E;
3947 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
3948 ValueDecl *VD = Res.first;
3949 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
3950 if (!isOpenMPPrivate(Data.CKind)) {
3951 S.Diag(E->getExprLoc(),
3952 diag::err_omp_expected_private_copy_for_allocate);
3953 continue;
3954 }
3955 VarDecl *PrivateVD = DeclToCopy[VD];
3956 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
3957 AllocatorKind, AC->getAllocator()))
3958 continue;
3959 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
3960 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00003961 }
3962 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003963}
3964
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003965StmtResult Sema::ActOnOpenMPExecutableDirective(
3966 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3967 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3968 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003969 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003970 // First check CancelRegion which is then used in checkNestingOfRegions.
3971 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3972 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003973 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003974 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003975
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003976 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003977 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003978 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003979 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003980 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003981 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3982
3983 // Check default data sharing attributes for referenced variables.
3984 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003985 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3986 Stmt *S = AStmt;
3987 while (--ThisCaptureLevel >= 0)
3988 S = cast<CapturedStmt>(S)->getCapturedStmt();
3989 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003990 if (DSAChecker.isErrorFound())
3991 return StmtError();
3992 // Generate list of implicitly defined firstprivate variables.
3993 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003994
Alexey Bataev88202be2017-07-27 13:20:36 +00003995 SmallVector<Expr *, 4> ImplicitFirstprivates(
3996 DSAChecker.getImplicitFirstprivate().begin(),
3997 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003998 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3999 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004000 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004001 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004002 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004003 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004004 if (E)
4005 ImplicitFirstprivates.emplace_back(E);
4006 }
4007 }
4008 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004009 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004010 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4011 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004012 ClausesWithImplicit.push_back(Implicit);
4013 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004014 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004015 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004016 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004017 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004018 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004019 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004020 CXXScopeSpec MapperIdScopeSpec;
4021 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004022 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004023 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4024 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4025 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004026 ClausesWithImplicit.emplace_back(Implicit);
4027 ErrorFound |=
4028 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004029 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004030 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004031 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004032 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004033 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004034
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004035 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004036 switch (Kind) {
4037 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004038 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4039 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004040 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004041 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004042 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004043 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4044 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004045 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004046 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004047 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4048 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004049 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004050 case OMPD_for_simd:
4051 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4052 EndLoc, VarsWithInheritedDSA);
4053 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004054 case OMPD_sections:
4055 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4056 EndLoc);
4057 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004058 case OMPD_section:
4059 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004060 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004061 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4062 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004063 case OMPD_single:
4064 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4065 EndLoc);
4066 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004067 case OMPD_master:
4068 assert(ClausesWithImplicit.empty() &&
4069 "No clauses are allowed for 'omp master' directive");
4070 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4071 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004072 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004073 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4074 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004075 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004076 case OMPD_parallel_for:
4077 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4078 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004079 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004080 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004081 case OMPD_parallel_for_simd:
4082 Res = ActOnOpenMPParallelForSimdDirective(
4083 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004084 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004085 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004086 case OMPD_parallel_sections:
4087 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4088 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004089 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004090 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004091 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004092 Res =
4093 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004094 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004095 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004096 case OMPD_taskyield:
4097 assert(ClausesWithImplicit.empty() &&
4098 "No clauses are allowed for 'omp taskyield' directive");
4099 assert(AStmt == nullptr &&
4100 "No associated statement allowed for 'omp taskyield' directive");
4101 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4102 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004103 case OMPD_barrier:
4104 assert(ClausesWithImplicit.empty() &&
4105 "No clauses are allowed for 'omp barrier' directive");
4106 assert(AStmt == nullptr &&
4107 "No associated statement allowed for 'omp barrier' directive");
4108 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4109 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004110 case OMPD_taskwait:
4111 assert(ClausesWithImplicit.empty() &&
4112 "No clauses are allowed for 'omp taskwait' directive");
4113 assert(AStmt == nullptr &&
4114 "No associated statement allowed for 'omp taskwait' directive");
4115 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4116 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004117 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004118 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4119 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004120 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004121 case OMPD_flush:
4122 assert(AStmt == nullptr &&
4123 "No associated statement allowed for 'omp flush' directive");
4124 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4125 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004126 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004127 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4128 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004129 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004130 case OMPD_atomic:
4131 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4132 EndLoc);
4133 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004134 case OMPD_teams:
4135 Res =
4136 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4137 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004138 case OMPD_target:
4139 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4140 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004141 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004142 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004143 case OMPD_target_parallel:
4144 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4145 StartLoc, EndLoc);
4146 AllowedNameModifiers.push_back(OMPD_target);
4147 AllowedNameModifiers.push_back(OMPD_parallel);
4148 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004149 case OMPD_target_parallel_for:
4150 Res = ActOnOpenMPTargetParallelForDirective(
4151 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4152 AllowedNameModifiers.push_back(OMPD_target);
4153 AllowedNameModifiers.push_back(OMPD_parallel);
4154 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004155 case OMPD_cancellation_point:
4156 assert(ClausesWithImplicit.empty() &&
4157 "No clauses are allowed for 'omp cancellation point' directive");
4158 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4159 "cancellation point' directive");
4160 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4161 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004162 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004163 assert(AStmt == nullptr &&
4164 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004165 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4166 CancelRegion);
4167 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004168 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004169 case OMPD_target_data:
4170 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4171 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004172 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004173 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004174 case OMPD_target_enter_data:
4175 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004176 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004177 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4178 break;
Samuel Antao72590762016-01-19 20:04:50 +00004179 case OMPD_target_exit_data:
4180 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004181 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004182 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4183 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004184 case OMPD_taskloop:
4185 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4186 EndLoc, VarsWithInheritedDSA);
4187 AllowedNameModifiers.push_back(OMPD_taskloop);
4188 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004189 case OMPD_taskloop_simd:
4190 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4191 EndLoc, VarsWithInheritedDSA);
4192 AllowedNameModifiers.push_back(OMPD_taskloop);
4193 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004194 case OMPD_distribute:
4195 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4196 EndLoc, VarsWithInheritedDSA);
4197 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004198 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004199 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4200 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004201 AllowedNameModifiers.push_back(OMPD_target_update);
4202 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004203 case OMPD_distribute_parallel_for:
4204 Res = ActOnOpenMPDistributeParallelForDirective(
4205 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4206 AllowedNameModifiers.push_back(OMPD_parallel);
4207 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004208 case OMPD_distribute_parallel_for_simd:
4209 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4210 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4211 AllowedNameModifiers.push_back(OMPD_parallel);
4212 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004213 case OMPD_distribute_simd:
4214 Res = ActOnOpenMPDistributeSimdDirective(
4215 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4216 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004217 case OMPD_target_parallel_for_simd:
4218 Res = ActOnOpenMPTargetParallelForSimdDirective(
4219 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4220 AllowedNameModifiers.push_back(OMPD_target);
4221 AllowedNameModifiers.push_back(OMPD_parallel);
4222 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004223 case OMPD_target_simd:
4224 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4225 EndLoc, VarsWithInheritedDSA);
4226 AllowedNameModifiers.push_back(OMPD_target);
4227 break;
Kelvin Li02532872016-08-05 14:37:37 +00004228 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004229 Res = ActOnOpenMPTeamsDistributeDirective(
4230 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004231 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004232 case OMPD_teams_distribute_simd:
4233 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4234 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4235 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004236 case OMPD_teams_distribute_parallel_for_simd:
4237 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4238 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4239 AllowedNameModifiers.push_back(OMPD_parallel);
4240 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004241 case OMPD_teams_distribute_parallel_for:
4242 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4243 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4244 AllowedNameModifiers.push_back(OMPD_parallel);
4245 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004246 case OMPD_target_teams:
4247 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4248 EndLoc);
4249 AllowedNameModifiers.push_back(OMPD_target);
4250 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004251 case OMPD_target_teams_distribute:
4252 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4253 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4254 AllowedNameModifiers.push_back(OMPD_target);
4255 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004256 case OMPD_target_teams_distribute_parallel_for:
4257 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4258 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4259 AllowedNameModifiers.push_back(OMPD_target);
4260 AllowedNameModifiers.push_back(OMPD_parallel);
4261 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004262 case OMPD_target_teams_distribute_parallel_for_simd:
4263 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4264 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4265 AllowedNameModifiers.push_back(OMPD_target);
4266 AllowedNameModifiers.push_back(OMPD_parallel);
4267 break;
Kelvin Lida681182017-01-10 18:08:18 +00004268 case OMPD_target_teams_distribute_simd:
4269 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4270 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4271 AllowedNameModifiers.push_back(OMPD_target);
4272 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004273 case OMPD_declare_target:
4274 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004275 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004276 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004277 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004278 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004279 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004280 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004281 llvm_unreachable("OpenMP Directive is not allowed");
4282 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004283 llvm_unreachable("Unknown OpenMP directive");
4284 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004285
Roman Lebedevb5700602019-03-20 16:32:36 +00004286 ErrorFound = Res.isInvalid() || ErrorFound;
4287
Alexey Bataev412254a2019-05-09 18:44:53 +00004288 // Check variables in the clauses if default(none) was specified.
4289 if (DSAStack->getDefaultDSA() == DSA_none) {
4290 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4291 for (OMPClause *C : Clauses) {
4292 switch (C->getClauseKind()) {
4293 case OMPC_num_threads:
4294 case OMPC_dist_schedule:
4295 // Do not analyse if no parent teams directive.
4296 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4297 break;
4298 continue;
4299 case OMPC_if:
4300 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4301 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4302 break;
4303 continue;
4304 case OMPC_schedule:
4305 break;
4306 case OMPC_ordered:
4307 case OMPC_device:
4308 case OMPC_num_teams:
4309 case OMPC_thread_limit:
4310 case OMPC_priority:
4311 case OMPC_grainsize:
4312 case OMPC_num_tasks:
4313 case OMPC_hint:
4314 case OMPC_collapse:
4315 case OMPC_safelen:
4316 case OMPC_simdlen:
4317 case OMPC_final:
4318 case OMPC_default:
4319 case OMPC_proc_bind:
4320 case OMPC_private:
4321 case OMPC_firstprivate:
4322 case OMPC_lastprivate:
4323 case OMPC_shared:
4324 case OMPC_reduction:
4325 case OMPC_task_reduction:
4326 case OMPC_in_reduction:
4327 case OMPC_linear:
4328 case OMPC_aligned:
4329 case OMPC_copyin:
4330 case OMPC_copyprivate:
4331 case OMPC_nowait:
4332 case OMPC_untied:
4333 case OMPC_mergeable:
4334 case OMPC_allocate:
4335 case OMPC_read:
4336 case OMPC_write:
4337 case OMPC_update:
4338 case OMPC_capture:
4339 case OMPC_seq_cst:
4340 case OMPC_depend:
4341 case OMPC_threads:
4342 case OMPC_simd:
4343 case OMPC_map:
4344 case OMPC_nogroup:
4345 case OMPC_defaultmap:
4346 case OMPC_to:
4347 case OMPC_from:
4348 case OMPC_use_device_ptr:
4349 case OMPC_is_device_ptr:
4350 continue;
4351 case OMPC_allocator:
4352 case OMPC_flush:
4353 case OMPC_threadprivate:
4354 case OMPC_uniform:
4355 case OMPC_unknown:
4356 case OMPC_unified_address:
4357 case OMPC_unified_shared_memory:
4358 case OMPC_reverse_offload:
4359 case OMPC_dynamic_allocators:
4360 case OMPC_atomic_default_mem_order:
4361 llvm_unreachable("Unexpected clause");
4362 }
4363 for (Stmt *CC : C->children()) {
4364 if (CC)
4365 DSAChecker.Visit(CC);
4366 }
4367 }
4368 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4369 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4370 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004371 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00004372 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4373 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004374 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004375 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004376 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
4377
4378 if (!AllowedNameModifiers.empty())
4379 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4380 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004381
Alexey Bataeved09d242014-05-28 05:53:51 +00004382 if (ErrorFound)
4383 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004384
4385 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4386 Res.getAs<OMPExecutableDirective>()
4387 ->getStructuredBlock()
4388 ->setIsOMPStructuredBlock(true);
4389 }
4390
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004391 if (!CurContext->isDependentContext() &&
4392 isOpenMPTargetExecutionDirective(Kind) &&
4393 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4394 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4395 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4396 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4397 // Register target to DSA Stack.
4398 DSAStack->addTargetDirLocation(StartLoc);
4399 }
4400
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004401 return Res;
4402}
4403
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004404Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4405 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004406 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004407 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4408 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004409 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004410 assert(Linears.size() == LinModifiers.size());
4411 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004412 if (!DG || DG.get().isNull())
4413 return DeclGroupPtrTy();
4414
4415 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00004416 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004417 return DG;
4418 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004419 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004420 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4421 ADecl = FTD->getTemplatedDecl();
4422
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004423 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4424 if (!FD) {
4425 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004426 return DeclGroupPtrTy();
4427 }
4428
Alexey Bataev2af33e32016-04-07 12:45:37 +00004429 // OpenMP [2.8.2, declare simd construct, Description]
4430 // The parameter of the simdlen clause must be a constant positive integer
4431 // expression.
4432 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004433 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004434 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004435 // OpenMP [2.8.2, declare simd construct, Description]
4436 // The special this pointer can be used as if was one of the arguments to the
4437 // function in any of the linear, aligned, or uniform clauses.
4438 // The uniform clause declares one or more arguments to have an invariant
4439 // value for all concurrent invocations of the function in the execution of a
4440 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004441 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4442 const Expr *UniformedLinearThis = nullptr;
4443 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004444 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004445 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4446 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004447 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4448 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004449 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004450 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004451 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004452 }
4453 if (isa<CXXThisExpr>(E)) {
4454 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004455 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004456 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004457 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4458 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004459 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004460 // OpenMP [2.8.2, declare simd construct, Description]
4461 // The aligned clause declares that the object to which each list item points
4462 // is aligned to the number of bytes expressed in the optional parameter of
4463 // the aligned clause.
4464 // The special this pointer can be used as if was one of the arguments to the
4465 // function in any of the linear, aligned, or uniform clauses.
4466 // The type of list items appearing in the aligned clause must be array,
4467 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004468 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4469 const Expr *AlignedThis = nullptr;
4470 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004471 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004472 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4473 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4474 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004475 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4476 FD->getParamDecl(PVD->getFunctionScopeIndex())
4477 ->getCanonicalDecl() == CanonPVD) {
4478 // OpenMP [2.8.1, simd construct, Restrictions]
4479 // A list-item cannot appear in more than one aligned clause.
4480 if (AlignedArgs.count(CanonPVD) > 0) {
4481 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4482 << 1 << E->getSourceRange();
4483 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4484 diag::note_omp_explicit_dsa)
4485 << getOpenMPClauseName(OMPC_aligned);
4486 continue;
4487 }
4488 AlignedArgs[CanonPVD] = E;
4489 QualType QTy = PVD->getType()
4490 .getNonReferenceType()
4491 .getUnqualifiedType()
4492 .getCanonicalType();
4493 const Type *Ty = QTy.getTypePtrOrNull();
4494 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4495 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4496 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4497 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4498 }
4499 continue;
4500 }
4501 }
4502 if (isa<CXXThisExpr>(E)) {
4503 if (AlignedThis) {
4504 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4505 << 2 << E->getSourceRange();
4506 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4507 << getOpenMPClauseName(OMPC_aligned);
4508 }
4509 AlignedThis = E;
4510 continue;
4511 }
4512 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4513 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4514 }
4515 // The optional parameter of the aligned clause, alignment, must be a constant
4516 // positive integer expression. If no optional parameter is specified,
4517 // implementation-defined default alignments for SIMD instructions on the
4518 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 SmallVector<const Expr *, 4> NewAligns;
4520 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004521 ExprResult Align;
4522 if (E)
4523 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4524 NewAligns.push_back(Align.get());
4525 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004526 // OpenMP [2.8.2, declare simd construct, Description]
4527 // The linear clause declares one or more list items to be private to a SIMD
4528 // lane and to have a linear relationship with respect to the iteration space
4529 // of a loop.
4530 // The special this pointer can be used as if was one of the arguments to the
4531 // function in any of the linear, aligned, or uniform clauses.
4532 // When a linear-step expression is specified in a linear clause it must be
4533 // either a constant integer expression or an integer-typed parameter that is
4534 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004535 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004536 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4537 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004538 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004539 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4540 ++MI;
4541 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004542 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4543 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4544 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004545 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4546 FD->getParamDecl(PVD->getFunctionScopeIndex())
4547 ->getCanonicalDecl() == CanonPVD) {
4548 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4549 // A list-item cannot appear in more than one linear clause.
4550 if (LinearArgs.count(CanonPVD) > 0) {
4551 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4552 << getOpenMPClauseName(OMPC_linear)
4553 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4554 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4555 diag::note_omp_explicit_dsa)
4556 << getOpenMPClauseName(OMPC_linear);
4557 continue;
4558 }
4559 // Each argument can appear in at most one uniform or linear clause.
4560 if (UniformedArgs.count(CanonPVD) > 0) {
4561 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4562 << getOpenMPClauseName(OMPC_linear)
4563 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4564 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4565 diag::note_omp_explicit_dsa)
4566 << getOpenMPClauseName(OMPC_uniform);
4567 continue;
4568 }
4569 LinearArgs[CanonPVD] = E;
4570 if (E->isValueDependent() || E->isTypeDependent() ||
4571 E->isInstantiationDependent() ||
4572 E->containsUnexpandedParameterPack())
4573 continue;
4574 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4575 PVD->getOriginalType());
4576 continue;
4577 }
4578 }
4579 if (isa<CXXThisExpr>(E)) {
4580 if (UniformedLinearThis) {
4581 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4582 << getOpenMPClauseName(OMPC_linear)
4583 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4584 << E->getSourceRange();
4585 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4586 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4587 : OMPC_linear);
4588 continue;
4589 }
4590 UniformedLinearThis = E;
4591 if (E->isValueDependent() || E->isTypeDependent() ||
4592 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4593 continue;
4594 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4595 E->getType());
4596 continue;
4597 }
4598 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4599 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4600 }
4601 Expr *Step = nullptr;
4602 Expr *NewStep = nullptr;
4603 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004604 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004605 // Skip the same step expression, it was checked already.
4606 if (Step == E || !E) {
4607 NewSteps.push_back(E ? NewStep : nullptr);
4608 continue;
4609 }
4610 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004611 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4612 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4613 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004614 if (UniformedArgs.count(CanonPVD) == 0) {
4615 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4616 << Step->getSourceRange();
4617 } else if (E->isValueDependent() || E->isTypeDependent() ||
4618 E->isInstantiationDependent() ||
4619 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004620 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004621 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004622 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004623 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4624 << Step->getSourceRange();
4625 }
4626 continue;
4627 }
4628 NewStep = Step;
4629 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4630 !Step->isInstantiationDependent() &&
4631 !Step->containsUnexpandedParameterPack()) {
4632 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4633 .get();
4634 if (NewStep)
4635 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4636 }
4637 NewSteps.push_back(NewStep);
4638 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004639 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4640 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004641 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004642 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4643 const_cast<Expr **>(Linears.data()), Linears.size(),
4644 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4645 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004646 ADecl->addAttr(NewAttr);
4647 return ConvertDeclToDeclGroup(ADecl);
4648}
4649
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004650StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4651 Stmt *AStmt,
4652 SourceLocation StartLoc,
4653 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004654 if (!AStmt)
4655 return StmtError();
4656
Alexey Bataeve3727102018-04-18 15:57:46 +00004657 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004658 // 1.2.2 OpenMP Language Terminology
4659 // Structured block - An executable statement with a single entry at the
4660 // top and a single exit at the bottom.
4661 // The point of exit cannot be a branch out of the structured block.
4662 // longjmp() and throw() must not violate the entry/exit criteria.
4663 CS->getCapturedDecl()->setNothrow();
4664
Reid Kleckner87a31802018-03-12 21:43:02 +00004665 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004666
Alexey Bataev25e5b442015-09-15 12:52:43 +00004667 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4668 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004669}
4670
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004671namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004672/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004673/// extracting iteration space of each loop in the loop nest, that will be used
4674/// for IR generation.
4675class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004676 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004677 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004678 /// Data-sharing stack.
4679 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004680 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004681 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004682 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004683 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004684 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004685 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004686 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004687 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004688 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004689 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004690 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004691 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004692 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004693 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004694 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004695 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004696 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004697 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004698 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004699 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004700 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004701 /// Var < UB
4702 /// Var <= UB
4703 /// UB > Var
4704 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004705 /// This will have no value when the condition is !=
4706 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004707 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004708 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004709 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004710 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004711 /// The outer loop counter this loop depends on (if any).
4712 const ValueDecl *DepDecl = nullptr;
4713 /// Contains number of loop (starts from 1) on which loop counter init
4714 /// expression of this loop depends on.
4715 Optional<unsigned> InitDependOnLC;
4716 /// Contains number of loop (starts from 1) on which loop counter condition
4717 /// expression of this loop depends on.
4718 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004719 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004720 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004721
4722public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00004723 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
4724 SourceLocation DefaultLoc)
4725 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
4726 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004727 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004728 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004729 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004730 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004731 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004732 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004733 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004734 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004735 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004736 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004737 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004738 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004739 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004740 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004741 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004742 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004743 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004744 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004745 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004746 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004747 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004748 /// True, if the compare operator is strict (<, > or !=).
4749 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004750 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004751 Expr *buildNumIterations(
4752 Scope *S, const bool LimitedType,
4753 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004754 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004755 Expr *
4756 buildPreCond(Scope *S, Expr *Cond,
4757 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004758 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004759 DeclRefExpr *
4760 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4761 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004762 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004763 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004764 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004765 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004766 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004767 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004768 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004769 /// Build loop data with counter value for depend clauses in ordered
4770 /// directives.
4771 Expr *
4772 buildOrderedLoopData(Scope *S, Expr *Counter,
4773 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4774 SourceLocation Loc, Expr *Inc = nullptr,
4775 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004776 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004777 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004778
4779private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004780 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004781 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004782 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004783 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00004784 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
4785 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004786 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004787 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4788 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004789 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004790 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004791};
4792
Alexey Bataeve3727102018-04-18 15:57:46 +00004793bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004794 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004795 assert(!LB && !UB && !Step);
4796 return false;
4797 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004798 return LCDecl->getType()->isDependentType() ||
4799 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4800 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004801}
4802
Alexey Bataeve3727102018-04-18 15:57:46 +00004803bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004804 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00004805 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004806 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004807 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004808 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004809 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004810 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004811 LCDecl = getCanonicalDecl(NewLCDecl);
4812 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004813 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4814 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004815 if ((Ctor->isCopyOrMoveConstructor() ||
4816 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4817 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004818 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004819 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004820 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004821 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004822 return false;
4823}
4824
Alexey Bataev316ccf62019-01-29 18:51:58 +00004825bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4826 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004827 bool StrictOp, SourceRange SR,
4828 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004829 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004830 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4831 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004832 if (!NewUB)
4833 return true;
4834 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004835 if (LessOp)
4836 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004837 TestIsStrictOp = StrictOp;
4838 ConditionSrcRange = SR;
4839 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004840 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004841 return false;
4842}
4843
Alexey Bataeve3727102018-04-18 15:57:46 +00004844bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004845 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004846 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004847 if (!NewStep)
4848 return true;
4849 if (!NewStep->isValueDependent()) {
4850 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004851 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004852 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4853 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004854 if (Val.isInvalid())
4855 return true;
4856 NewStep = Val.get();
4857
4858 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4859 // If test-expr is of form var relational-op b and relational-op is < or
4860 // <= then incr-expr must cause var to increase on each iteration of the
4861 // loop. If test-expr is of form var relational-op b and relational-op is
4862 // > or >= then incr-expr must cause var to decrease on each iteration of
4863 // the loop.
4864 // If test-expr is of form b relational-op var and relational-op is < or
4865 // <= then incr-expr must cause var to decrease on each iteration of the
4866 // loop. If test-expr is of form b relational-op var and relational-op is
4867 // > or >= then incr-expr must cause var to increase on each iteration of
4868 // the loop.
4869 llvm::APSInt Result;
4870 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4871 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4872 bool IsConstNeg =
4873 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004874 bool IsConstPos =
4875 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004876 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004877
4878 // != with increment is treated as <; != with decrement is treated as >
4879 if (!TestIsLessOp.hasValue())
4880 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004881 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004882 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004883 (IsConstNeg || (IsUnsigned && Subtract)) :
4884 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004885 SemaRef.Diag(NewStep->getExprLoc(),
4886 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004887 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004888 SemaRef.Diag(ConditionLoc,
4889 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004890 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004891 return true;
4892 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004893 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004894 NewStep =
4895 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4896 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004897 Subtract = !Subtract;
4898 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004899 }
4900
4901 Step = NewStep;
4902 SubtractStep = Subtract;
4903 return false;
4904}
4905
Alexey Bataev622af1d2019-04-24 19:58:30 +00004906namespace {
4907/// Checker for the non-rectangular loops. Checks if the initializer or
4908/// condition expression references loop counter variable.
4909class LoopCounterRefChecker final
4910 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
4911 Sema &SemaRef;
4912 DSAStackTy &Stack;
4913 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004914 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004915 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004916 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004917 unsigned BaseLoopId = 0;
4918 bool checkDecl(const Expr *E, const ValueDecl *VD) {
4919 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
4920 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
4921 << (IsInitializer ? 0 : 1);
4922 return false;
4923 }
4924 const auto &&Data = Stack.isLoopControlVariable(VD);
4925 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
4926 // The type of the loop iterator on which we depend may not have a random
4927 // access iterator type.
4928 if (Data.first && VD->getType()->isRecordType()) {
4929 SmallString<128> Name;
4930 llvm::raw_svector_ostream OS(Name);
4931 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4932 /*Qualified=*/true);
4933 SemaRef.Diag(E->getExprLoc(),
4934 diag::err_omp_wrong_dependency_iterator_type)
4935 << OS.str();
4936 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
4937 return false;
4938 }
4939 if (Data.first &&
4940 (DepDecl || (PrevDepDecl &&
4941 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
4942 if (!DepDecl && PrevDepDecl)
4943 DepDecl = PrevDepDecl;
4944 SmallString<128> Name;
4945 llvm::raw_svector_ostream OS(Name);
4946 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4947 /*Qualified=*/true);
4948 SemaRef.Diag(E->getExprLoc(),
4949 diag::err_omp_invariant_or_linear_dependency)
4950 << OS.str();
4951 return false;
4952 }
4953 if (Data.first) {
4954 DepDecl = VD;
4955 BaseLoopId = Data.first;
4956 }
4957 return Data.first;
4958 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004959
4960public:
4961 bool VisitDeclRefExpr(const DeclRefExpr *E) {
4962 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004963 if (isa<VarDecl>(VD))
4964 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00004965 return false;
4966 }
4967 bool VisitMemberExpr(const MemberExpr *E) {
4968 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
4969 const ValueDecl *VD = E->getMemberDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004970 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00004971 }
4972 return false;
4973 }
4974 bool VisitStmt(const Stmt *S) {
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004975 bool Res = true;
4976 for (const Stmt *Child : S->children())
4977 Res = Child && Visit(Child) && Res;
4978 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004979 }
4980 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004981 const ValueDecl *CurLCDecl, bool IsInitializer,
4982 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00004983 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004984 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
4985 unsigned getBaseLoopId() const {
4986 assert(CurLCDecl && "Expected loop dependency.");
4987 return BaseLoopId;
4988 }
4989 const ValueDecl *getDepDecl() const {
4990 assert(CurLCDecl && "Expected loop dependency.");
4991 return DepDecl;
4992 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004993};
4994} // namespace
4995
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004996Optional<unsigned>
4997OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
4998 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00004999 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005000 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5001 DepDecl);
5002 if (LoopStmtChecker.Visit(S)) {
5003 DepDecl = LoopStmtChecker.getDepDecl();
5004 return LoopStmtChecker.getBaseLoopId();
5005 }
5006 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005007}
5008
Alexey Bataeve3727102018-04-18 15:57:46 +00005009bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005010 // Check init-expr for canonical loop form and save loop counter
5011 // variable - #Var and its initialization value - #LB.
5012 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5013 // var = lb
5014 // integer-type var = lb
5015 // random-access-iterator-type var = lb
5016 // pointer-type var = lb
5017 //
5018 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005019 if (EmitDiags) {
5020 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5021 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005022 return true;
5023 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005024 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5025 if (!ExprTemp->cleanupsHaveSideEffects())
5026 S = ExprTemp->getSubExpr();
5027
Alexander Musmana5f070a2014-10-01 06:03:56 +00005028 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005029 if (Expr *E = dyn_cast<Expr>(S))
5030 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005031 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005032 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005033 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005034 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5035 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5036 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005037 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5038 EmitDiags);
5039 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005040 }
5041 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5042 if (ME->isArrow() &&
5043 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005044 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5045 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005046 }
5047 }
David Majnemer9d168222016-08-05 17:44:54 +00005048 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005049 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005050 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005051 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005052 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005053 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005054 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005055 diag::ext_omp_loop_not_canonical_init)
5056 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005057 return setLCDeclAndLB(
5058 Var,
5059 buildDeclRefExpr(SemaRef, Var,
5060 Var->getType().getNonReferenceType(),
5061 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005062 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005063 }
5064 }
5065 }
David Majnemer9d168222016-08-05 17:44:54 +00005066 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005067 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005068 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005069 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005070 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5071 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005072 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5073 EmitDiags);
5074 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005075 }
5076 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5077 if (ME->isArrow() &&
5078 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005079 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5080 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005081 }
5082 }
5083 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005084
Alexey Bataeve3727102018-04-18 15:57:46 +00005085 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005086 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005087 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005088 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005089 << S->getSourceRange();
5090 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005091 return true;
5092}
5093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005094/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005095/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005096static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005097 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005098 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005099 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005100 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005101 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005102 if ((Ctor->isCopyOrMoveConstructor() ||
5103 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5104 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005105 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005106 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5107 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005108 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005109 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005110 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005111 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5112 return getCanonicalDecl(ME->getMemberDecl());
5113 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005114}
5115
Alexey Bataeve3727102018-04-18 15:57:46 +00005116bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005117 // Check test-expr for canonical form, save upper-bound UB, flags for
5118 // less/greater and for strict/non-strict comparison.
5119 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5120 // var relational-op b
5121 // b relational-op var
5122 //
5123 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005124 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005125 return true;
5126 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005127 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005128 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005129 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005130 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005131 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5132 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005133 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5134 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5135 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005136 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5137 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005138 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5139 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5140 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005141 } else if (BO->getOpcode() == BO_NE)
5142 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
5143 BO->getRHS() : BO->getLHS(),
5144 /*LessOp=*/llvm::None,
5145 /*StrictOp=*/true,
5146 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005147 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005148 if (CE->getNumArgs() == 2) {
5149 auto Op = CE->getOperator();
5150 switch (Op) {
5151 case OO_Greater:
5152 case OO_GreaterEqual:
5153 case OO_Less:
5154 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005155 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5156 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005157 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5158 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005159 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5160 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005161 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5162 CE->getOperatorLoc());
5163 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005164 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00005165 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
5166 CE->getArg(1) : CE->getArg(0),
5167 /*LessOp=*/llvm::None,
5168 /*StrictOp=*/true,
5169 CE->getSourceRange(),
5170 CE->getOperatorLoc());
5171 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005172 default:
5173 break;
5174 }
5175 }
5176 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005177 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005178 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005179 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005180 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005181 return true;
5182}
5183
Alexey Bataeve3727102018-04-18 15:57:46 +00005184bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005185 // RHS of canonical loop form increment can be:
5186 // var + incr
5187 // incr + var
5188 // var - incr
5189 //
5190 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005191 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005192 if (BO->isAdditiveOp()) {
5193 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005194 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5195 return setStep(BO->getRHS(), !IsAdd);
5196 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5197 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005198 }
David Majnemer9d168222016-08-05 17:44:54 +00005199 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005200 bool IsAdd = CE->getOperator() == OO_Plus;
5201 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005202 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5203 return setStep(CE->getArg(1), !IsAdd);
5204 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5205 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005206 }
5207 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005208 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005209 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005210 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005211 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005212 return true;
5213}
5214
Alexey Bataeve3727102018-04-18 15:57:46 +00005215bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005216 // Check incr-expr for canonical loop form and return true if it
5217 // does not conform.
5218 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5219 // ++var
5220 // var++
5221 // --var
5222 // var--
5223 // var += incr
5224 // var -= incr
5225 // var = var + incr
5226 // var = incr + var
5227 // var = var - incr
5228 //
5229 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005230 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005231 return true;
5232 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005233 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5234 if (!ExprTemp->cleanupsHaveSideEffects())
5235 S = ExprTemp->getSubExpr();
5236
Alexander Musmana5f070a2014-10-01 06:03:56 +00005237 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005238 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005239 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005240 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005241 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5242 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005243 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005244 (UO->isDecrementOp() ? -1 : 1))
5245 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005246 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005247 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005248 switch (BO->getOpcode()) {
5249 case BO_AddAssign:
5250 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005251 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5252 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005253 break;
5254 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005255 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5256 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005257 break;
5258 default:
5259 break;
5260 }
David Majnemer9d168222016-08-05 17:44:54 +00005261 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005262 switch (CE->getOperator()) {
5263 case OO_PlusPlus:
5264 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005265 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5266 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005267 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005268 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005269 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5270 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005271 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005272 break;
5273 case OO_PlusEqual:
5274 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005275 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5276 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005277 break;
5278 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005279 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5280 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005281 break;
5282 default:
5283 break;
5284 }
5285 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005286 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005287 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005288 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005289 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005290 return true;
5291}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005292
Alexey Bataev5a3af132016-03-29 08:58:54 +00005293static ExprResult
5294tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005295 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005296 if (SemaRef.CurContext->isDependentContext())
5297 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005298 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5299 return SemaRef.PerformImplicitConversion(
5300 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5301 /*AllowExplicit=*/true);
5302 auto I = Captures.find(Capture);
5303 if (I != Captures.end())
5304 return buildCapture(SemaRef, Capture, I->second);
5305 DeclRefExpr *Ref = nullptr;
5306 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5307 Captures[Capture] = Ref;
5308 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005309}
5310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005311/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005312Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005313 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005314 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005315 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005316 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005317 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005318 SemaRef.getLangOpts().CPlusPlus) {
5319 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00005320 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
5321 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00005322 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
5323 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005324 if (!Upper || !Lower)
5325 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005326
5327 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5328
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005329 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005330 // BuildBinOp already emitted error, this one is to point user to upper
5331 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005332 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005333 << Upper->getSourceRange() << Lower->getSourceRange();
5334 return nullptr;
5335 }
5336 }
5337
5338 if (!Diff.isUsable())
5339 return nullptr;
5340
5341 // Upper - Lower [- 1]
5342 if (TestIsStrictOp)
5343 Diff = SemaRef.BuildBinOp(
5344 S, DefaultLoc, BO_Sub, Diff.get(),
5345 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5346 if (!Diff.isUsable())
5347 return nullptr;
5348
5349 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005350 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005351 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005352 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005353 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005354 if (!Diff.isUsable())
5355 return nullptr;
5356
5357 // Parentheses (for dumping/debugging purposes only).
5358 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5359 if (!Diff.isUsable())
5360 return nullptr;
5361
5362 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005363 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005364 if (!Diff.isUsable())
5365 return nullptr;
5366
Alexander Musman174b3ca2014-10-06 11:16:29 +00005367 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005368 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00005369 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005370 bool UseVarType = VarType->hasIntegerRepresentation() &&
5371 C.getTypeSize(Type) > C.getTypeSize(VarType);
5372 if (!Type->isIntegerType() || UseVarType) {
5373 unsigned NewSize =
5374 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
5375 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
5376 : Type->hasSignedIntegerRepresentation();
5377 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00005378 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
5379 Diff = SemaRef.PerformImplicitConversion(
5380 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
5381 if (!Diff.isUsable())
5382 return nullptr;
5383 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005384 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005385 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00005386 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
5387 if (NewSize != C.getTypeSize(Type)) {
5388 if (NewSize < C.getTypeSize(Type)) {
5389 assert(NewSize == 64 && "incorrect loop var size");
5390 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
5391 << InitSrcRange << ConditionSrcRange;
5392 }
5393 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005394 NewSize, Type->hasSignedIntegerRepresentation() ||
5395 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00005396 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
5397 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
5398 Sema::AA_Converting, true);
5399 if (!Diff.isUsable())
5400 return nullptr;
5401 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005402 }
5403 }
5404
Alexander Musmana5f070a2014-10-01 06:03:56 +00005405 return Diff.get();
5406}
5407
Alexey Bataeve3727102018-04-18 15:57:46 +00005408Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005409 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00005410 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005411 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
5412 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5413 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005414
Alexey Bataeve3727102018-04-18 15:57:46 +00005415 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
5416 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005417 if (!NewLB.isUsable() || !NewUB.isUsable())
5418 return nullptr;
5419
Alexey Bataeve3727102018-04-18 15:57:46 +00005420 ExprResult CondExpr =
5421 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005422 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005423 (TestIsStrictOp ? BO_LT : BO_LE) :
5424 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00005425 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005426 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005427 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
5428 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00005429 CondExpr = SemaRef.PerformImplicitConversion(
5430 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
5431 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005432 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00005433 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00005434 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005435 return CondExpr.isUsable() ? CondExpr.get() : Cond;
5436}
5437
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005438/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005439DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00005440 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5441 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005442 auto *VD = dyn_cast<VarDecl>(LCDecl);
5443 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005444 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
5445 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005446 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005447 const DSAStackTy::DSAVarData Data =
5448 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005449 // If the loop control decl is explicitly marked as private, do not mark it
5450 // as captured again.
5451 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
5452 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005453 return Ref;
5454 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00005455 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00005456}
5457
Alexey Bataeve3727102018-04-18 15:57:46 +00005458Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005459 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005460 QualType Type = LCDecl->getType().getNonReferenceType();
5461 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00005462 SemaRef, DefaultLoc, Type, LCDecl->getName(),
5463 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
5464 isa<VarDecl>(LCDecl)
5465 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
5466 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00005467 if (PrivateVar->isInvalidDecl())
5468 return nullptr;
5469 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
5470 }
5471 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005472}
5473
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005474/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005475Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005476
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005477/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005478Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005479
Alexey Bataevf138fda2018-08-13 19:04:24 +00005480Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
5481 Scope *S, Expr *Counter,
5482 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
5483 Expr *Inc, OverloadedOperatorKind OOK) {
5484 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
5485 if (!Cnt)
5486 return nullptr;
5487 if (Inc) {
5488 assert((OOK == OO_Plus || OOK == OO_Minus) &&
5489 "Expected only + or - operations for depend clauses.");
5490 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
5491 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
5492 if (!Cnt)
5493 return nullptr;
5494 }
5495 ExprResult Diff;
5496 QualType VarType = LCDecl->getType().getNonReferenceType();
5497 if (VarType->isIntegerType() || VarType->isPointerType() ||
5498 SemaRef.getLangOpts().CPlusPlus) {
5499 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00005500 Expr *Upper = TestIsLessOp.getValue()
5501 ? Cnt
5502 : tryBuildCapture(SemaRef, UB, Captures).get();
5503 Expr *Lower = TestIsLessOp.getValue()
5504 ? tryBuildCapture(SemaRef, LB, Captures).get()
5505 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005506 if (!Upper || !Lower)
5507 return nullptr;
5508
5509 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5510
5511 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5512 // BuildBinOp already emitted error, this one is to point user to upper
5513 // and lower bound, and to tell what is passed to 'operator-'.
5514 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5515 << Upper->getSourceRange() << Lower->getSourceRange();
5516 return nullptr;
5517 }
5518 }
5519
5520 if (!Diff.isUsable())
5521 return nullptr;
5522
5523 // Parentheses (for dumping/debugging purposes only).
5524 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5525 if (!Diff.isUsable())
5526 return nullptr;
5527
5528 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5529 if (!NewStep.isUsable())
5530 return nullptr;
5531 // (Upper - Lower) / Step
5532 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5533 if (!Diff.isUsable())
5534 return nullptr;
5535
5536 return Diff.get();
5537}
5538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005539/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005540struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005541 /// True if the condition operator is the strict compare operator (<, > or
5542 /// !=).
5543 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005544 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005545 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005546 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005547 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005548 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005550 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005551 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005552 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005553 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00005554 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005555 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005556 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005557 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005558 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005559 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005560 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005561 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005562 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005563 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005564 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005565 SourceRange IncSrcRange;
5566};
5567
Alexey Bataev23b69422014-06-18 07:08:49 +00005568} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005569
Alexey Bataev9c821032015-04-30 04:23:23 +00005570void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5571 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5572 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005573 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5574 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005575 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005576 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00005577 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005578 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5579 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005580 auto *VD = dyn_cast<VarDecl>(D);
5581 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005582 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005583 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005584 } else {
5585 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5586 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005587 VD = cast<VarDecl>(Ref->getDecl());
5588 }
5589 }
5590 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005591 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5592 if (LD != D->getCanonicalDecl()) {
5593 DSAStack->resetPossibleLoopCounter();
5594 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5595 MarkDeclarationsReferencedInExpr(
5596 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5597 Var->getType().getNonLValueExprType(Context),
5598 ForLoc, /*RefersToCapture=*/true));
5599 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005600 }
5601 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005602 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005603 }
5604}
5605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005607/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005608static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005609 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5610 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005611 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5612 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005613 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005614 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005615 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005616 // OpenMP [2.6, Canonical Loop Form]
5617 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005618 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005619 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005620 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005621 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005622 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005623 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005624 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005625 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5626 SemaRef.Diag(DSA.getConstructLoc(),
5627 diag::note_omp_collapse_ordered_expr)
5628 << 2 << CollapseLoopCountExpr->getSourceRange()
5629 << OrderedLoopCountExpr->getSourceRange();
5630 else if (CollapseLoopCountExpr)
5631 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5632 diag::note_omp_collapse_ordered_expr)
5633 << 0 << CollapseLoopCountExpr->getSourceRange();
5634 else
5635 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5636 diag::note_omp_collapse_ordered_expr)
5637 << 1 << OrderedLoopCountExpr->getSourceRange();
5638 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005639 return true;
5640 }
5641 assert(For->getBody());
5642
Alexey Bataev622af1d2019-04-24 19:58:30 +00005643 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005644
5645 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005646 Stmt *Init = For->getInit();
5647 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005648 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005649
5650 bool HasErrors = false;
5651
5652 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005653 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5654 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005655
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005656 // OpenMP [2.6, Canonical Loop Form]
5657 // Var is one of the following:
5658 // A variable of signed or unsigned integer type.
5659 // For C++, a variable of a random access iterator type.
5660 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005661 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005662 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5663 !VarType->isPointerType() &&
5664 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005665 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005666 << SemaRef.getLangOpts().CPlusPlus;
5667 HasErrors = true;
5668 }
5669
5670 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5671 // a Construct
5672 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5673 // parallel for construct is (are) private.
5674 // The loop iteration variable in the associated for-loop of a simd
5675 // construct with just one associated for-loop is linear with a
5676 // constant-linear-step that is the increment of the associated for-loop.
5677 // Exclude loop var from the list of variables with implicitly defined data
5678 // sharing attributes.
5679 VarsWithImplicitDSA.erase(LCDecl);
5680
5681 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5682 // in a Construct, C/C++].
5683 // The loop iteration variable in the associated for-loop of a simd
5684 // construct with just one associated for-loop may be listed in a linear
5685 // clause with a constant-linear-step that is the increment of the
5686 // associated for-loop.
5687 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5688 // parallel for construct may be listed in a private or lastprivate clause.
5689 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5690 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5691 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005692 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005693 isOpenMPSimdDirective(DKind)
5694 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5695 : OMPC_private;
5696 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5697 DVar.CKind != PredeterminedCKind) ||
5698 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5699 isOpenMPDistributeDirective(DKind)) &&
5700 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5701 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5702 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005703 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005704 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5705 << getOpenMPClauseName(PredeterminedCKind);
5706 if (DVar.RefExpr == nullptr)
5707 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005708 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005709 HasErrors = true;
5710 } else if (LoopDeclRefExpr != nullptr) {
5711 // Make the loop iteration variable private (for worksharing constructs),
5712 // linear (for simd directives with the only one associated loop) or
5713 // lastprivate (for simd directives with several collapsed or ordered
5714 // loops).
5715 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005716 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005717 }
5718
5719 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5720
5721 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005722 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005723
5724 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005725 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005726 }
5727
Alexey Bataeve3727102018-04-18 15:57:46 +00005728 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005729 return HasErrors;
5730
Alexander Musmana5f070a2014-10-01 06:03:56 +00005731 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005732 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005733 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5734 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005735 DSA.getCurScope(),
5736 (isOpenMPWorksharingDirective(DKind) ||
5737 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5738 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005739 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5740 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5741 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5742 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5743 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5744 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5745 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5746 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005747 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005748
Alexey Bataev62dbb972015-04-22 11:59:37 +00005749 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5750 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005751 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005752 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005753 ResultIterSpace.CounterInit == nullptr ||
5754 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005755 if (!HasErrors && DSA.isOrderedRegion()) {
5756 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5757 if (CurrentNestedLoopCount <
5758 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5759 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5760 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5761 DSA.getOrderedRegionParam().second->setLoopCounter(
5762 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5763 }
5764 }
5765 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5766 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5767 // Erroneous case - clause has some problems.
5768 continue;
5769 }
5770 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5771 Pair.second.size() <= CurrentNestedLoopCount) {
5772 // Erroneous case - clause has some problems.
5773 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5774 continue;
5775 }
5776 Expr *CntValue;
5777 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5778 CntValue = ISC.buildOrderedLoopData(
5779 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5780 Pair.first->getDependencyLoc());
5781 else
5782 CntValue = ISC.buildOrderedLoopData(
5783 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5784 Pair.first->getDependencyLoc(),
5785 Pair.second[CurrentNestedLoopCount].first,
5786 Pair.second[CurrentNestedLoopCount].second);
5787 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5788 }
5789 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005790
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005791 return HasErrors;
5792}
5793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005794/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005795static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005796buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005797 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005798 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005799 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005800 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005801 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005802 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005803 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005804 VarRef.get()->getType())) {
5805 NewStart = SemaRef.PerformImplicitConversion(
5806 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5807 /*AllowExplicit=*/true);
5808 if (!NewStart.isUsable())
5809 return ExprError();
5810 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005811
Alexey Bataeve3727102018-04-18 15:57:46 +00005812 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005813 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5814 return Init;
5815}
5816
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005817/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005818static ExprResult buildCounterUpdate(
5819 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5820 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5821 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005822 // Add parentheses (for debugging purposes only).
5823 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5824 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5825 !Step.isUsable())
5826 return ExprError();
5827
Alexey Bataev5a3af132016-03-29 08:58:54 +00005828 ExprResult NewStep = Step;
5829 if (Captures)
5830 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005831 if (NewStep.isInvalid())
5832 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005833 ExprResult Update =
5834 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005835 if (!Update.isUsable())
5836 return ExprError();
5837
Alexey Bataevc0214e02016-02-16 12:13:49 +00005838 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5839 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005840 ExprResult NewStart = Start;
5841 if (Captures)
5842 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005843 if (NewStart.isInvalid())
5844 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005845
Alexey Bataevc0214e02016-02-16 12:13:49 +00005846 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5847 ExprResult SavedUpdate = Update;
5848 ExprResult UpdateVal;
5849 if (VarRef.get()->getType()->isOverloadableType() ||
5850 NewStart.get()->getType()->isOverloadableType() ||
5851 Update.get()->getType()->isOverloadableType()) {
5852 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5853 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5854 Update =
5855 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5856 if (Update.isUsable()) {
5857 UpdateVal =
5858 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5859 VarRef.get(), SavedUpdate.get());
5860 if (UpdateVal.isUsable()) {
5861 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5862 UpdateVal.get());
5863 }
5864 }
5865 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5866 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005867
Alexey Bataevc0214e02016-02-16 12:13:49 +00005868 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5869 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5870 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5871 NewStart.get(), SavedUpdate.get());
5872 if (!Update.isUsable())
5873 return ExprError();
5874
Alexey Bataev11481f52016-02-17 10:29:05 +00005875 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5876 VarRef.get()->getType())) {
5877 Update = SemaRef.PerformImplicitConversion(
5878 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5879 if (!Update.isUsable())
5880 return ExprError();
5881 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005882
5883 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5884 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005885 return Update;
5886}
5887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005888/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005889/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005890static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005891 if (E == nullptr)
5892 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005893 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005894 QualType OldType = E->getType();
5895 unsigned HasBits = C.getTypeSize(OldType);
5896 if (HasBits >= Bits)
5897 return ExprResult(E);
5898 // OK to convert to signed, because new type has more bits than old.
5899 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5900 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5901 true);
5902}
5903
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005904/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005905/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005906static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005907 if (E == nullptr)
5908 return false;
5909 llvm::APSInt Result;
5910 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5911 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5912 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005913}
5914
Alexey Bataev5a3af132016-03-29 08:58:54 +00005915/// Build preinits statement for the given declarations.
5916static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005917 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005918 if (!PreInits.empty()) {
5919 return new (Context) DeclStmt(
5920 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5921 SourceLocation(), SourceLocation());
5922 }
5923 return nullptr;
5924}
5925
5926/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005927static Stmt *
5928buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005929 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005930 if (!Captures.empty()) {
5931 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005932 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005933 PreInits.push_back(Pair.second->getDecl());
5934 return buildPreInits(Context, PreInits);
5935 }
5936 return nullptr;
5937}
5938
5939/// Build postupdate expression for the given list of postupdates expressions.
5940static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5941 Expr *PostUpdate = nullptr;
5942 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005943 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005944 Expr *ConvE = S.BuildCStyleCastExpr(
5945 E->getExprLoc(),
5946 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5947 E->getExprLoc(), E)
5948 .get();
5949 PostUpdate = PostUpdate
5950 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5951 PostUpdate, ConvE)
5952 .get()
5953 : ConvE;
5954 }
5955 }
5956 return PostUpdate;
5957}
5958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005959/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005960/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5961/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005962static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005963checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005964 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5965 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005966 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005967 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005968 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005969 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005970 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005971 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005972 if (!CollapseLoopCountExpr->isValueDependent() &&
5973 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00005974 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005975 } else {
5976 Built.clear(/*size=*/1);
5977 return 1;
5978 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00005979 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005980 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005981 if (OrderedLoopCountExpr) {
5982 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005983 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005984 if (!OrderedLoopCountExpr->isValueDependent() &&
5985 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
5986 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00005987 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005988 if (Result.getLimitedValue() < NestedLoopCount) {
5989 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5990 diag::err_omp_wrong_ordered_loop_count)
5991 << OrderedLoopCountExpr->getSourceRange();
5992 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5993 diag::note_collapse_loop_count)
5994 << CollapseLoopCountExpr->getSourceRange();
5995 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005996 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005997 } else {
5998 Built.clear(/*size=*/1);
5999 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006000 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006001 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006002 // This is helper routine for loop directives (e.g., 'for', 'simd',
6003 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006004 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006005 SmallVector<LoopIterationSpace, 4> IterSpaces(
6006 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006007 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006008 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006009 if (checkOpenMPIterationSpace(
6010 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6011 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6012 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
6013 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006014 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006015 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006016 // OpenMP [2.8.1, simd construct, Restrictions]
6017 // All loops associated with the construct must be perfectly nested; that
6018 // is, there must be no intervening code nor any OpenMP directive between
6019 // any two loops.
6020 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006021 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006022 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6023 if (checkOpenMPIterationSpace(
6024 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6025 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6026 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
6027 Captures))
6028 return 0;
6029 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6030 // Handle initialization of captured loop iterator variables.
6031 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6032 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6033 Captures[DRE] = DRE;
6034 }
6035 }
6036 // Move on to the next nested for loop, or to the loop body.
6037 // OpenMP [2.8.1, simd construct, Restrictions]
6038 // All loops associated with the construct must be perfectly nested; that
6039 // is, there must be no intervening code nor any OpenMP directive between
6040 // any two loops.
6041 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
6042 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006043
Alexander Musmana5f070a2014-10-01 06:03:56 +00006044 Built.clear(/* size */ NestedLoopCount);
6045
6046 if (SemaRef.CurContext->isDependentContext())
6047 return NestedLoopCount;
6048
6049 // An example of what is generated for the following code:
6050 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006051 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006052 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006053 // for (k = 0; k < NK; ++k)
6054 // for (j = J0; j < NJ; j+=2) {
6055 // <loop body>
6056 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006057 //
6058 // We generate the code below.
6059 // Note: the loop body may be outlined in CodeGen.
6060 // Note: some counters may be C++ classes, operator- is used to find number of
6061 // iterations and operator+= to calculate counter value.
6062 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
6063 // or i64 is currently supported).
6064 //
6065 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
6066 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
6067 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
6068 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
6069 // // similar updates for vars in clauses (e.g. 'linear')
6070 // <loop body (using local i and j)>
6071 // }
6072 // i = NI; // assign final values of counters
6073 // j = NJ;
6074 //
6075
6076 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
6077 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006078 // Precondition tests if there is at least one iteration (all conditions are
6079 // true).
6080 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00006081 Expr *N0 = IterSpaces[0].NumIterations;
6082 ExprResult LastIteration32 =
6083 widenIterationCount(/*Bits=*/32,
6084 SemaRef
6085 .PerformImplicitConversion(
6086 N0->IgnoreImpCasts(), N0->getType(),
6087 Sema::AA_Converting, /*AllowExplicit=*/true)
6088 .get(),
6089 SemaRef);
6090 ExprResult LastIteration64 = widenIterationCount(
6091 /*Bits=*/64,
6092 SemaRef
6093 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
6094 Sema::AA_Converting,
6095 /*AllowExplicit=*/true)
6096 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006097 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006098
6099 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
6100 return NestedLoopCount;
6101
Alexey Bataeve3727102018-04-18 15:57:46 +00006102 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006103 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
6104
6105 Scope *CurScope = DSA.getCurScope();
6106 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006107 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00006108 PreCond =
6109 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
6110 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00006111 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006112 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00006113 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006114 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
6115 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006116 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006117 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006118 SemaRef
6119 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6120 Sema::AA_Converting,
6121 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006122 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006123 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006124 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006125 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006126 SemaRef
6127 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6128 Sema::AA_Converting,
6129 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006130 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006131 }
6132
6133 // Choose either the 32-bit or 64-bit version.
6134 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006135 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
6136 (LastIteration32.isUsable() &&
6137 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
6138 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
6139 fitsInto(
6140 /*Bits=*/32,
6141 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
6142 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00006143 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00006144 QualType VType = LastIteration.get()->getType();
6145 QualType RealVType = VType;
6146 QualType StrideVType = VType;
6147 if (isOpenMPTaskLoopDirective(DKind)) {
6148 VType =
6149 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
6150 StrideVType =
6151 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6152 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006153
6154 if (!LastIteration.isUsable())
6155 return 0;
6156
6157 // Save the number of iterations.
6158 ExprResult NumIterations = LastIteration;
6159 {
6160 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006161 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
6162 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006163 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6164 if (!LastIteration.isUsable())
6165 return 0;
6166 }
6167
6168 // Calculate the last iteration number beforehand instead of doing this on
6169 // each iteration. Do not do this if the number of iterations may be kfold-ed.
6170 llvm::APSInt Result;
6171 bool IsConstant =
6172 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
6173 ExprResult CalcLastIteration;
6174 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006175 ExprResult SaveRef =
6176 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006177 LastIteration = SaveRef;
6178
6179 // Prepare SaveRef + 1.
6180 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006181 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006182 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6183 if (!NumIterations.isUsable())
6184 return 0;
6185 }
6186
6187 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
6188
David Majnemer9d168222016-08-05 17:44:54 +00006189 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006190 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006191 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6192 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006193 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006194 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
6195 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006196 SemaRef.AddInitializerToDecl(LBDecl,
6197 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6198 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006199
6200 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006201 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
6202 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00006203 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00006204 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006205
6206 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
6207 // This will be used to implement clause 'lastprivate'.
6208 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006209 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
6210 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006211 SemaRef.AddInitializerToDecl(ILDecl,
6212 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6213 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006214
6215 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00006216 VarDecl *STDecl =
6217 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
6218 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006219 SemaRef.AddInitializerToDecl(STDecl,
6220 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
6221 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006222
6223 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00006224 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00006225 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
6226 UB.get(), LastIteration.get());
6227 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00006228 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
6229 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00006230 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
6231 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006232 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006233
6234 // If we have a combined directive that combines 'distribute', 'for' or
6235 // 'simd' we need to be able to access the bounds of the schedule of the
6236 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
6237 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
6238 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00006239 // Lower bound variable, initialized with zero.
6240 VarDecl *CombLBDecl =
6241 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
6242 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
6243 SemaRef.AddInitializerToDecl(
6244 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6245 /*DirectInit*/ false);
6246
6247 // Upper bound variable, initialized with last iteration number.
6248 VarDecl *CombUBDecl =
6249 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
6250 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
6251 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
6252 /*DirectInit*/ false);
6253
6254 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
6255 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
6256 ExprResult CombCondOp =
6257 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
6258 LastIteration.get(), CombUB.get());
6259 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
6260 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006261 CombEUB =
6262 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006263
Alexey Bataeve3727102018-04-18 15:57:46 +00006264 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006265 // We expect to have at least 2 more parameters than the 'parallel'
6266 // directive does - the lower and upper bounds of the previous schedule.
6267 assert(CD->getNumParams() >= 4 &&
6268 "Unexpected number of parameters in loop combined directive");
6269
6270 // Set the proper type for the bounds given what we learned from the
6271 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00006272 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
6273 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006274
6275 // Previous lower and upper bounds are obtained from the region
6276 // parameters.
6277 PrevLB =
6278 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
6279 PrevUB =
6280 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
6281 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006282 }
6283
6284 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006285 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006286 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006287 {
Alexey Bataev7292c292016-04-25 12:22:29 +00006288 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
6289 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00006290 Expr *RHS =
6291 (isOpenMPWorksharingDirective(DKind) ||
6292 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
6293 ? LB.get()
6294 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006295 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006296 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006297
6298 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6299 Expr *CombRHS =
6300 (isOpenMPWorksharingDirective(DKind) ||
6301 isOpenMPTaskLoopDirective(DKind) ||
6302 isOpenMPDistributeDirective(DKind))
6303 ? CombLB.get()
6304 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
6305 CombInit =
6306 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006307 CombInit =
6308 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006309 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006310 }
6311
Alexey Bataev316ccf62019-01-29 18:51:58 +00006312 bool UseStrictCompare =
6313 RealVType->hasUnsignedIntegerRepresentation() &&
6314 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
6315 return LIS.IsStrictCompare;
6316 });
6317 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
6318 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006319 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00006320 Expr *BoundUB = UB.get();
6321 if (UseStrictCompare) {
6322 BoundUB =
6323 SemaRef
6324 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
6325 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6326 .get();
6327 BoundUB =
6328 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
6329 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006330 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006331 (isOpenMPWorksharingDirective(DKind) ||
6332 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00006333 ? SemaRef.BuildBinOp(CurScope, CondLoc,
6334 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
6335 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00006336 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6337 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006338 ExprResult CombDistCond;
6339 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006340 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6341 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006342 }
6343
Carlo Bertolliffafe102017-04-20 00:39:39 +00006344 ExprResult CombCond;
6345 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006346 Expr *BoundCombUB = CombUB.get();
6347 if (UseStrictCompare) {
6348 BoundCombUB =
6349 SemaRef
6350 .BuildBinOp(
6351 CurScope, CondLoc, BO_Add, BoundCombUB,
6352 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6353 .get();
6354 BoundCombUB =
6355 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
6356 .get();
6357 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00006358 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006359 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6360 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006361 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006362 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006363 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006364 ExprResult Inc =
6365 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
6366 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
6367 if (!Inc.isUsable())
6368 return 0;
6369 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006370 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006371 if (!Inc.isUsable())
6372 return 0;
6373
6374 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
6375 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006376 // In combined construct, add combined version that use CombLB and CombUB
6377 // base variables for the update
6378 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006379 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6380 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006381 // LB + ST
6382 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
6383 if (!NextLB.isUsable())
6384 return 0;
6385 // LB = LB + ST
6386 NextLB =
6387 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006388 NextLB =
6389 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006390 if (!NextLB.isUsable())
6391 return 0;
6392 // UB + ST
6393 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
6394 if (!NextUB.isUsable())
6395 return 0;
6396 // UB = UB + ST
6397 NextUB =
6398 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006399 NextUB =
6400 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006401 if (!NextUB.isUsable())
6402 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006403 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6404 CombNextLB =
6405 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
6406 if (!NextLB.isUsable())
6407 return 0;
6408 // LB = LB + ST
6409 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
6410 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006411 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
6412 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006413 if (!CombNextLB.isUsable())
6414 return 0;
6415 // UB + ST
6416 CombNextUB =
6417 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
6418 if (!CombNextUB.isUsable())
6419 return 0;
6420 // UB = UB + ST
6421 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
6422 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006423 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
6424 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006425 if (!CombNextUB.isUsable())
6426 return 0;
6427 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006428 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006429
Carlo Bertolliffafe102017-04-20 00:39:39 +00006430 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00006431 // directive with for as IV = IV + ST; ensure upper bound expression based
6432 // on PrevUB instead of NumIterations - used to implement 'for' when found
6433 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006434 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006435 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00006436 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006437 DistCond = SemaRef.BuildBinOp(
6438 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006439 assert(DistCond.isUsable() && "distribute cond expr was not built");
6440
6441 DistInc =
6442 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
6443 assert(DistInc.isUsable() && "distribute inc expr was not built");
6444 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
6445 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006446 DistInc =
6447 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006448 assert(DistInc.isUsable() && "distribute inc expr was not built");
6449
6450 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
6451 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006452 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006453 ExprResult IsUBGreater =
6454 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
6455 ExprResult CondOp = SemaRef.ActOnConditionalOp(
6456 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
6457 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
6458 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006459 PrevEUB =
6460 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006461
Alexey Bataev316ccf62019-01-29 18:51:58 +00006462 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
6463 // parallel for is in combination with a distribute directive with
6464 // schedule(static, 1)
6465 Expr *BoundPrevUB = PrevUB.get();
6466 if (UseStrictCompare) {
6467 BoundPrevUB =
6468 SemaRef
6469 .BuildBinOp(
6470 CurScope, CondLoc, BO_Add, BoundPrevUB,
6471 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6472 .get();
6473 BoundPrevUB =
6474 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
6475 .get();
6476 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006477 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006478 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6479 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006480 }
6481
Alexander Musmana5f070a2014-10-01 06:03:56 +00006482 // Build updates and final values of the loop counters.
6483 bool HasErrors = false;
6484 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006485 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006486 Built.Updates.resize(NestedLoopCount);
6487 Built.Finals.resize(NestedLoopCount);
6488 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006489 // We implement the following algorithm for obtaining the
6490 // original loop iteration variable values based on the
6491 // value of the collapsed loop iteration variable IV.
6492 //
6493 // Let n+1 be the number of collapsed loops in the nest.
6494 // Iteration variables (I0, I1, .... In)
6495 // Iteration counts (N0, N1, ... Nn)
6496 //
6497 // Acc = IV;
6498 //
6499 // To compute Ik for loop k, 0 <= k <= n, generate:
6500 // Prod = N(k+1) * N(k+2) * ... * Nn;
6501 // Ik = Acc / Prod;
6502 // Acc -= Ik * Prod;
6503 //
6504 ExprResult Acc = IV;
6505 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006506 LoopIterationSpace &IS = IterSpaces[Cnt];
6507 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006508 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006509
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006510 // Compute prod
6511 ExprResult Prod =
6512 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6513 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
6514 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
6515 IterSpaces[K].NumIterations);
6516
6517 // Iter = Acc / Prod
6518 // If there is at least one more inner loop to avoid
6519 // multiplication by 1.
6520 if (Cnt + 1 < NestedLoopCount)
6521 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
6522 Acc.get(), Prod.get());
6523 else
6524 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006525 if (!Iter.isUsable()) {
6526 HasErrors = true;
6527 break;
6528 }
6529
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006530 // Update Acc:
6531 // Acc -= Iter * Prod
6532 // Check if there is at least one more inner loop to avoid
6533 // multiplication by 1.
6534 if (Cnt + 1 < NestedLoopCount)
6535 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
6536 Iter.get(), Prod.get());
6537 else
6538 Prod = Iter;
6539 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
6540 Acc.get(), Prod.get());
6541
Alexey Bataev39f915b82015-05-08 10:41:21 +00006542 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006543 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00006544 DeclRefExpr *CounterVar = buildDeclRefExpr(
6545 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
6546 /*RefersToCapture=*/true);
6547 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006548 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006549 if (!Init.isUsable()) {
6550 HasErrors = true;
6551 break;
6552 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006553 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006554 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6555 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006556 if (!Update.isUsable()) {
6557 HasErrors = true;
6558 break;
6559 }
6560
6561 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006562 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00006563 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006564 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006565 if (!Final.isUsable()) {
6566 HasErrors = true;
6567 break;
6568 }
6569
Alexander Musmana5f070a2014-10-01 06:03:56 +00006570 if (!Update.isUsable() || !Final.isUsable()) {
6571 HasErrors = true;
6572 break;
6573 }
6574 // Save results
6575 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006576 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006577 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006578 Built.Updates[Cnt] = Update.get();
6579 Built.Finals[Cnt] = Final.get();
6580 }
6581 }
6582
6583 if (HasErrors)
6584 return 0;
6585
6586 // Save results
6587 Built.IterationVarRef = IV.get();
6588 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006589 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006590 Built.CalcLastIteration = SemaRef
6591 .ActOnFinishFullExpr(CalcLastIteration.get(),
6592 /*DiscardedValue*/ false)
6593 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006594 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006595 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006596 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006597 Built.Init = Init.get();
6598 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006599 Built.LB = LB.get();
6600 Built.UB = UB.get();
6601 Built.IL = IL.get();
6602 Built.ST = ST.get();
6603 Built.EUB = EUB.get();
6604 Built.NLB = NextLB.get();
6605 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006606 Built.PrevLB = PrevLB.get();
6607 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006608 Built.DistInc = DistInc.get();
6609 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006610 Built.DistCombinedFields.LB = CombLB.get();
6611 Built.DistCombinedFields.UB = CombUB.get();
6612 Built.DistCombinedFields.EUB = CombEUB.get();
6613 Built.DistCombinedFields.Init = CombInit.get();
6614 Built.DistCombinedFields.Cond = CombCond.get();
6615 Built.DistCombinedFields.NLB = CombNextLB.get();
6616 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006617 Built.DistCombinedFields.DistCond = CombDistCond.get();
6618 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006619
Alexey Bataevabfc0692014-06-25 06:52:00 +00006620 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006621}
6622
Alexey Bataev10e775f2015-07-30 11:36:16 +00006623static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006624 auto CollapseClauses =
6625 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6626 if (CollapseClauses.begin() != CollapseClauses.end())
6627 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006628 return nullptr;
6629}
6630
Alexey Bataev10e775f2015-07-30 11:36:16 +00006631static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006632 auto OrderedClauses =
6633 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6634 if (OrderedClauses.begin() != OrderedClauses.end())
6635 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006636 return nullptr;
6637}
6638
Kelvin Lic5609492016-07-15 04:39:07 +00006639static bool checkSimdlenSafelenSpecified(Sema &S,
6640 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006641 const OMPSafelenClause *Safelen = nullptr;
6642 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006643
Alexey Bataeve3727102018-04-18 15:57:46 +00006644 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006645 if (Clause->getClauseKind() == OMPC_safelen)
6646 Safelen = cast<OMPSafelenClause>(Clause);
6647 else if (Clause->getClauseKind() == OMPC_simdlen)
6648 Simdlen = cast<OMPSimdlenClause>(Clause);
6649 if (Safelen && Simdlen)
6650 break;
6651 }
6652
6653 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006654 const Expr *SimdlenLength = Simdlen->getSimdlen();
6655 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006656 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6657 SimdlenLength->isInstantiationDependent() ||
6658 SimdlenLength->containsUnexpandedParameterPack())
6659 return false;
6660 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6661 SafelenLength->isInstantiationDependent() ||
6662 SafelenLength->containsUnexpandedParameterPack())
6663 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006664 Expr::EvalResult SimdlenResult, SafelenResult;
6665 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6666 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6667 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6668 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006669 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6670 // If both simdlen and safelen clauses are specified, the value of the
6671 // simdlen parameter must be less than or equal to the value of the safelen
6672 // parameter.
6673 if (SimdlenRes > SafelenRes) {
6674 S.Diag(SimdlenLength->getExprLoc(),
6675 diag::err_omp_wrong_simdlen_safelen_values)
6676 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6677 return true;
6678 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006679 }
6680 return false;
6681}
6682
Alexey Bataeve3727102018-04-18 15:57:46 +00006683StmtResult
6684Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6685 SourceLocation StartLoc, SourceLocation EndLoc,
6686 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006687 if (!AStmt)
6688 return StmtError();
6689
6690 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006691 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006692 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6693 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006694 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006695 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6696 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006697 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006698 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006699
Alexander Musmana5f070a2014-10-01 06:03:56 +00006700 assert((CurContext->isDependentContext() || B.builtAll()) &&
6701 "omp simd loop exprs were not built");
6702
Alexander Musman3276a272015-03-21 10:12:56 +00006703 if (!CurContext->isDependentContext()) {
6704 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006705 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006706 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006707 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006708 B.NumIterations, *this, CurScope,
6709 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006710 return StmtError();
6711 }
6712 }
6713
Kelvin Lic5609492016-07-15 04:39:07 +00006714 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006715 return StmtError();
6716
Reid Kleckner87a31802018-03-12 21:43:02 +00006717 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006718 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6719 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006720}
6721
Alexey Bataeve3727102018-04-18 15:57:46 +00006722StmtResult
6723Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6724 SourceLocation StartLoc, SourceLocation EndLoc,
6725 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006726 if (!AStmt)
6727 return StmtError();
6728
6729 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006730 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006731 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6732 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006733 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006734 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6735 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006736 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006737 return StmtError();
6738
Alexander Musmana5f070a2014-10-01 06:03:56 +00006739 assert((CurContext->isDependentContext() || B.builtAll()) &&
6740 "omp for loop exprs were not built");
6741
Alexey Bataev54acd402015-08-04 11:18:19 +00006742 if (!CurContext->isDependentContext()) {
6743 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006744 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006745 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006746 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006747 B.NumIterations, *this, CurScope,
6748 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006749 return StmtError();
6750 }
6751 }
6752
Reid Kleckner87a31802018-03-12 21:43:02 +00006753 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006754 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006755 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006756}
6757
Alexander Musmanf82886e2014-09-18 05:12:34 +00006758StmtResult Sema::ActOnOpenMPForSimdDirective(
6759 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006760 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006761 if (!AStmt)
6762 return StmtError();
6763
6764 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006765 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006766 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6767 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006768 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006769 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006770 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6771 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006772 if (NestedLoopCount == 0)
6773 return StmtError();
6774
Alexander Musmanc6388682014-12-15 07:07:06 +00006775 assert((CurContext->isDependentContext() || B.builtAll()) &&
6776 "omp for simd loop exprs were not built");
6777
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006778 if (!CurContext->isDependentContext()) {
6779 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006780 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006781 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006782 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006783 B.NumIterations, *this, CurScope,
6784 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006785 return StmtError();
6786 }
6787 }
6788
Kelvin Lic5609492016-07-15 04:39:07 +00006789 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006790 return StmtError();
6791
Reid Kleckner87a31802018-03-12 21:43:02 +00006792 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006793 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6794 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006795}
6796
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006797StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6798 Stmt *AStmt,
6799 SourceLocation StartLoc,
6800 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006801 if (!AStmt)
6802 return StmtError();
6803
6804 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006805 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006806 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006807 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006808 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006809 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006810 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006811 return StmtError();
6812 // All associated statements must be '#pragma omp section' except for
6813 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006814 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006815 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6816 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006817 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006818 diag::err_omp_sections_substmt_not_section);
6819 return StmtError();
6820 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006821 cast<OMPSectionDirective>(SectionStmt)
6822 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006823 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006824 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006825 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006826 return StmtError();
6827 }
6828
Reid Kleckner87a31802018-03-12 21:43:02 +00006829 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006830
Alexey Bataev25e5b442015-09-15 12:52:43 +00006831 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6832 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006833}
6834
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006835StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6836 SourceLocation StartLoc,
6837 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006838 if (!AStmt)
6839 return StmtError();
6840
6841 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006842
Reid Kleckner87a31802018-03-12 21:43:02 +00006843 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006844 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006845
Alexey Bataev25e5b442015-09-15 12:52:43 +00006846 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6847 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006848}
6849
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006850StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6851 Stmt *AStmt,
6852 SourceLocation StartLoc,
6853 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006854 if (!AStmt)
6855 return StmtError();
6856
6857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006858
Reid Kleckner87a31802018-03-12 21:43:02 +00006859 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006860
Alexey Bataev3255bf32015-01-19 05:20:46 +00006861 // OpenMP [2.7.3, single Construct, Restrictions]
6862 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006863 const OMPClause *Nowait = nullptr;
6864 const OMPClause *Copyprivate = nullptr;
6865 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006866 if (Clause->getClauseKind() == OMPC_nowait)
6867 Nowait = Clause;
6868 else if (Clause->getClauseKind() == OMPC_copyprivate)
6869 Copyprivate = Clause;
6870 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006871 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006872 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006873 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006874 return StmtError();
6875 }
6876 }
6877
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006878 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6879}
6880
Alexander Musman80c22892014-07-17 08:54:58 +00006881StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6882 SourceLocation StartLoc,
6883 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006884 if (!AStmt)
6885 return StmtError();
6886
6887 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006888
Reid Kleckner87a31802018-03-12 21:43:02 +00006889 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006890
6891 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6892}
6893
Alexey Bataev28c75412015-12-15 08:19:24 +00006894StmtResult Sema::ActOnOpenMPCriticalDirective(
6895 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6896 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006897 if (!AStmt)
6898 return StmtError();
6899
6900 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006901
Alexey Bataev28c75412015-12-15 08:19:24 +00006902 bool ErrorFound = false;
6903 llvm::APSInt Hint;
6904 SourceLocation HintLoc;
6905 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006906 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006907 if (C->getClauseKind() == OMPC_hint) {
6908 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006909 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006910 ErrorFound = true;
6911 }
6912 Expr *E = cast<OMPHintClause>(C)->getHint();
6913 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006914 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006915 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006916 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006917 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006918 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006919 }
6920 }
6921 }
6922 if (ErrorFound)
6923 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006924 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006925 if (Pair.first && DirName.getName() && !DependentHint) {
6926 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6927 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006928 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006929 Diag(HintLoc, diag::note_omp_critical_hint_here)
6930 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006931 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006932 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006933 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006934 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006935 << 1
6936 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6937 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006938 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006939 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006940 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006941 }
6942 }
6943
Reid Kleckner87a31802018-03-12 21:43:02 +00006944 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006945
Alexey Bataev28c75412015-12-15 08:19:24 +00006946 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6947 Clauses, AStmt);
6948 if (!Pair.first && DirName.getName() && !DependentHint)
6949 DSAStack->addCriticalWithHint(Dir, Hint);
6950 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006951}
6952
Alexey Bataev4acb8592014-07-07 13:01:15 +00006953StmtResult Sema::ActOnOpenMPParallelForDirective(
6954 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006955 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006956 if (!AStmt)
6957 return StmtError();
6958
Alexey Bataeve3727102018-04-18 15:57:46 +00006959 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006960 // 1.2.2 OpenMP Language Terminology
6961 // Structured block - An executable statement with a single entry at the
6962 // top and a single exit at the bottom.
6963 // The point of exit cannot be a branch out of the structured block.
6964 // longjmp() and throw() must not violate the entry/exit criteria.
6965 CS->getCapturedDecl()->setNothrow();
6966
Alexander Musmanc6388682014-12-15 07:07:06 +00006967 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006968 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6969 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006970 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006971 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006972 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6973 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006974 if (NestedLoopCount == 0)
6975 return StmtError();
6976
Alexander Musmana5f070a2014-10-01 06:03:56 +00006977 assert((CurContext->isDependentContext() || B.builtAll()) &&
6978 "omp parallel for loop exprs were not built");
6979
Alexey Bataev54acd402015-08-04 11:18:19 +00006980 if (!CurContext->isDependentContext()) {
6981 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006982 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006983 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006984 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006985 B.NumIterations, *this, CurScope,
6986 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006987 return StmtError();
6988 }
6989 }
6990
Reid Kleckner87a31802018-03-12 21:43:02 +00006991 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006992 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006993 NestedLoopCount, Clauses, AStmt, B,
6994 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006995}
6996
Alexander Musmane4e893b2014-09-23 09:33:00 +00006997StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006999 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007000 if (!AStmt)
7001 return StmtError();
7002
Alexey Bataeve3727102018-04-18 15:57:46 +00007003 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007004 // 1.2.2 OpenMP Language Terminology
7005 // Structured block - An executable statement with a single entry at the
7006 // top and a single exit at the bottom.
7007 // The point of exit cannot be a branch out of the structured block.
7008 // longjmp() and throw() must not violate the entry/exit criteria.
7009 CS->getCapturedDecl()->setNothrow();
7010
Alexander Musmanc6388682014-12-15 07:07:06 +00007011 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007012 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7013 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007014 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007015 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007016 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7017 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007018 if (NestedLoopCount == 0)
7019 return StmtError();
7020
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007021 if (!CurContext->isDependentContext()) {
7022 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007023 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007024 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007025 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007026 B.NumIterations, *this, CurScope,
7027 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007028 return StmtError();
7029 }
7030 }
7031
Kelvin Lic5609492016-07-15 04:39:07 +00007032 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007033 return StmtError();
7034
Reid Kleckner87a31802018-03-12 21:43:02 +00007035 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007036 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007037 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007038}
7039
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007040StmtResult
7041Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7042 Stmt *AStmt, SourceLocation StartLoc,
7043 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007044 if (!AStmt)
7045 return StmtError();
7046
7047 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007048 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007049 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007050 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007051 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007052 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007053 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007054 return StmtError();
7055 // All associated statements must be '#pragma omp section' except for
7056 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007057 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007058 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7059 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007060 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007061 diag::err_omp_parallel_sections_substmt_not_section);
7062 return StmtError();
7063 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007064 cast<OMPSectionDirective>(SectionStmt)
7065 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007066 }
7067 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007068 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007069 diag::err_omp_parallel_sections_not_compound_stmt);
7070 return StmtError();
7071 }
7072
Reid Kleckner87a31802018-03-12 21:43:02 +00007073 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007074
Alexey Bataev25e5b442015-09-15 12:52:43 +00007075 return OMPParallelSectionsDirective::Create(
7076 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007077}
7078
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007079StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7080 Stmt *AStmt, SourceLocation StartLoc,
7081 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007082 if (!AStmt)
7083 return StmtError();
7084
David Majnemer9d168222016-08-05 17:44:54 +00007085 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007086 // 1.2.2 OpenMP Language Terminology
7087 // Structured block - An executable statement with a single entry at the
7088 // top and a single exit at the bottom.
7089 // The point of exit cannot be a branch out of the structured block.
7090 // longjmp() and throw() must not violate the entry/exit criteria.
7091 CS->getCapturedDecl()->setNothrow();
7092
Reid Kleckner87a31802018-03-12 21:43:02 +00007093 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007094
Alexey Bataev25e5b442015-09-15 12:52:43 +00007095 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7096 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007097}
7098
Alexey Bataev68446b72014-07-18 07:47:19 +00007099StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7100 SourceLocation EndLoc) {
7101 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
7102}
7103
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00007104StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7105 SourceLocation EndLoc) {
7106 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
7107}
7108
Alexey Bataev2df347a2014-07-18 10:17:07 +00007109StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7110 SourceLocation EndLoc) {
7111 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
7112}
7113
Alexey Bataev169d96a2017-07-18 20:17:46 +00007114StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
7115 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007116 SourceLocation StartLoc,
7117 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007118 if (!AStmt)
7119 return StmtError();
7120
7121 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007122
Reid Kleckner87a31802018-03-12 21:43:02 +00007123 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007124
Alexey Bataev169d96a2017-07-18 20:17:46 +00007125 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00007126 AStmt,
7127 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007128}
7129
Alexey Bataev6125da92014-07-21 11:26:11 +00007130StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7131 SourceLocation StartLoc,
7132 SourceLocation EndLoc) {
7133 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
7134 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
7135}
7136
Alexey Bataev346265e2015-09-25 10:37:12 +00007137StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7138 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007139 SourceLocation StartLoc,
7140 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007141 const OMPClause *DependFound = nullptr;
7142 const OMPClause *DependSourceClause = nullptr;
7143 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00007144 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007145 const OMPThreadsClause *TC = nullptr;
7146 const OMPSIMDClause *SC = nullptr;
7147 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00007148 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
7149 DependFound = C;
7150 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
7151 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007152 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00007153 << getOpenMPDirectiveName(OMPD_ordered)
7154 << getOpenMPClauseName(OMPC_depend) << 2;
7155 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007156 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00007157 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00007158 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007159 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007160 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007161 << 0;
7162 ErrorFound = true;
7163 }
7164 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
7165 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007166 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007167 << 1;
7168 ErrorFound = true;
7169 }
7170 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00007171 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007172 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00007173 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007174 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007175 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007176 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007177 }
Alexey Bataeveb482352015-12-18 05:05:56 +00007178 if (!ErrorFound && !SC &&
7179 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007180 // OpenMP [2.8.1,simd Construct, Restrictions]
7181 // An ordered construct with the simd clause is the only OpenMP construct
7182 // that can appear in the simd region.
7183 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00007184 ErrorFound = true;
7185 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007186 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00007187 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
7188 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007189 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007190 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00007191 diag::err_omp_ordered_directive_without_param);
7192 ErrorFound = true;
7193 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007194 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007195 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00007196 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
7197 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007198 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00007199 ErrorFound = true;
7200 }
7201 }
7202 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007203 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00007204
7205 if (AStmt) {
7206 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7207
Reid Kleckner87a31802018-03-12 21:43:02 +00007208 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007209 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007210
7211 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007212}
7213
Alexey Bataev1d160b12015-03-13 12:27:31 +00007214namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007215/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007216/// construct.
7217class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007218 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007219 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007220 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007221 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007222 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007223 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007224 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007225 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007226 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007227 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007228 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007229 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007230 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007231 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007232 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00007233 /// expression.
7234 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007235 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00007236 /// part.
7237 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007238 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007239 NoError
7240 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007241 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007242 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007243 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00007244 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007245 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007246 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007247 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007248 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007249 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00007250 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7251 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7252 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007253 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00007254 /// important for non-associative operations.
7255 bool IsXLHSInRHSPart;
7256 BinaryOperatorKind Op;
7257 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007258 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007259 /// if it is a prefix unary operation.
7260 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007261
7262public:
7263 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00007264 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00007265 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007266 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007267 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00007268 /// expression. If DiagId and NoteId == 0, then only check is performed
7269 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007270 /// \param DiagId Diagnostic which should be emitted if error is found.
7271 /// \param NoteId Diagnostic note for the main error message.
7272 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00007273 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007274 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007275 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007276 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007277 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007278 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00007279 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7280 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7281 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007282 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00007283 /// false otherwise.
7284 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
7285
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007286 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007287 /// if it is a prefix unary operation.
7288 bool isPostfixUpdate() const { return IsPostfixUpdate; }
7289
Alexey Bataev1d160b12015-03-13 12:27:31 +00007290private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00007291 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
7292 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00007293};
7294} // namespace
7295
7296bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
7297 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
7298 ExprAnalysisErrorCode ErrorFound = NoError;
7299 SourceLocation ErrorLoc, NoteLoc;
7300 SourceRange ErrorRange, NoteRange;
7301 // Allowed constructs are:
7302 // x = x binop expr;
7303 // x = expr binop x;
7304 if (AtomicBinOp->getOpcode() == BO_Assign) {
7305 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00007306 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007307 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
7308 if (AtomicInnerBinOp->isMultiplicativeOp() ||
7309 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
7310 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007311 Op = AtomicInnerBinOp->getOpcode();
7312 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00007313 Expr *LHS = AtomicInnerBinOp->getLHS();
7314 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007315 llvm::FoldingSetNodeID XId, LHSId, RHSId;
7316 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
7317 /*Canonical=*/true);
7318 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
7319 /*Canonical=*/true);
7320 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
7321 /*Canonical=*/true);
7322 if (XId == LHSId) {
7323 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007324 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007325 } else if (XId == RHSId) {
7326 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007327 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007328 } else {
7329 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7330 ErrorRange = AtomicInnerBinOp->getSourceRange();
7331 NoteLoc = X->getExprLoc();
7332 NoteRange = X->getSourceRange();
7333 ErrorFound = NotAnUpdateExpression;
7334 }
7335 } else {
7336 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7337 ErrorRange = AtomicInnerBinOp->getSourceRange();
7338 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
7339 NoteRange = SourceRange(NoteLoc, NoteLoc);
7340 ErrorFound = NotABinaryOperator;
7341 }
7342 } else {
7343 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
7344 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
7345 ErrorFound = NotABinaryExpression;
7346 }
7347 } else {
7348 ErrorLoc = AtomicBinOp->getExprLoc();
7349 ErrorRange = AtomicBinOp->getSourceRange();
7350 NoteLoc = AtomicBinOp->getOperatorLoc();
7351 NoteRange = SourceRange(NoteLoc, NoteLoc);
7352 ErrorFound = NotAnAssignmentOp;
7353 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007354 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007355 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7356 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7357 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007358 }
7359 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007360 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007361 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007362}
7363
7364bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
7365 unsigned NoteId) {
7366 ExprAnalysisErrorCode ErrorFound = NoError;
7367 SourceLocation ErrorLoc, NoteLoc;
7368 SourceRange ErrorRange, NoteRange;
7369 // Allowed constructs are:
7370 // x++;
7371 // x--;
7372 // ++x;
7373 // --x;
7374 // x binop= expr;
7375 // x = x binop expr;
7376 // x = expr binop x;
7377 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
7378 AtomicBody = AtomicBody->IgnoreParenImpCasts();
7379 if (AtomicBody->getType()->isScalarType() ||
7380 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007381 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007382 AtomicBody->IgnoreParenImpCasts())) {
7383 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00007384 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007385 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00007386 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007387 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007388 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007389 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007390 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
7391 AtomicBody->IgnoreParenImpCasts())) {
7392 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00007393 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00007394 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007395 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00007396 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007397 // Check for Unary Operation
7398 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007399 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007400 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
7401 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007402 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007403 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
7404 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007405 } else {
7406 ErrorFound = NotAnUnaryIncDecExpression;
7407 ErrorLoc = AtomicUnaryOp->getExprLoc();
7408 ErrorRange = AtomicUnaryOp->getSourceRange();
7409 NoteLoc = AtomicUnaryOp->getOperatorLoc();
7410 NoteRange = SourceRange(NoteLoc, NoteLoc);
7411 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007412 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007413 ErrorFound = NotABinaryOrUnaryExpression;
7414 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
7415 NoteRange = ErrorRange = AtomicBody->getSourceRange();
7416 }
7417 } else {
7418 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007419 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007420 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7421 }
7422 } else {
7423 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007424 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007425 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7426 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007427 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007428 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7429 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7430 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007431 }
7432 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007433 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007434 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007435 // Build an update expression of form 'OpaqueValueExpr(x) binop
7436 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
7437 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
7438 auto *OVEX = new (SemaRef.getASTContext())
7439 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
7440 auto *OVEExpr = new (SemaRef.getASTContext())
7441 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00007442 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00007443 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
7444 IsXLHSInRHSPart ? OVEExpr : OVEX);
7445 if (Update.isInvalid())
7446 return true;
7447 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
7448 Sema::AA_Casting);
7449 if (Update.isInvalid())
7450 return true;
7451 UpdateExpr = Update.get();
7452 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00007453 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007454}
7455
Alexey Bataev0162e452014-07-22 10:10:35 +00007456StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7457 Stmt *AStmt,
7458 SourceLocation StartLoc,
7459 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007460 if (!AStmt)
7461 return StmtError();
7462
David Majnemer9d168222016-08-05 17:44:54 +00007463 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00007464 // 1.2.2 OpenMP Language Terminology
7465 // Structured block - An executable statement with a single entry at the
7466 // top and a single exit at the bottom.
7467 // The point of exit cannot be a branch out of the structured block.
7468 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00007469 OpenMPClauseKind AtomicKind = OMPC_unknown;
7470 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00007471 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00007472 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00007473 C->getClauseKind() == OMPC_update ||
7474 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00007475 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007476 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007477 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00007478 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
7479 << getOpenMPClauseName(AtomicKind);
7480 } else {
7481 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007482 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007483 }
7484 }
7485 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007486
Alexey Bataeve3727102018-04-18 15:57:46 +00007487 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00007488 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
7489 Body = EWC->getSubExpr();
7490
Alexey Bataev62cec442014-11-18 10:14:22 +00007491 Expr *X = nullptr;
7492 Expr *V = nullptr;
7493 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007494 Expr *UE = nullptr;
7495 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007496 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00007497 // OpenMP [2.12.6, atomic Construct]
7498 // In the next expressions:
7499 // * x and v (as applicable) are both l-value expressions with scalar type.
7500 // * During the execution of an atomic region, multiple syntactic
7501 // occurrences of x must designate the same storage location.
7502 // * Neither of v and expr (as applicable) may access the storage location
7503 // designated by x.
7504 // * Neither of x and expr (as applicable) may access the storage location
7505 // designated by v.
7506 // * expr is an expression with scalar type.
7507 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
7508 // * binop, binop=, ++, and -- are not overloaded operators.
7509 // * The expression x binop expr must be numerically equivalent to x binop
7510 // (expr). This requirement is satisfied if the operators in expr have
7511 // precedence greater than binop, or by using parentheses around expr or
7512 // subexpressions of expr.
7513 // * The expression expr binop x must be numerically equivalent to (expr)
7514 // binop x. This requirement is satisfied if the operators in expr have
7515 // precedence equal to or greater than binop, or by using parentheses around
7516 // expr or subexpressions of expr.
7517 // * For forms that allow multiple occurrences of x, the number of times
7518 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00007519 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007520 enum {
7521 NotAnExpression,
7522 NotAnAssignmentOp,
7523 NotAScalarType,
7524 NotAnLValue,
7525 NoError
7526 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00007527 SourceLocation ErrorLoc, NoteLoc;
7528 SourceRange ErrorRange, NoteRange;
7529 // If clause is read:
7530 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007531 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7532 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00007533 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7534 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7535 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7536 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
7537 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7538 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
7539 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007540 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00007541 ErrorFound = NotAnLValue;
7542 ErrorLoc = AtomicBinOp->getExprLoc();
7543 ErrorRange = AtomicBinOp->getSourceRange();
7544 NoteLoc = NotLValueExpr->getExprLoc();
7545 NoteRange = NotLValueExpr->getSourceRange();
7546 }
7547 } else if (!X->isInstantiationDependent() ||
7548 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007549 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00007550 (X->isInstantiationDependent() || X->getType()->isScalarType())
7551 ? V
7552 : X;
7553 ErrorFound = NotAScalarType;
7554 ErrorLoc = AtomicBinOp->getExprLoc();
7555 ErrorRange = AtomicBinOp->getSourceRange();
7556 NoteLoc = NotScalarExpr->getExprLoc();
7557 NoteRange = NotScalarExpr->getSourceRange();
7558 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007559 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00007560 ErrorFound = NotAnAssignmentOp;
7561 ErrorLoc = AtomicBody->getExprLoc();
7562 ErrorRange = AtomicBody->getSourceRange();
7563 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7564 : AtomicBody->getExprLoc();
7565 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7566 : AtomicBody->getSourceRange();
7567 }
7568 } else {
7569 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007570 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007571 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007572 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007573 if (ErrorFound != NoError) {
7574 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7575 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007576 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7577 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007578 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007579 }
7580 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007581 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007582 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007583 enum {
7584 NotAnExpression,
7585 NotAnAssignmentOp,
7586 NotAScalarType,
7587 NotAnLValue,
7588 NoError
7589 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007590 SourceLocation ErrorLoc, NoteLoc;
7591 SourceRange ErrorRange, NoteRange;
7592 // If clause is write:
7593 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007594 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7595 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007596 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7597 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007598 X = AtomicBinOp->getLHS();
7599 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007600 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7601 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7602 if (!X->isLValue()) {
7603 ErrorFound = NotAnLValue;
7604 ErrorLoc = AtomicBinOp->getExprLoc();
7605 ErrorRange = AtomicBinOp->getSourceRange();
7606 NoteLoc = X->getExprLoc();
7607 NoteRange = X->getSourceRange();
7608 }
7609 } else if (!X->isInstantiationDependent() ||
7610 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007611 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007612 (X->isInstantiationDependent() || X->getType()->isScalarType())
7613 ? E
7614 : X;
7615 ErrorFound = NotAScalarType;
7616 ErrorLoc = AtomicBinOp->getExprLoc();
7617 ErrorRange = AtomicBinOp->getSourceRange();
7618 NoteLoc = NotScalarExpr->getExprLoc();
7619 NoteRange = NotScalarExpr->getSourceRange();
7620 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007621 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007622 ErrorFound = NotAnAssignmentOp;
7623 ErrorLoc = AtomicBody->getExprLoc();
7624 ErrorRange = AtomicBody->getSourceRange();
7625 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7626 : AtomicBody->getExprLoc();
7627 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7628 : AtomicBody->getSourceRange();
7629 }
7630 } else {
7631 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007632 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007633 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007634 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007635 if (ErrorFound != NoError) {
7636 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7637 << ErrorRange;
7638 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7639 << NoteRange;
7640 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007641 }
7642 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007643 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007644 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007645 // If clause is update:
7646 // x++;
7647 // x--;
7648 // ++x;
7649 // --x;
7650 // x binop= expr;
7651 // x = x binop expr;
7652 // x = expr binop x;
7653 OpenMPAtomicUpdateChecker Checker(*this);
7654 if (Checker.checkStatement(
7655 Body, (AtomicKind == OMPC_update)
7656 ? diag::err_omp_atomic_update_not_expression_statement
7657 : diag::err_omp_atomic_not_expression_statement,
7658 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007659 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007660 if (!CurContext->isDependentContext()) {
7661 E = Checker.getExpr();
7662 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007663 UE = Checker.getUpdateExpr();
7664 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007665 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007666 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007667 enum {
7668 NotAnAssignmentOp,
7669 NotACompoundStatement,
7670 NotTwoSubstatements,
7671 NotASpecificExpression,
7672 NoError
7673 } ErrorFound = NoError;
7674 SourceLocation ErrorLoc, NoteLoc;
7675 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007676 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007677 // If clause is a capture:
7678 // v = x++;
7679 // v = x--;
7680 // v = ++x;
7681 // v = --x;
7682 // v = x binop= expr;
7683 // v = x = x binop expr;
7684 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007685 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007686 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7687 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7688 V = AtomicBinOp->getLHS();
7689 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7690 OpenMPAtomicUpdateChecker Checker(*this);
7691 if (Checker.checkStatement(
7692 Body, diag::err_omp_atomic_capture_not_expression_statement,
7693 diag::note_omp_atomic_update))
7694 return StmtError();
7695 E = Checker.getExpr();
7696 X = Checker.getX();
7697 UE = Checker.getUpdateExpr();
7698 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7699 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007700 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007701 ErrorLoc = AtomicBody->getExprLoc();
7702 ErrorRange = AtomicBody->getSourceRange();
7703 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7704 : AtomicBody->getExprLoc();
7705 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7706 : AtomicBody->getSourceRange();
7707 ErrorFound = NotAnAssignmentOp;
7708 }
7709 if (ErrorFound != NoError) {
7710 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7711 << ErrorRange;
7712 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7713 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007714 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007715 if (CurContext->isDependentContext())
7716 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007717 } else {
7718 // If clause is a capture:
7719 // { v = x; x = expr; }
7720 // { v = x; x++; }
7721 // { v = x; x--; }
7722 // { v = x; ++x; }
7723 // { v = x; --x; }
7724 // { v = x; x binop= expr; }
7725 // { v = x; x = x binop expr; }
7726 // { v = x; x = expr binop x; }
7727 // { x++; v = x; }
7728 // { x--; v = x; }
7729 // { ++x; v = x; }
7730 // { --x; v = x; }
7731 // { x binop= expr; v = x; }
7732 // { x = x binop expr; v = x; }
7733 // { x = expr binop x; v = x; }
7734 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7735 // Check that this is { expr1; expr2; }
7736 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007737 Stmt *First = CS->body_front();
7738 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007739 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7740 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7741 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7742 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7743 // Need to find what subexpression is 'v' and what is 'x'.
7744 OpenMPAtomicUpdateChecker Checker(*this);
7745 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7746 BinaryOperator *BinOp = nullptr;
7747 if (IsUpdateExprFound) {
7748 BinOp = dyn_cast<BinaryOperator>(First);
7749 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7750 }
7751 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7752 // { v = x; x++; }
7753 // { v = x; x--; }
7754 // { v = x; ++x; }
7755 // { v = x; --x; }
7756 // { v = x; x binop= expr; }
7757 // { v = x; x = x binop expr; }
7758 // { v = x; x = expr binop x; }
7759 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007760 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007761 llvm::FoldingSetNodeID XId, PossibleXId;
7762 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7763 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7764 IsUpdateExprFound = XId == PossibleXId;
7765 if (IsUpdateExprFound) {
7766 V = BinOp->getLHS();
7767 X = Checker.getX();
7768 E = Checker.getExpr();
7769 UE = Checker.getUpdateExpr();
7770 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007771 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007772 }
7773 }
7774 if (!IsUpdateExprFound) {
7775 IsUpdateExprFound = !Checker.checkStatement(First);
7776 BinOp = nullptr;
7777 if (IsUpdateExprFound) {
7778 BinOp = dyn_cast<BinaryOperator>(Second);
7779 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7780 }
7781 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7782 // { x++; v = x; }
7783 // { x--; v = x; }
7784 // { ++x; v = x; }
7785 // { --x; v = x; }
7786 // { x binop= expr; v = x; }
7787 // { x = x binop expr; v = x; }
7788 // { x = expr binop x; v = x; }
7789 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007790 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007791 llvm::FoldingSetNodeID XId, PossibleXId;
7792 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7793 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7794 IsUpdateExprFound = XId == PossibleXId;
7795 if (IsUpdateExprFound) {
7796 V = BinOp->getLHS();
7797 X = Checker.getX();
7798 E = Checker.getExpr();
7799 UE = Checker.getUpdateExpr();
7800 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007801 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007802 }
7803 }
7804 }
7805 if (!IsUpdateExprFound) {
7806 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007807 auto *FirstExpr = dyn_cast<Expr>(First);
7808 auto *SecondExpr = dyn_cast<Expr>(Second);
7809 if (!FirstExpr || !SecondExpr ||
7810 !(FirstExpr->isInstantiationDependent() ||
7811 SecondExpr->isInstantiationDependent())) {
7812 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7813 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007814 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007815 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007816 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007817 NoteRange = ErrorRange = FirstBinOp
7818 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007819 : SourceRange(ErrorLoc, ErrorLoc);
7820 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007821 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7822 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7823 ErrorFound = NotAnAssignmentOp;
7824 NoteLoc = ErrorLoc = SecondBinOp
7825 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007826 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007827 NoteRange = ErrorRange =
7828 SecondBinOp ? SecondBinOp->getSourceRange()
7829 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007830 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007831 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007832 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007833 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007834 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7835 llvm::FoldingSetNodeID X1Id, X2Id;
7836 PossibleXRHSInFirst->Profile(X1Id, Context,
7837 /*Canonical=*/true);
7838 PossibleXLHSInSecond->Profile(X2Id, Context,
7839 /*Canonical=*/true);
7840 IsUpdateExprFound = X1Id == X2Id;
7841 if (IsUpdateExprFound) {
7842 V = FirstBinOp->getLHS();
7843 X = SecondBinOp->getLHS();
7844 E = SecondBinOp->getRHS();
7845 UE = nullptr;
7846 IsXLHSInRHSPart = false;
7847 IsPostfixUpdate = true;
7848 } else {
7849 ErrorFound = NotASpecificExpression;
7850 ErrorLoc = FirstBinOp->getExprLoc();
7851 ErrorRange = FirstBinOp->getSourceRange();
7852 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7853 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7854 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007855 }
7856 }
7857 }
7858 }
7859 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007860 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007861 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007862 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007863 ErrorFound = NotTwoSubstatements;
7864 }
7865 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007866 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007867 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007868 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007869 ErrorFound = NotACompoundStatement;
7870 }
7871 if (ErrorFound != NoError) {
7872 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7873 << ErrorRange;
7874 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7875 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007876 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007877 if (CurContext->isDependentContext())
7878 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007879 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007880 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007881
Reid Kleckner87a31802018-03-12 21:43:02 +00007882 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007883
Alexey Bataev62cec442014-11-18 10:14:22 +00007884 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007885 X, V, E, UE, IsXLHSInRHSPart,
7886 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007887}
7888
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007889StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7890 Stmt *AStmt,
7891 SourceLocation StartLoc,
7892 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007893 if (!AStmt)
7894 return StmtError();
7895
Alexey Bataeve3727102018-04-18 15:57:46 +00007896 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007897 // 1.2.2 OpenMP Language Terminology
7898 // Structured block - An executable statement with a single entry at the
7899 // top and a single exit at the bottom.
7900 // The point of exit cannot be a branch out of the structured block.
7901 // longjmp() and throw() must not violate the entry/exit criteria.
7902 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007903 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7904 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7905 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7906 // 1.2.2 OpenMP Language Terminology
7907 // Structured block - An executable statement with a single entry at the
7908 // top and a single exit at the bottom.
7909 // The point of exit cannot be a branch out of the structured block.
7910 // longjmp() and throw() must not violate the entry/exit criteria.
7911 CS->getCapturedDecl()->setNothrow();
7912 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007913
Alexey Bataev13314bf2014-10-09 04:18:56 +00007914 // OpenMP [2.16, Nesting of Regions]
7915 // If specified, a teams construct must be contained within a target
7916 // construct. That target construct must contain no statements or directives
7917 // outside of the teams construct.
7918 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007919 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007920 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007921 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007922 auto I = CS->body_begin();
7923 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007924 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007925 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7926 OMPTeamsFound) {
7927
Alexey Bataev13314bf2014-10-09 04:18:56 +00007928 OMPTeamsFound = false;
7929 break;
7930 }
7931 ++I;
7932 }
7933 assert(I != CS->body_end() && "Not found statement");
7934 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007935 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007936 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007937 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007938 }
7939 if (!OMPTeamsFound) {
7940 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7941 Diag(DSAStack->getInnerTeamsRegionLoc(),
7942 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007943 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007944 << isa<OMPExecutableDirective>(S);
7945 return StmtError();
7946 }
7947 }
7948
Reid Kleckner87a31802018-03-12 21:43:02 +00007949 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007950
7951 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7952}
7953
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007954StmtResult
7955Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7956 Stmt *AStmt, SourceLocation StartLoc,
7957 SourceLocation EndLoc) {
7958 if (!AStmt)
7959 return StmtError();
7960
Alexey Bataeve3727102018-04-18 15:57:46 +00007961 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007962 // 1.2.2 OpenMP Language Terminology
7963 // Structured block - An executable statement with a single entry at the
7964 // top and a single exit at the bottom.
7965 // The point of exit cannot be a branch out of the structured block.
7966 // longjmp() and throw() must not violate the entry/exit criteria.
7967 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007968 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7969 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7970 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7971 // 1.2.2 OpenMP Language Terminology
7972 // Structured block - An executable statement with a single entry at the
7973 // top and a single exit at the bottom.
7974 // The point of exit cannot be a branch out of the structured block.
7975 // longjmp() and throw() must not violate the entry/exit criteria.
7976 CS->getCapturedDecl()->setNothrow();
7977 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007978
Reid Kleckner87a31802018-03-12 21:43:02 +00007979 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007980
7981 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7982 AStmt);
7983}
7984
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007985StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7986 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007987 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007988 if (!AStmt)
7989 return StmtError();
7990
Alexey Bataeve3727102018-04-18 15:57:46 +00007991 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007992 // 1.2.2 OpenMP Language Terminology
7993 // Structured block - An executable statement with a single entry at the
7994 // top and a single exit at the bottom.
7995 // The point of exit cannot be a branch out of the structured block.
7996 // longjmp() and throw() must not violate the entry/exit criteria.
7997 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007998 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7999 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8000 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8001 // 1.2.2 OpenMP Language Terminology
8002 // Structured block - An executable statement with a single entry at the
8003 // top and a single exit at the bottom.
8004 // The point of exit cannot be a branch out of the structured block.
8005 // longjmp() and throw() must not violate the entry/exit criteria.
8006 CS->getCapturedDecl()->setNothrow();
8007 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008008
8009 OMPLoopDirective::HelperExprs B;
8010 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8011 // define the nested loops number.
8012 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008013 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008014 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008015 VarsWithImplicitDSA, B);
8016 if (NestedLoopCount == 0)
8017 return StmtError();
8018
8019 assert((CurContext->isDependentContext() || B.builtAll()) &&
8020 "omp target parallel for loop exprs were not built");
8021
8022 if (!CurContext->isDependentContext()) {
8023 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008024 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008025 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008026 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008027 B.NumIterations, *this, CurScope,
8028 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008029 return StmtError();
8030 }
8031 }
8032
Reid Kleckner87a31802018-03-12 21:43:02 +00008033 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008034 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8035 NestedLoopCount, Clauses, AStmt,
8036 B, DSAStack->isCancelRegion());
8037}
8038
Alexey Bataev95b64a92017-05-30 16:00:04 +00008039/// Check for existence of a map clause in the list of clauses.
8040static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8041 const OpenMPClauseKind K) {
8042 return llvm::any_of(
8043 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8044}
Samuel Antaodf67fc42016-01-19 19:15:56 +00008045
Alexey Bataev95b64a92017-05-30 16:00:04 +00008046template <typename... Params>
8047static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
8048 const Params... ClauseTypes) {
8049 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008050}
8051
Michael Wong65f367f2015-07-21 13:44:28 +00008052StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8053 Stmt *AStmt,
8054 SourceLocation StartLoc,
8055 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008056 if (!AStmt)
8057 return StmtError();
8058
8059 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8060
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008061 // OpenMP [2.10.1, Restrictions, p. 97]
8062 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008063 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
8064 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8065 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00008066 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008067 return StmtError();
8068 }
8069
Reid Kleckner87a31802018-03-12 21:43:02 +00008070 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00008071
8072 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8073 AStmt);
8074}
8075
Samuel Antaodf67fc42016-01-19 19:15:56 +00008076StmtResult
8077Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8078 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008079 SourceLocation EndLoc, Stmt *AStmt) {
8080 if (!AStmt)
8081 return StmtError();
8082
Alexey Bataeve3727102018-04-18 15:57:46 +00008083 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008084 // 1.2.2 OpenMP Language Terminology
8085 // Structured block - An executable statement with a single entry at the
8086 // top and a single exit at the bottom.
8087 // The point of exit cannot be a branch out of the structured block.
8088 // longjmp() and throw() must not violate the entry/exit criteria.
8089 CS->getCapturedDecl()->setNothrow();
8090 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
8091 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8092 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8093 // 1.2.2 OpenMP Language Terminology
8094 // Structured block - An executable statement with a single entry at the
8095 // top and a single exit at the bottom.
8096 // The point of exit cannot be a branch out of the structured block.
8097 // longjmp() and throw() must not violate the entry/exit criteria.
8098 CS->getCapturedDecl()->setNothrow();
8099 }
8100
Samuel Antaodf67fc42016-01-19 19:15:56 +00008101 // OpenMP [2.10.2, Restrictions, p. 99]
8102 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008103 if (!hasClauses(Clauses, OMPC_map)) {
8104 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8105 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008106 return StmtError();
8107 }
8108
Alexey Bataev7828b252017-11-21 17:08:48 +00008109 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8110 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008111}
8112
Samuel Antao72590762016-01-19 20:04:50 +00008113StmtResult
8114Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8115 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008116 SourceLocation EndLoc, Stmt *AStmt) {
8117 if (!AStmt)
8118 return StmtError();
8119
Alexey Bataeve3727102018-04-18 15:57:46 +00008120 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008121 // 1.2.2 OpenMP Language Terminology
8122 // Structured block - An executable statement with a single entry at the
8123 // top and a single exit at the bottom.
8124 // The point of exit cannot be a branch out of the structured block.
8125 // longjmp() and throw() must not violate the entry/exit criteria.
8126 CS->getCapturedDecl()->setNothrow();
8127 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
8128 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8129 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8130 // 1.2.2 OpenMP Language Terminology
8131 // Structured block - An executable statement with a single entry at the
8132 // top and a single exit at the bottom.
8133 // The point of exit cannot be a branch out of the structured block.
8134 // longjmp() and throw() must not violate the entry/exit criteria.
8135 CS->getCapturedDecl()->setNothrow();
8136 }
8137
Samuel Antao72590762016-01-19 20:04:50 +00008138 // OpenMP [2.10.3, Restrictions, p. 102]
8139 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008140 if (!hasClauses(Clauses, OMPC_map)) {
8141 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8142 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00008143 return StmtError();
8144 }
8145
Alexey Bataev7828b252017-11-21 17:08:48 +00008146 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8147 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00008148}
8149
Samuel Antao686c70c2016-05-26 17:30:50 +00008150StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8151 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008152 SourceLocation EndLoc,
8153 Stmt *AStmt) {
8154 if (!AStmt)
8155 return StmtError();
8156
Alexey Bataeve3727102018-04-18 15:57:46 +00008157 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008158 // 1.2.2 OpenMP Language Terminology
8159 // Structured block - An executable statement with a single entry at the
8160 // top and a single exit at the bottom.
8161 // The point of exit cannot be a branch out of the structured block.
8162 // longjmp() and throw() must not violate the entry/exit criteria.
8163 CS->getCapturedDecl()->setNothrow();
8164 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
8165 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8166 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8167 // 1.2.2 OpenMP Language Terminology
8168 // Structured block - An executable statement with a single entry at the
8169 // top and a single exit at the bottom.
8170 // The point of exit cannot be a branch out of the structured block.
8171 // longjmp() and throw() must not violate the entry/exit criteria.
8172 CS->getCapturedDecl()->setNothrow();
8173 }
8174
Alexey Bataev95b64a92017-05-30 16:00:04 +00008175 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00008176 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
8177 return StmtError();
8178 }
Alexey Bataev7828b252017-11-21 17:08:48 +00008179 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
8180 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00008181}
8182
Alexey Bataev13314bf2014-10-09 04:18:56 +00008183StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8184 Stmt *AStmt, SourceLocation StartLoc,
8185 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008186 if (!AStmt)
8187 return StmtError();
8188
Alexey Bataeve3727102018-04-18 15:57:46 +00008189 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008190 // 1.2.2 OpenMP Language Terminology
8191 // Structured block - An executable statement with a single entry at the
8192 // top and a single exit at the bottom.
8193 // The point of exit cannot be a branch out of the structured block.
8194 // longjmp() and throw() must not violate the entry/exit criteria.
8195 CS->getCapturedDecl()->setNothrow();
8196
Reid Kleckner87a31802018-03-12 21:43:02 +00008197 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00008198
Alexey Bataevceabd412017-11-30 18:01:54 +00008199 DSAStack->setParentTeamsRegionLoc(StartLoc);
8200
Alexey Bataev13314bf2014-10-09 04:18:56 +00008201 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8202}
8203
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008204StmtResult
8205Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8206 SourceLocation EndLoc,
8207 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008208 if (DSAStack->isParentNowaitRegion()) {
8209 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
8210 return StmtError();
8211 }
8212 if (DSAStack->isParentOrderedRegion()) {
8213 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
8214 return StmtError();
8215 }
8216 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
8217 CancelRegion);
8218}
8219
Alexey Bataev87933c72015-09-18 08:07:34 +00008220StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8221 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00008222 SourceLocation EndLoc,
8223 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00008224 if (DSAStack->isParentNowaitRegion()) {
8225 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
8226 return StmtError();
8227 }
8228 if (DSAStack->isParentOrderedRegion()) {
8229 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
8230 return StmtError();
8231 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008232 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00008233 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8234 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00008235}
8236
Alexey Bataev382967a2015-12-08 12:06:20 +00008237static bool checkGrainsizeNumTasksClauses(Sema &S,
8238 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008239 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00008240 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008241 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00008242 if (C->getClauseKind() == OMPC_grainsize ||
8243 C->getClauseKind() == OMPC_num_tasks) {
8244 if (!PrevClause)
8245 PrevClause = C;
8246 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008247 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008248 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
8249 << getOpenMPClauseName(C->getClauseKind())
8250 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008251 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008252 diag::note_omp_previous_grainsize_num_tasks)
8253 << getOpenMPClauseName(PrevClause->getClauseKind());
8254 ErrorFound = true;
8255 }
8256 }
8257 }
8258 return ErrorFound;
8259}
8260
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008261static bool checkReductionClauseWithNogroup(Sema &S,
8262 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008263 const OMPClause *ReductionClause = nullptr;
8264 const OMPClause *NogroupClause = nullptr;
8265 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008266 if (C->getClauseKind() == OMPC_reduction) {
8267 ReductionClause = C;
8268 if (NogroupClause)
8269 break;
8270 continue;
8271 }
8272 if (C->getClauseKind() == OMPC_nogroup) {
8273 NogroupClause = C;
8274 if (ReductionClause)
8275 break;
8276 continue;
8277 }
8278 }
8279 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008280 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
8281 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008282 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008283 return true;
8284 }
8285 return false;
8286}
8287
Alexey Bataev49f6e782015-12-01 04:18:41 +00008288StmtResult Sema::ActOnOpenMPTaskLoopDirective(
8289 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008290 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00008291 if (!AStmt)
8292 return StmtError();
8293
8294 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8295 OMPLoopDirective::HelperExprs B;
8296 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8297 // define the nested loops number.
8298 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008299 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008300 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00008301 VarsWithImplicitDSA, B);
8302 if (NestedLoopCount == 0)
8303 return StmtError();
8304
8305 assert((CurContext->isDependentContext() || B.builtAll()) &&
8306 "omp for loop exprs were not built");
8307
Alexey Bataev382967a2015-12-08 12:06:20 +00008308 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8309 // The grainsize clause and num_tasks clause are mutually exclusive and may
8310 // not appear on the same taskloop directive.
8311 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8312 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008313 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8314 // If a reduction clause is present on the taskloop directive, the nogroup
8315 // clause must not be specified.
8316 if (checkReductionClauseWithNogroup(*this, Clauses))
8317 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008318
Reid Kleckner87a31802018-03-12 21:43:02 +00008319 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00008320 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
8321 NestedLoopCount, Clauses, AStmt, B);
8322}
8323
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008324StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
8325 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008326 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008327 if (!AStmt)
8328 return StmtError();
8329
8330 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8331 OMPLoopDirective::HelperExprs B;
8332 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8333 // define the nested loops number.
8334 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008335 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008336 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
8337 VarsWithImplicitDSA, B);
8338 if (NestedLoopCount == 0)
8339 return StmtError();
8340
8341 assert((CurContext->isDependentContext() || B.builtAll()) &&
8342 "omp for loop exprs were not built");
8343
Alexey Bataev5a3af132016-03-29 08:58:54 +00008344 if (!CurContext->isDependentContext()) {
8345 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008346 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008347 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008348 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008349 B.NumIterations, *this, CurScope,
8350 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008351 return StmtError();
8352 }
8353 }
8354
Alexey Bataev382967a2015-12-08 12:06:20 +00008355 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8356 // The grainsize clause and num_tasks clause are mutually exclusive and may
8357 // not appear on the same taskloop directive.
8358 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8359 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008360 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8361 // If a reduction clause is present on the taskloop directive, the nogroup
8362 // clause must not be specified.
8363 if (checkReductionClauseWithNogroup(*this, Clauses))
8364 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00008365 if (checkSimdlenSafelenSpecified(*this, Clauses))
8366 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008367
Reid Kleckner87a31802018-03-12 21:43:02 +00008368 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008369 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
8370 NestedLoopCount, Clauses, AStmt, B);
8371}
8372
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008373StmtResult Sema::ActOnOpenMPDistributeDirective(
8374 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008375 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008376 if (!AStmt)
8377 return StmtError();
8378
8379 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8380 OMPLoopDirective::HelperExprs B;
8381 // In presence of clause 'collapse' with number of loops, it will
8382 // define the nested loops number.
8383 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008385 nullptr /*ordered not a clause on distribute*/, AStmt,
8386 *this, *DSAStack, VarsWithImplicitDSA, B);
8387 if (NestedLoopCount == 0)
8388 return StmtError();
8389
8390 assert((CurContext->isDependentContext() || B.builtAll()) &&
8391 "omp for loop exprs were not built");
8392
Reid Kleckner87a31802018-03-12 21:43:02 +00008393 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008394 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
8395 NestedLoopCount, Clauses, AStmt, B);
8396}
8397
Carlo Bertolli9925f152016-06-27 14:55:37 +00008398StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
8399 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008400 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00008401 if (!AStmt)
8402 return StmtError();
8403
Alexey Bataeve3727102018-04-18 15:57:46 +00008404 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00008405 // 1.2.2 OpenMP Language Terminology
8406 // Structured block - An executable statement with a single entry at the
8407 // top and a single exit at the bottom.
8408 // The point of exit cannot be a branch out of the structured block.
8409 // longjmp() and throw() must not violate the entry/exit criteria.
8410 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00008411 for (int ThisCaptureLevel =
8412 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
8413 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8414 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8415 // 1.2.2 OpenMP Language Terminology
8416 // Structured block - An executable statement with a single entry at the
8417 // top and a single exit at the bottom.
8418 // The point of exit cannot be a branch out of the structured block.
8419 // longjmp() and throw() must not violate the entry/exit criteria.
8420 CS->getCapturedDecl()->setNothrow();
8421 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00008422
8423 OMPLoopDirective::HelperExprs B;
8424 // In presence of clause 'collapse' with number of loops, it will
8425 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008426 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00008427 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00008428 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00008429 VarsWithImplicitDSA, B);
8430 if (NestedLoopCount == 0)
8431 return StmtError();
8432
8433 assert((CurContext->isDependentContext() || B.builtAll()) &&
8434 "omp for loop exprs were not built");
8435
Reid Kleckner87a31802018-03-12 21:43:02 +00008436 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008437 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008438 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8439 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00008440}
8441
Kelvin Li4a39add2016-07-05 05:00:15 +00008442StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
8443 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008444 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00008445 if (!AStmt)
8446 return StmtError();
8447
Alexey Bataeve3727102018-04-18 15:57:46 +00008448 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00008449 // 1.2.2 OpenMP Language Terminology
8450 // Structured block - An executable statement with a single entry at the
8451 // top and a single exit at the bottom.
8452 // The point of exit cannot be a branch out of the structured block.
8453 // longjmp() and throw() must not violate the entry/exit criteria.
8454 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00008455 for (int ThisCaptureLevel =
8456 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
8457 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8458 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8459 // 1.2.2 OpenMP Language Terminology
8460 // Structured block - An executable statement with a single entry at the
8461 // top and a single exit at the bottom.
8462 // The point of exit cannot be a branch out of the structured block.
8463 // longjmp() and throw() must not violate the entry/exit criteria.
8464 CS->getCapturedDecl()->setNothrow();
8465 }
Kelvin Li4a39add2016-07-05 05:00:15 +00008466
8467 OMPLoopDirective::HelperExprs B;
8468 // In presence of clause 'collapse' with number of loops, it will
8469 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008470 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00008471 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00008472 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00008473 VarsWithImplicitDSA, B);
8474 if (NestedLoopCount == 0)
8475 return StmtError();
8476
8477 assert((CurContext->isDependentContext() || B.builtAll()) &&
8478 "omp for loop exprs were not built");
8479
Alexey Bataev438388c2017-11-22 18:34:02 +00008480 if (!CurContext->isDependentContext()) {
8481 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008482 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008483 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8484 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8485 B.NumIterations, *this, CurScope,
8486 DSAStack))
8487 return StmtError();
8488 }
8489 }
8490
Kelvin Lic5609492016-07-15 04:39:07 +00008491 if (checkSimdlenSafelenSpecified(*this, Clauses))
8492 return StmtError();
8493
Reid Kleckner87a31802018-03-12 21:43:02 +00008494 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00008495 return OMPDistributeParallelForSimdDirective::Create(
8496 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8497}
8498
Kelvin Li787f3fc2016-07-06 04:45:38 +00008499StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
8500 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008501 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00008502 if (!AStmt)
8503 return StmtError();
8504
Alexey Bataeve3727102018-04-18 15:57:46 +00008505 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008506 // 1.2.2 OpenMP Language Terminology
8507 // Structured block - An executable statement with a single entry at the
8508 // top and a single exit at the bottom.
8509 // The point of exit cannot be a branch out of the structured block.
8510 // longjmp() and throw() must not violate the entry/exit criteria.
8511 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00008512 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
8513 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8514 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8515 // 1.2.2 OpenMP Language Terminology
8516 // Structured block - An executable statement with a single entry at the
8517 // top and a single exit at the bottom.
8518 // The point of exit cannot be a branch out of the structured block.
8519 // longjmp() and throw() must not violate the entry/exit criteria.
8520 CS->getCapturedDecl()->setNothrow();
8521 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00008522
8523 OMPLoopDirective::HelperExprs B;
8524 // In presence of clause 'collapse' with number of loops, it will
8525 // define the nested loops number.
8526 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008527 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00008528 nullptr /*ordered not a clause on distribute*/, CS, *this,
8529 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008530 if (NestedLoopCount == 0)
8531 return StmtError();
8532
8533 assert((CurContext->isDependentContext() || B.builtAll()) &&
8534 "omp for loop exprs were not built");
8535
Alexey Bataev438388c2017-11-22 18:34:02 +00008536 if (!CurContext->isDependentContext()) {
8537 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008538 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008539 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8540 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8541 B.NumIterations, *this, CurScope,
8542 DSAStack))
8543 return StmtError();
8544 }
8545 }
8546
Kelvin Lic5609492016-07-15 04:39:07 +00008547 if (checkSimdlenSafelenSpecified(*this, Clauses))
8548 return StmtError();
8549
Reid Kleckner87a31802018-03-12 21:43:02 +00008550 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00008551 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8552 NestedLoopCount, Clauses, AStmt, B);
8553}
8554
Kelvin Lia579b912016-07-14 02:54:56 +00008555StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8556 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008557 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00008558 if (!AStmt)
8559 return StmtError();
8560
Alexey Bataeve3727102018-04-18 15:57:46 +00008561 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00008562 // 1.2.2 OpenMP Language Terminology
8563 // Structured block - An executable statement with a single entry at the
8564 // top and a single exit at the bottom.
8565 // The point of exit cannot be a branch out of the structured block.
8566 // longjmp() and throw() must not violate the entry/exit criteria.
8567 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008568 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8569 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8570 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8571 // 1.2.2 OpenMP Language Terminology
8572 // Structured block - An executable statement with a single entry at the
8573 // top and a single exit at the bottom.
8574 // The point of exit cannot be a branch out of the structured block.
8575 // longjmp() and throw() must not violate the entry/exit criteria.
8576 CS->getCapturedDecl()->setNothrow();
8577 }
Kelvin Lia579b912016-07-14 02:54:56 +00008578
8579 OMPLoopDirective::HelperExprs B;
8580 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8581 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008582 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008583 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008584 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008585 VarsWithImplicitDSA, B);
8586 if (NestedLoopCount == 0)
8587 return StmtError();
8588
8589 assert((CurContext->isDependentContext() || B.builtAll()) &&
8590 "omp target parallel for simd loop exprs were not built");
8591
8592 if (!CurContext->isDependentContext()) {
8593 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008594 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008595 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008596 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8597 B.NumIterations, *this, CurScope,
8598 DSAStack))
8599 return StmtError();
8600 }
8601 }
Kelvin Lic5609492016-07-15 04:39:07 +00008602 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008603 return StmtError();
8604
Reid Kleckner87a31802018-03-12 21:43:02 +00008605 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008606 return OMPTargetParallelForSimdDirective::Create(
8607 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8608}
8609
Kelvin Li986330c2016-07-20 22:57:10 +00008610StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8611 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008612 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008613 if (!AStmt)
8614 return StmtError();
8615
Alexey Bataeve3727102018-04-18 15:57:46 +00008616 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008617 // 1.2.2 OpenMP Language Terminology
8618 // Structured block - An executable statement with a single entry at the
8619 // top and a single exit at the bottom.
8620 // The point of exit cannot be a branch out of the structured block.
8621 // longjmp() and throw() must not violate the entry/exit criteria.
8622 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008623 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8624 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8625 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8626 // 1.2.2 OpenMP Language Terminology
8627 // Structured block - An executable statement with a single entry at the
8628 // top and a single exit at the bottom.
8629 // The point of exit cannot be a branch out of the structured block.
8630 // longjmp() and throw() must not violate the entry/exit criteria.
8631 CS->getCapturedDecl()->setNothrow();
8632 }
8633
Kelvin Li986330c2016-07-20 22:57:10 +00008634 OMPLoopDirective::HelperExprs B;
8635 // In presence of clause 'collapse' with number of loops, it will define the
8636 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008637 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008638 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008639 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008640 VarsWithImplicitDSA, B);
8641 if (NestedLoopCount == 0)
8642 return StmtError();
8643
8644 assert((CurContext->isDependentContext() || B.builtAll()) &&
8645 "omp target simd loop exprs were not built");
8646
8647 if (!CurContext->isDependentContext()) {
8648 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008649 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008650 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008651 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8652 B.NumIterations, *this, CurScope,
8653 DSAStack))
8654 return StmtError();
8655 }
8656 }
8657
8658 if (checkSimdlenSafelenSpecified(*this, Clauses))
8659 return StmtError();
8660
Reid Kleckner87a31802018-03-12 21:43:02 +00008661 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008662 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8663 NestedLoopCount, Clauses, AStmt, B);
8664}
8665
Kelvin Li02532872016-08-05 14:37:37 +00008666StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8667 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008668 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008669 if (!AStmt)
8670 return StmtError();
8671
Alexey Bataeve3727102018-04-18 15:57:46 +00008672 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008673 // 1.2.2 OpenMP Language Terminology
8674 // Structured block - An executable statement with a single entry at the
8675 // top and a single exit at the bottom.
8676 // The point of exit cannot be a branch out of the structured block.
8677 // longjmp() and throw() must not violate the entry/exit criteria.
8678 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008679 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8680 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8681 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8682 // 1.2.2 OpenMP Language Terminology
8683 // Structured block - An executable statement with a single entry at the
8684 // top and a single exit at the bottom.
8685 // The point of exit cannot be a branch out of the structured block.
8686 // longjmp() and throw() must not violate the entry/exit criteria.
8687 CS->getCapturedDecl()->setNothrow();
8688 }
Kelvin Li02532872016-08-05 14:37:37 +00008689
8690 OMPLoopDirective::HelperExprs B;
8691 // In presence of clause 'collapse' with number of loops, it will
8692 // define the nested loops number.
8693 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008694 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008695 nullptr /*ordered not a clause on distribute*/, CS, *this,
8696 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008697 if (NestedLoopCount == 0)
8698 return StmtError();
8699
8700 assert((CurContext->isDependentContext() || B.builtAll()) &&
8701 "omp teams distribute loop exprs were not built");
8702
Reid Kleckner87a31802018-03-12 21:43:02 +00008703 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008704
8705 DSAStack->setParentTeamsRegionLoc(StartLoc);
8706
David Majnemer9d168222016-08-05 17:44:54 +00008707 return OMPTeamsDistributeDirective::Create(
8708 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008709}
8710
Kelvin Li4e325f72016-10-25 12:50:55 +00008711StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008713 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008714 if (!AStmt)
8715 return StmtError();
8716
Alexey Bataeve3727102018-04-18 15:57:46 +00008717 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008718 // 1.2.2 OpenMP Language Terminology
8719 // Structured block - An executable statement with a single entry at the
8720 // top and a single exit at the bottom.
8721 // The point of exit cannot be a branch out of the structured block.
8722 // longjmp() and throw() must not violate the entry/exit criteria.
8723 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008724 for (int ThisCaptureLevel =
8725 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8726 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8727 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8728 // 1.2.2 OpenMP Language Terminology
8729 // Structured block - An executable statement with a single entry at the
8730 // top and a single exit at the bottom.
8731 // The point of exit cannot be a branch out of the structured block.
8732 // longjmp() and throw() must not violate the entry/exit criteria.
8733 CS->getCapturedDecl()->setNothrow();
8734 }
8735
Kelvin Li4e325f72016-10-25 12:50:55 +00008736
8737 OMPLoopDirective::HelperExprs B;
8738 // In presence of clause 'collapse' with number of loops, it will
8739 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008740 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008741 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008742 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008743 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008744
8745 if (NestedLoopCount == 0)
8746 return StmtError();
8747
8748 assert((CurContext->isDependentContext() || B.builtAll()) &&
8749 "omp teams distribute simd loop exprs were not built");
8750
8751 if (!CurContext->isDependentContext()) {
8752 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008753 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008754 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8755 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8756 B.NumIterations, *this, CurScope,
8757 DSAStack))
8758 return StmtError();
8759 }
8760 }
8761
8762 if (checkSimdlenSafelenSpecified(*this, Clauses))
8763 return StmtError();
8764
Reid Kleckner87a31802018-03-12 21:43:02 +00008765 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008766
8767 DSAStack->setParentTeamsRegionLoc(StartLoc);
8768
Kelvin Li4e325f72016-10-25 12:50:55 +00008769 return OMPTeamsDistributeSimdDirective::Create(
8770 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8771}
8772
Kelvin Li579e41c2016-11-30 23:51:03 +00008773StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8774 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008775 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008776 if (!AStmt)
8777 return StmtError();
8778
Alexey Bataeve3727102018-04-18 15:57:46 +00008779 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008780 // 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
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008787 for (int ThisCaptureLevel =
8788 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8789 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8790 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8791 // 1.2.2 OpenMP Language Terminology
8792 // Structured block - An executable statement with a single entry at the
8793 // top and a single exit at the bottom.
8794 // The point of exit cannot be a branch out of the structured block.
8795 // longjmp() and throw() must not violate the entry/exit criteria.
8796 CS->getCapturedDecl()->setNothrow();
8797 }
8798
Kelvin Li579e41c2016-11-30 23:51:03 +00008799 OMPLoopDirective::HelperExprs B;
8800 // In presence of clause 'collapse' with number of loops, it will
8801 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008802 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008803 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008804 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008805 VarsWithImplicitDSA, B);
8806
8807 if (NestedLoopCount == 0)
8808 return StmtError();
8809
8810 assert((CurContext->isDependentContext() || B.builtAll()) &&
8811 "omp for loop exprs were not built");
8812
8813 if (!CurContext->isDependentContext()) {
8814 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008815 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008816 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8817 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8818 B.NumIterations, *this, CurScope,
8819 DSAStack))
8820 return StmtError();
8821 }
8822 }
8823
8824 if (checkSimdlenSafelenSpecified(*this, Clauses))
8825 return StmtError();
8826
Reid Kleckner87a31802018-03-12 21:43:02 +00008827 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008828
8829 DSAStack->setParentTeamsRegionLoc(StartLoc);
8830
Kelvin Li579e41c2016-11-30 23:51:03 +00008831 return OMPTeamsDistributeParallelForSimdDirective::Create(
8832 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8833}
8834
Kelvin Li7ade93f2016-12-09 03:24:30 +00008835StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8836 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008837 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008838 if (!AStmt)
8839 return StmtError();
8840
Alexey Bataeve3727102018-04-18 15:57:46 +00008841 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008842 // 1.2.2 OpenMP Language Terminology
8843 // Structured block - An executable statement with a single entry at the
8844 // top and a single exit at the bottom.
8845 // The point of exit cannot be a branch out of the structured block.
8846 // longjmp() and throw() must not violate the entry/exit criteria.
8847 CS->getCapturedDecl()->setNothrow();
8848
Carlo Bertolli62fae152017-11-20 20:46:39 +00008849 for (int ThisCaptureLevel =
8850 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8851 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8852 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8853 // 1.2.2 OpenMP Language Terminology
8854 // Structured block - An executable statement with a single entry at the
8855 // top and a single exit at the bottom.
8856 // The point of exit cannot be a branch out of the structured block.
8857 // longjmp() and throw() must not violate the entry/exit criteria.
8858 CS->getCapturedDecl()->setNothrow();
8859 }
8860
Kelvin Li7ade93f2016-12-09 03:24:30 +00008861 OMPLoopDirective::HelperExprs B;
8862 // In presence of clause 'collapse' with number of loops, it will
8863 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008864 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008865 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008866 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008867 VarsWithImplicitDSA, B);
8868
8869 if (NestedLoopCount == 0)
8870 return StmtError();
8871
8872 assert((CurContext->isDependentContext() || B.builtAll()) &&
8873 "omp for loop exprs were not built");
8874
Reid Kleckner87a31802018-03-12 21:43:02 +00008875 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008876
8877 DSAStack->setParentTeamsRegionLoc(StartLoc);
8878
Kelvin Li7ade93f2016-12-09 03:24:30 +00008879 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008880 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8881 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008882}
8883
Kelvin Libf594a52016-12-17 05:48:59 +00008884StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8885 Stmt *AStmt,
8886 SourceLocation StartLoc,
8887 SourceLocation EndLoc) {
8888 if (!AStmt)
8889 return StmtError();
8890
Alexey Bataeve3727102018-04-18 15:57:46 +00008891 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008892 // 1.2.2 OpenMP Language Terminology
8893 // Structured block - An executable statement with a single entry at the
8894 // top and a single exit at the bottom.
8895 // The point of exit cannot be a branch out of the structured block.
8896 // longjmp() and throw() must not violate the entry/exit criteria.
8897 CS->getCapturedDecl()->setNothrow();
8898
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008899 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
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 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008909 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008910
8911 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8912 AStmt);
8913}
8914
Kelvin Li83c451e2016-12-25 04:52:54 +00008915StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8916 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008917 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008918 if (!AStmt)
8919 return StmtError();
8920
Alexey Bataeve3727102018-04-18 15:57:46 +00008921 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008922 // 1.2.2 OpenMP Language Terminology
8923 // Structured block - An executable statement with a single entry at the
8924 // top and a single exit at the bottom.
8925 // The point of exit cannot be a branch out of the structured block.
8926 // longjmp() and throw() must not violate the entry/exit criteria.
8927 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008928 for (int ThisCaptureLevel =
8929 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8930 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8931 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8932 // 1.2.2 OpenMP Language Terminology
8933 // Structured block - An executable statement with a single entry at the
8934 // top and a single exit at the bottom.
8935 // The point of exit cannot be a branch out of the structured block.
8936 // longjmp() and throw() must not violate the entry/exit criteria.
8937 CS->getCapturedDecl()->setNothrow();
8938 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008939
8940 OMPLoopDirective::HelperExprs B;
8941 // In presence of clause 'collapse' with number of loops, it will
8942 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008943 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008944 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8945 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008946 VarsWithImplicitDSA, B);
8947 if (NestedLoopCount == 0)
8948 return StmtError();
8949
8950 assert((CurContext->isDependentContext() || B.builtAll()) &&
8951 "omp target teams distribute loop exprs were not built");
8952
Reid Kleckner87a31802018-03-12 21:43:02 +00008953 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008954 return OMPTargetTeamsDistributeDirective::Create(
8955 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8956}
8957
Kelvin Li80e8f562016-12-29 22:16:30 +00008958StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8959 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008960 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008961 if (!AStmt)
8962 return StmtError();
8963
Alexey Bataeve3727102018-04-18 15:57:46 +00008964 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008965 // 1.2.2 OpenMP Language Terminology
8966 // Structured block - An executable statement with a single entry at the
8967 // top and a single exit at the bottom.
8968 // The point of exit cannot be a branch out of the structured block.
8969 // longjmp() and throw() must not violate the entry/exit criteria.
8970 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008971 for (int ThisCaptureLevel =
8972 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8973 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8974 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8975 // 1.2.2 OpenMP Language Terminology
8976 // Structured block - An executable statement with a single entry at the
8977 // top and a single exit at the bottom.
8978 // The point of exit cannot be a branch out of the structured block.
8979 // longjmp() and throw() must not violate the entry/exit criteria.
8980 CS->getCapturedDecl()->setNothrow();
8981 }
8982
Kelvin Li80e8f562016-12-29 22:16:30 +00008983 OMPLoopDirective::HelperExprs B;
8984 // In presence of clause 'collapse' with number of loops, it will
8985 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008986 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008987 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8988 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008989 VarsWithImplicitDSA, B);
8990 if (NestedLoopCount == 0)
8991 return StmtError();
8992
8993 assert((CurContext->isDependentContext() || B.builtAll()) &&
8994 "omp target teams distribute parallel for loop exprs were not built");
8995
Alexey Bataev647dd842018-01-15 20:59:40 +00008996 if (!CurContext->isDependentContext()) {
8997 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008998 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008999 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9000 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9001 B.NumIterations, *this, CurScope,
9002 DSAStack))
9003 return StmtError();
9004 }
9005 }
9006
Reid Kleckner87a31802018-03-12 21:43:02 +00009007 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00009008 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00009009 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9010 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00009011}
9012
Kelvin Li1851df52017-01-03 05:23:48 +00009013StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9014 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009015 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00009016 if (!AStmt)
9017 return StmtError();
9018
Alexey Bataeve3727102018-04-18 15:57:46 +00009019 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00009020 // 1.2.2 OpenMP Language Terminology
9021 // Structured block - An executable statement with a single entry at the
9022 // top and a single exit at the bottom.
9023 // The point of exit cannot be a branch out of the structured block.
9024 // longjmp() and throw() must not violate the entry/exit criteria.
9025 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00009026 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
9027 OMPD_target_teams_distribute_parallel_for_simd);
9028 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9029 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9030 // 1.2.2 OpenMP Language Terminology
9031 // Structured block - An executable statement with a single entry at the
9032 // top and a single exit at the bottom.
9033 // The point of exit cannot be a branch out of the structured block.
9034 // longjmp() and throw() must not violate the entry/exit criteria.
9035 CS->getCapturedDecl()->setNothrow();
9036 }
Kelvin Li1851df52017-01-03 05:23:48 +00009037
9038 OMPLoopDirective::HelperExprs B;
9039 // In presence of clause 'collapse' with number of loops, it will
9040 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009041 unsigned NestedLoopCount =
9042 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00009043 getCollapseNumberExpr(Clauses),
9044 nullptr /*ordered not a clause on distribute*/, CS, *this,
9045 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00009046 if (NestedLoopCount == 0)
9047 return StmtError();
9048
9049 assert((CurContext->isDependentContext() || B.builtAll()) &&
9050 "omp target teams distribute parallel for simd loop exprs were not "
9051 "built");
9052
9053 if (!CurContext->isDependentContext()) {
9054 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009055 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00009056 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9057 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9058 B.NumIterations, *this, CurScope,
9059 DSAStack))
9060 return StmtError();
9061 }
9062 }
9063
Alexey Bataev438388c2017-11-22 18:34:02 +00009064 if (checkSimdlenSafelenSpecified(*this, Clauses))
9065 return StmtError();
9066
Reid Kleckner87a31802018-03-12 21:43:02 +00009067 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00009068 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
9069 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9070}
9071
Kelvin Lida681182017-01-10 18:08:18 +00009072StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
9073 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009074 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00009075 if (!AStmt)
9076 return StmtError();
9077
9078 auto *CS = cast<CapturedStmt>(AStmt);
9079 // 1.2.2 OpenMP Language Terminology
9080 // Structured block - An executable statement with a single entry at the
9081 // top and a single exit at the bottom.
9082 // The point of exit cannot be a branch out of the structured block.
9083 // longjmp() and throw() must not violate the entry/exit criteria.
9084 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009085 for (int ThisCaptureLevel =
9086 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
9087 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9088 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9089 // 1.2.2 OpenMP Language Terminology
9090 // Structured block - An executable statement with a single entry at the
9091 // top and a single exit at the bottom.
9092 // The point of exit cannot be a branch out of the structured block.
9093 // longjmp() and throw() must not violate the entry/exit criteria.
9094 CS->getCapturedDecl()->setNothrow();
9095 }
Kelvin Lida681182017-01-10 18:08:18 +00009096
9097 OMPLoopDirective::HelperExprs B;
9098 // In presence of clause 'collapse' with number of loops, it will
9099 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009100 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00009101 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009102 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00009103 VarsWithImplicitDSA, B);
9104 if (NestedLoopCount == 0)
9105 return StmtError();
9106
9107 assert((CurContext->isDependentContext() || B.builtAll()) &&
9108 "omp target teams distribute simd loop exprs were not built");
9109
Alexey Bataev438388c2017-11-22 18:34:02 +00009110 if (!CurContext->isDependentContext()) {
9111 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009112 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009113 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9114 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9115 B.NumIterations, *this, CurScope,
9116 DSAStack))
9117 return StmtError();
9118 }
9119 }
9120
9121 if (checkSimdlenSafelenSpecified(*this, Clauses))
9122 return StmtError();
9123
Reid Kleckner87a31802018-03-12 21:43:02 +00009124 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00009125 return OMPTargetTeamsDistributeSimdDirective::Create(
9126 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9127}
9128
Alexey Bataeved09d242014-05-28 05:53:51 +00009129OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009130 SourceLocation StartLoc,
9131 SourceLocation LParenLoc,
9132 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009133 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009134 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00009135 case OMPC_final:
9136 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
9137 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00009138 case OMPC_num_threads:
9139 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
9140 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009141 case OMPC_safelen:
9142 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
9143 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00009144 case OMPC_simdlen:
9145 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
9146 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009147 case OMPC_allocator:
9148 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
9149 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00009150 case OMPC_collapse:
9151 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
9152 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009153 case OMPC_ordered:
9154 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
9155 break;
Michael Wonge710d542015-08-07 16:16:36 +00009156 case OMPC_device:
9157 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
9158 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00009159 case OMPC_num_teams:
9160 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
9161 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009162 case OMPC_thread_limit:
9163 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
9164 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00009165 case OMPC_priority:
9166 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
9167 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009168 case OMPC_grainsize:
9169 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
9170 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00009171 case OMPC_num_tasks:
9172 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
9173 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00009174 case OMPC_hint:
9175 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
9176 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009177 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009178 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009179 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009180 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009181 case OMPC_private:
9182 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009183 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009184 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009185 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009186 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009187 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009188 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009189 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009190 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009191 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00009192 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009193 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009194 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009195 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009196 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009197 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009198 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009199 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009200 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009201 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009202 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009203 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00009204 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009205 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009206 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00009207 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009208 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009209 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009210 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009211 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009212 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009213 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009214 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009215 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009216 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009217 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009218 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009219 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009220 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009221 llvm_unreachable("Clause is not allowed.");
9222 }
9223 return Res;
9224}
9225
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009226// An OpenMP directive such as 'target parallel' has two captured regions:
9227// for the 'target' and 'parallel' respectively. This function returns
9228// the region in which to capture expressions associated with a clause.
9229// A return value of OMPD_unknown signifies that the expression should not
9230// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009231static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
9232 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
9233 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009234 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009235 switch (CKind) {
9236 case OMPC_if:
9237 switch (DKind) {
9238 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009239 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009240 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009241 // If this clause applies to the nested 'parallel' region, capture within
9242 // the 'target' region, otherwise do not capture.
9243 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9244 CaptureRegion = OMPD_target;
9245 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00009246 case OMPD_target_teams_distribute_parallel_for:
9247 case OMPD_target_teams_distribute_parallel_for_simd:
9248 // If this clause applies to the nested 'parallel' region, capture within
9249 // the 'teams' region, otherwise do not capture.
9250 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9251 CaptureRegion = OMPD_teams;
9252 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009253 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009254 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009255 CaptureRegion = OMPD_teams;
9256 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009257 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009258 case OMPD_target_enter_data:
9259 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009260 CaptureRegion = OMPD_task;
9261 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009262 case OMPD_cancel:
9263 case OMPD_parallel:
9264 case OMPD_parallel_sections:
9265 case OMPD_parallel_for:
9266 case OMPD_parallel_for_simd:
9267 case OMPD_target:
9268 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009269 case OMPD_target_teams:
9270 case OMPD_target_teams_distribute:
9271 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009272 case OMPD_distribute_parallel_for:
9273 case OMPD_distribute_parallel_for_simd:
9274 case OMPD_task:
9275 case OMPD_taskloop:
9276 case OMPD_taskloop_simd:
9277 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009278 // Do not capture if-clause expressions.
9279 break;
9280 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009281 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009282 case OMPD_taskyield:
9283 case OMPD_barrier:
9284 case OMPD_taskwait:
9285 case OMPD_cancellation_point:
9286 case OMPD_flush:
9287 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009288 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009289 case OMPD_declare_simd:
9290 case OMPD_declare_target:
9291 case OMPD_end_declare_target:
9292 case OMPD_teams:
9293 case OMPD_simd:
9294 case OMPD_for:
9295 case OMPD_for_simd:
9296 case OMPD_sections:
9297 case OMPD_section:
9298 case OMPD_single:
9299 case OMPD_master:
9300 case OMPD_critical:
9301 case OMPD_taskgroup:
9302 case OMPD_distribute:
9303 case OMPD_ordered:
9304 case OMPD_atomic:
9305 case OMPD_distribute_simd:
9306 case OMPD_teams_distribute:
9307 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009308 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009309 llvm_unreachable("Unexpected OpenMP directive with if-clause");
9310 case OMPD_unknown:
9311 llvm_unreachable("Unknown OpenMP directive");
9312 }
9313 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009314 case OMPC_num_threads:
9315 switch (DKind) {
9316 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009317 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009318 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009319 CaptureRegion = OMPD_target;
9320 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009321 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009322 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009323 case OMPD_target_teams_distribute_parallel_for:
9324 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009325 CaptureRegion = OMPD_teams;
9326 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009327 case OMPD_parallel:
9328 case OMPD_parallel_sections:
9329 case OMPD_parallel_for:
9330 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009331 case OMPD_distribute_parallel_for:
9332 case OMPD_distribute_parallel_for_simd:
9333 // Do not capture num_threads-clause expressions.
9334 break;
9335 case OMPD_target_data:
9336 case OMPD_target_enter_data:
9337 case OMPD_target_exit_data:
9338 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009339 case OMPD_target:
9340 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009341 case OMPD_target_teams:
9342 case OMPD_target_teams_distribute:
9343 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009344 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009345 case OMPD_task:
9346 case OMPD_taskloop:
9347 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009348 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009349 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009350 case OMPD_taskyield:
9351 case OMPD_barrier:
9352 case OMPD_taskwait:
9353 case OMPD_cancellation_point:
9354 case OMPD_flush:
9355 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009356 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009357 case OMPD_declare_simd:
9358 case OMPD_declare_target:
9359 case OMPD_end_declare_target:
9360 case OMPD_teams:
9361 case OMPD_simd:
9362 case OMPD_for:
9363 case OMPD_for_simd:
9364 case OMPD_sections:
9365 case OMPD_section:
9366 case OMPD_single:
9367 case OMPD_master:
9368 case OMPD_critical:
9369 case OMPD_taskgroup:
9370 case OMPD_distribute:
9371 case OMPD_ordered:
9372 case OMPD_atomic:
9373 case OMPD_distribute_simd:
9374 case OMPD_teams_distribute:
9375 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009376 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009377 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
9378 case OMPD_unknown:
9379 llvm_unreachable("Unknown OpenMP directive");
9380 }
9381 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009382 case OMPC_num_teams:
9383 switch (DKind) {
9384 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009385 case OMPD_target_teams_distribute:
9386 case OMPD_target_teams_distribute_simd:
9387 case OMPD_target_teams_distribute_parallel_for:
9388 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009389 CaptureRegion = OMPD_target;
9390 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009391 case OMPD_teams_distribute_parallel_for:
9392 case OMPD_teams_distribute_parallel_for_simd:
9393 case OMPD_teams:
9394 case OMPD_teams_distribute:
9395 case OMPD_teams_distribute_simd:
9396 // Do not capture num_teams-clause expressions.
9397 break;
9398 case OMPD_distribute_parallel_for:
9399 case OMPD_distribute_parallel_for_simd:
9400 case OMPD_task:
9401 case OMPD_taskloop:
9402 case OMPD_taskloop_simd:
9403 case OMPD_target_data:
9404 case OMPD_target_enter_data:
9405 case OMPD_target_exit_data:
9406 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009407 case OMPD_cancel:
9408 case OMPD_parallel:
9409 case OMPD_parallel_sections:
9410 case OMPD_parallel_for:
9411 case OMPD_parallel_for_simd:
9412 case OMPD_target:
9413 case OMPD_target_simd:
9414 case OMPD_target_parallel:
9415 case OMPD_target_parallel_for:
9416 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009417 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009418 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009419 case OMPD_taskyield:
9420 case OMPD_barrier:
9421 case OMPD_taskwait:
9422 case OMPD_cancellation_point:
9423 case OMPD_flush:
9424 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009425 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009426 case OMPD_declare_simd:
9427 case OMPD_declare_target:
9428 case OMPD_end_declare_target:
9429 case OMPD_simd:
9430 case OMPD_for:
9431 case OMPD_for_simd:
9432 case OMPD_sections:
9433 case OMPD_section:
9434 case OMPD_single:
9435 case OMPD_master:
9436 case OMPD_critical:
9437 case OMPD_taskgroup:
9438 case OMPD_distribute:
9439 case OMPD_ordered:
9440 case OMPD_atomic:
9441 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009442 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009443 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9444 case OMPD_unknown:
9445 llvm_unreachable("Unknown OpenMP directive");
9446 }
9447 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009448 case OMPC_thread_limit:
9449 switch (DKind) {
9450 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009451 case OMPD_target_teams_distribute:
9452 case OMPD_target_teams_distribute_simd:
9453 case OMPD_target_teams_distribute_parallel_for:
9454 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009455 CaptureRegion = OMPD_target;
9456 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009457 case OMPD_teams_distribute_parallel_for:
9458 case OMPD_teams_distribute_parallel_for_simd:
9459 case OMPD_teams:
9460 case OMPD_teams_distribute:
9461 case OMPD_teams_distribute_simd:
9462 // Do not capture thread_limit-clause expressions.
9463 break;
9464 case OMPD_distribute_parallel_for:
9465 case OMPD_distribute_parallel_for_simd:
9466 case OMPD_task:
9467 case OMPD_taskloop:
9468 case OMPD_taskloop_simd:
9469 case OMPD_target_data:
9470 case OMPD_target_enter_data:
9471 case OMPD_target_exit_data:
9472 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009473 case OMPD_cancel:
9474 case OMPD_parallel:
9475 case OMPD_parallel_sections:
9476 case OMPD_parallel_for:
9477 case OMPD_parallel_for_simd:
9478 case OMPD_target:
9479 case OMPD_target_simd:
9480 case OMPD_target_parallel:
9481 case OMPD_target_parallel_for:
9482 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009483 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009484 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009485 case OMPD_taskyield:
9486 case OMPD_barrier:
9487 case OMPD_taskwait:
9488 case OMPD_cancellation_point:
9489 case OMPD_flush:
9490 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009491 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009492 case OMPD_declare_simd:
9493 case OMPD_declare_target:
9494 case OMPD_end_declare_target:
9495 case OMPD_simd:
9496 case OMPD_for:
9497 case OMPD_for_simd:
9498 case OMPD_sections:
9499 case OMPD_section:
9500 case OMPD_single:
9501 case OMPD_master:
9502 case OMPD_critical:
9503 case OMPD_taskgroup:
9504 case OMPD_distribute:
9505 case OMPD_ordered:
9506 case OMPD_atomic:
9507 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009508 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009509 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
9510 case OMPD_unknown:
9511 llvm_unreachable("Unknown OpenMP directive");
9512 }
9513 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009514 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009515 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00009516 case OMPD_parallel_for:
9517 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009518 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00009519 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009520 case OMPD_teams_distribute_parallel_for:
9521 case OMPD_teams_distribute_parallel_for_simd:
9522 case OMPD_target_parallel_for:
9523 case OMPD_target_parallel_for_simd:
9524 case OMPD_target_teams_distribute_parallel_for:
9525 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009526 CaptureRegion = OMPD_parallel;
9527 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009528 case OMPD_for:
9529 case OMPD_for_simd:
9530 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009531 break;
9532 case OMPD_task:
9533 case OMPD_taskloop:
9534 case OMPD_taskloop_simd:
9535 case OMPD_target_data:
9536 case OMPD_target_enter_data:
9537 case OMPD_target_exit_data:
9538 case OMPD_target_update:
9539 case OMPD_teams:
9540 case OMPD_teams_distribute:
9541 case OMPD_teams_distribute_simd:
9542 case OMPD_target_teams_distribute:
9543 case OMPD_target_teams_distribute_simd:
9544 case OMPD_target:
9545 case OMPD_target_simd:
9546 case OMPD_target_parallel:
9547 case OMPD_cancel:
9548 case OMPD_parallel:
9549 case OMPD_parallel_sections:
9550 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009551 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009552 case OMPD_taskyield:
9553 case OMPD_barrier:
9554 case OMPD_taskwait:
9555 case OMPD_cancellation_point:
9556 case OMPD_flush:
9557 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009558 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009559 case OMPD_declare_simd:
9560 case OMPD_declare_target:
9561 case OMPD_end_declare_target:
9562 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009563 case OMPD_sections:
9564 case OMPD_section:
9565 case OMPD_single:
9566 case OMPD_master:
9567 case OMPD_critical:
9568 case OMPD_taskgroup:
9569 case OMPD_distribute:
9570 case OMPD_ordered:
9571 case OMPD_atomic:
9572 case OMPD_distribute_simd:
9573 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009574 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009575 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9576 case OMPD_unknown:
9577 llvm_unreachable("Unknown OpenMP directive");
9578 }
9579 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009580 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009581 switch (DKind) {
9582 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009583 case OMPD_teams_distribute_parallel_for_simd:
9584 case OMPD_teams_distribute:
9585 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009586 case OMPD_target_teams_distribute_parallel_for:
9587 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009588 case OMPD_target_teams_distribute:
9589 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009590 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009591 break;
9592 case OMPD_distribute_parallel_for:
9593 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009594 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009595 case OMPD_distribute_simd:
9596 // Do not capture thread_limit-clause expressions.
9597 break;
9598 case OMPD_parallel_for:
9599 case OMPD_parallel_for_simd:
9600 case OMPD_target_parallel_for_simd:
9601 case OMPD_target_parallel_for:
9602 case OMPD_task:
9603 case OMPD_taskloop:
9604 case OMPD_taskloop_simd:
9605 case OMPD_target_data:
9606 case OMPD_target_enter_data:
9607 case OMPD_target_exit_data:
9608 case OMPD_target_update:
9609 case OMPD_teams:
9610 case OMPD_target:
9611 case OMPD_target_simd:
9612 case OMPD_target_parallel:
9613 case OMPD_cancel:
9614 case OMPD_parallel:
9615 case OMPD_parallel_sections:
9616 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009617 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009618 case OMPD_taskyield:
9619 case OMPD_barrier:
9620 case OMPD_taskwait:
9621 case OMPD_cancellation_point:
9622 case OMPD_flush:
9623 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009624 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009625 case OMPD_declare_simd:
9626 case OMPD_declare_target:
9627 case OMPD_end_declare_target:
9628 case OMPD_simd:
9629 case OMPD_for:
9630 case OMPD_for_simd:
9631 case OMPD_sections:
9632 case OMPD_section:
9633 case OMPD_single:
9634 case OMPD_master:
9635 case OMPD_critical:
9636 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009637 case OMPD_ordered:
9638 case OMPD_atomic:
9639 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009640 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009641 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9642 case OMPD_unknown:
9643 llvm_unreachable("Unknown OpenMP directive");
9644 }
9645 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009646 case OMPC_device:
9647 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009648 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009649 case OMPD_target_enter_data:
9650 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009651 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009652 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009653 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009654 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009655 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009656 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009657 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009658 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009659 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009660 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009661 CaptureRegion = OMPD_task;
9662 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009663 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009664 // Do not capture device-clause expressions.
9665 break;
9666 case OMPD_teams_distribute_parallel_for:
9667 case OMPD_teams_distribute_parallel_for_simd:
9668 case OMPD_teams:
9669 case OMPD_teams_distribute:
9670 case OMPD_teams_distribute_simd:
9671 case OMPD_distribute_parallel_for:
9672 case OMPD_distribute_parallel_for_simd:
9673 case OMPD_task:
9674 case OMPD_taskloop:
9675 case OMPD_taskloop_simd:
9676 case OMPD_cancel:
9677 case OMPD_parallel:
9678 case OMPD_parallel_sections:
9679 case OMPD_parallel_for:
9680 case OMPD_parallel_for_simd:
9681 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009682 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009683 case OMPD_taskyield:
9684 case OMPD_barrier:
9685 case OMPD_taskwait:
9686 case OMPD_cancellation_point:
9687 case OMPD_flush:
9688 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009689 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009690 case OMPD_declare_simd:
9691 case OMPD_declare_target:
9692 case OMPD_end_declare_target:
9693 case OMPD_simd:
9694 case OMPD_for:
9695 case OMPD_for_simd:
9696 case OMPD_sections:
9697 case OMPD_section:
9698 case OMPD_single:
9699 case OMPD_master:
9700 case OMPD_critical:
9701 case OMPD_taskgroup:
9702 case OMPD_distribute:
9703 case OMPD_ordered:
9704 case OMPD_atomic:
9705 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009706 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009707 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9708 case OMPD_unknown:
9709 llvm_unreachable("Unknown OpenMP directive");
9710 }
9711 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009712 case OMPC_firstprivate:
9713 case OMPC_lastprivate:
9714 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009715 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009716 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009717 case OMPC_linear:
9718 case OMPC_default:
9719 case OMPC_proc_bind:
9720 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009721 case OMPC_safelen:
9722 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009723 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009724 case OMPC_collapse:
9725 case OMPC_private:
9726 case OMPC_shared:
9727 case OMPC_aligned:
9728 case OMPC_copyin:
9729 case OMPC_copyprivate:
9730 case OMPC_ordered:
9731 case OMPC_nowait:
9732 case OMPC_untied:
9733 case OMPC_mergeable:
9734 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009735 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009736 case OMPC_flush:
9737 case OMPC_read:
9738 case OMPC_write:
9739 case OMPC_update:
9740 case OMPC_capture:
9741 case OMPC_seq_cst:
9742 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009743 case OMPC_threads:
9744 case OMPC_simd:
9745 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009746 case OMPC_priority:
9747 case OMPC_grainsize:
9748 case OMPC_nogroup:
9749 case OMPC_num_tasks:
9750 case OMPC_hint:
9751 case OMPC_defaultmap:
9752 case OMPC_unknown:
9753 case OMPC_uniform:
9754 case OMPC_to:
9755 case OMPC_from:
9756 case OMPC_use_device_ptr:
9757 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009758 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009759 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009760 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009761 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009762 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009763 llvm_unreachable("Unexpected OpenMP clause.");
9764 }
9765 return CaptureRegion;
9766}
9767
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009768OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9769 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009770 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009771 SourceLocation NameModifierLoc,
9772 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009773 SourceLocation EndLoc) {
9774 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009775 Stmt *HelperValStmt = nullptr;
9776 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009777 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9778 !Condition->isInstantiationDependent() &&
9779 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009780 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009781 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009782 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009783
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009784 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009785
9786 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9787 CaptureRegion =
9788 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009789 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009790 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009791 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009792 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9793 HelperValStmt = buildPreInits(Context, Captures);
9794 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009795 }
9796
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009797 return new (Context)
9798 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9799 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009800}
9801
Alexey Bataev3778b602014-07-17 07:32:53 +00009802OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9803 SourceLocation StartLoc,
9804 SourceLocation LParenLoc,
9805 SourceLocation EndLoc) {
9806 Expr *ValExpr = Condition;
9807 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9808 !Condition->isInstantiationDependent() &&
9809 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009810 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009811 if (Val.isInvalid())
9812 return nullptr;
9813
Richard Smith03a4aa32016-06-23 19:02:52 +00009814 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009815 }
9816
9817 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9818}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009819ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9820 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009821 if (!Op)
9822 return ExprError();
9823
9824 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9825 public:
9826 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009827 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009828 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9829 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009830 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9831 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009832 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9833 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009834 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9835 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009836 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9837 QualType T,
9838 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009839 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9840 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009841 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9842 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009843 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009844 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009845 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009846 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9847 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009848 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9849 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009850 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9851 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009852 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009853 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009854 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009855 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9856 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009857 llvm_unreachable("conversion functions are permitted");
9858 }
9859 } ConvertDiagnoser;
9860 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9861}
9862
Alexey Bataeve3727102018-04-18 15:57:46 +00009863static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009864 OpenMPClauseKind CKind,
9865 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009866 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9867 !ValExpr->isInstantiationDependent()) {
9868 SourceLocation Loc = ValExpr->getExprLoc();
9869 ExprResult Value =
9870 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9871 if (Value.isInvalid())
9872 return false;
9873
9874 ValExpr = Value.get();
9875 // The expression must evaluate to a non-negative integer value.
9876 llvm::APSInt Result;
9877 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009878 Result.isSigned() &&
9879 !((!StrictlyPositive && Result.isNonNegative()) ||
9880 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009881 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009882 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9883 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009884 return false;
9885 }
9886 }
9887 return true;
9888}
9889
Alexey Bataev568a8332014-03-06 06:15:19 +00009890OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9891 SourceLocation StartLoc,
9892 SourceLocation LParenLoc,
9893 SourceLocation EndLoc) {
9894 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009895 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009896
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009897 // OpenMP [2.5, Restrictions]
9898 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009899 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009900 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009901 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009902
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009903 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009904 OpenMPDirectiveKind CaptureRegion =
9905 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9906 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009907 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009908 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009909 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9910 HelperValStmt = buildPreInits(Context, Captures);
9911 }
9912
9913 return new (Context) OMPNumThreadsClause(
9914 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009915}
9916
Alexey Bataev62c87d22014-03-21 04:51:18 +00009917ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009918 OpenMPClauseKind CKind,
9919 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009920 if (!E)
9921 return ExprError();
9922 if (E->isValueDependent() || E->isTypeDependent() ||
9923 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009924 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009925 llvm::APSInt Result;
9926 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9927 if (ICE.isInvalid())
9928 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009929 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9930 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009931 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009932 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9933 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009934 return ExprError();
9935 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009936 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9937 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9938 << E->getSourceRange();
9939 return ExprError();
9940 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009941 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9942 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009943 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009944 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009945 return ICE;
9946}
9947
9948OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9949 SourceLocation LParenLoc,
9950 SourceLocation EndLoc) {
9951 // OpenMP [2.8.1, simd construct, Description]
9952 // The parameter of the safelen clause must be a constant
9953 // positive integer expression.
9954 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9955 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009956 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009957 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009958 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009959}
9960
Alexey Bataev66b15b52015-08-21 11:14:16 +00009961OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9962 SourceLocation LParenLoc,
9963 SourceLocation EndLoc) {
9964 // OpenMP [2.8.1, simd construct, Description]
9965 // The parameter of the simdlen clause must be a constant
9966 // positive integer expression.
9967 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9968 if (Simdlen.isInvalid())
9969 return nullptr;
9970 return new (Context)
9971 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9972}
9973
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009974/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009975static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9976 DSAStackTy *Stack) {
9977 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009978 if (!OMPAllocatorHandleT.isNull())
9979 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009980 // Build the predefined allocator expressions.
9981 bool ErrorFound = false;
9982 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9983 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9984 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9985 StringRef Allocator =
9986 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9987 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9988 auto *VD = dyn_cast_or_null<ValueDecl>(
9989 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9990 if (!VD) {
9991 ErrorFound = true;
9992 break;
9993 }
9994 QualType AllocatorType =
9995 VD->getType().getNonLValueExprType(S.getASTContext());
9996 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9997 if (!Res.isUsable()) {
9998 ErrorFound = true;
9999 break;
10000 }
10001 if (OMPAllocatorHandleT.isNull())
10002 OMPAllocatorHandleT = AllocatorType;
10003 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
10004 ErrorFound = true;
10005 break;
10006 }
10007 Stack->setAllocator(AllocatorKind, Res.get());
10008 }
10009 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010010 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
10011 return false;
10012 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000010013 OMPAllocatorHandleT.addConst();
10014 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010015 return true;
10016}
10017
10018OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
10019 SourceLocation LParenLoc,
10020 SourceLocation EndLoc) {
10021 // OpenMP [2.11.3, allocate Directive, Description]
10022 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010023 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010024 return nullptr;
10025
10026 ExprResult Allocator = DefaultLvalueConversion(A);
10027 if (Allocator.isInvalid())
10028 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010029 Allocator = PerformImplicitConversion(Allocator.get(),
10030 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010031 Sema::AA_Initializing,
10032 /*AllowExplicit=*/true);
10033 if (Allocator.isInvalid())
10034 return nullptr;
10035 return new (Context)
10036 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
10037}
10038
Alexander Musman64d33f12014-06-04 07:53:32 +000010039OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
10040 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000010041 SourceLocation LParenLoc,
10042 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000010043 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010044 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000010045 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010046 // The parameter of the collapse clause must be a constant
10047 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000010048 ExprResult NumForLoopsResult =
10049 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
10050 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000010051 return nullptr;
10052 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000010053 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000010054}
10055
Alexey Bataev10e775f2015-07-30 11:36:16 +000010056OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
10057 SourceLocation EndLoc,
10058 SourceLocation LParenLoc,
10059 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000010060 // OpenMP [2.7.1, loop construct, Description]
10061 // OpenMP [2.8.1, simd construct, Description]
10062 // OpenMP [2.9.6, distribute construct, Description]
10063 // The parameter of the ordered clause must be a constant
10064 // positive integer expression if any.
10065 if (NumForLoops && LParenLoc.isValid()) {
10066 ExprResult NumForLoopsResult =
10067 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
10068 if (NumForLoopsResult.isInvalid())
10069 return nullptr;
10070 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010071 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000010072 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010073 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000010074 auto *Clause = OMPOrderedClause::Create(
10075 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
10076 StartLoc, LParenLoc, EndLoc);
10077 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
10078 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010079}
10080
Alexey Bataeved09d242014-05-28 05:53:51 +000010081OMPClause *Sema::ActOnOpenMPSimpleClause(
10082 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
10083 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010084 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010085 switch (Kind) {
10086 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010087 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000010088 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
10089 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010090 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010091 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000010092 Res = ActOnOpenMPProcBindClause(
10093 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
10094 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010095 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010096 case OMPC_atomic_default_mem_order:
10097 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
10098 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
10099 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10100 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010101 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010102 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010103 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010104 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010105 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010106 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010107 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010108 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010109 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010110 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010111 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010112 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010113 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010114 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010115 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010116 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010117 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010118 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010119 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010120 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010121 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010122 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010123 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010124 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010125 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010126 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010127 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010128 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010129 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010130 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010131 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010132 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010133 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010134 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010135 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010136 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010137 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010138 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010139 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010140 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010141 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010142 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010143 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010144 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010145 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010146 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010147 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010148 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010149 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010150 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010151 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010152 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010153 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010154 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010155 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010156 llvm_unreachable("Clause is not allowed.");
10157 }
10158 return Res;
10159}
10160
Alexey Bataev6402bca2015-12-28 07:25:51 +000010161static std::string
10162getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
10163 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010164 SmallString<256> Buffer;
10165 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000010166 unsigned Bound = Last >= 2 ? Last - 2 : 0;
10167 unsigned Skipped = Exclude.size();
10168 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000010169 for (unsigned I = First; I < Last; ++I) {
10170 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010171 --Skipped;
10172 continue;
10173 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010174 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
10175 if (I == Bound - Skipped)
10176 Out << " or ";
10177 else if (I != Bound + 1 - Skipped)
10178 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000010179 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010180 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000010181}
10182
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010183OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10184 SourceLocation KindKwLoc,
10185 SourceLocation StartLoc,
10186 SourceLocation LParenLoc,
10187 SourceLocation EndLoc) {
10188 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000010189 static_assert(OMPC_DEFAULT_unknown > 0,
10190 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010191 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010192 << getListOfPossibleValues(OMPC_default, /*First=*/0,
10193 /*Last=*/OMPC_DEFAULT_unknown)
10194 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010195 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010196 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000010197 switch (Kind) {
10198 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010199 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010200 break;
10201 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010202 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010203 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010204 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010205 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000010206 break;
10207 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010208 return new (Context)
10209 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010210}
10211
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010212OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
10213 SourceLocation KindKwLoc,
10214 SourceLocation StartLoc,
10215 SourceLocation LParenLoc,
10216 SourceLocation EndLoc) {
10217 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010218 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010219 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
10220 /*Last=*/OMPC_PROC_BIND_unknown)
10221 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010222 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010223 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010224 return new (Context)
10225 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010226}
10227
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010228OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
10229 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
10230 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
10231 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
10232 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10233 << getListOfPossibleValues(
10234 OMPC_atomic_default_mem_order, /*First=*/0,
10235 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
10236 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
10237 return nullptr;
10238 }
10239 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
10240 LParenLoc, EndLoc);
10241}
10242
Alexey Bataev56dafe82014-06-20 07:16:17 +000010243OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010244 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010245 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010246 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010247 SourceLocation EndLoc) {
10248 OMPClause *Res = nullptr;
10249 switch (Kind) {
10250 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010251 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
10252 assert(Argument.size() == NumberOfElements &&
10253 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010254 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010255 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
10256 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
10257 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
10258 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
10259 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010260 break;
10261 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010262 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
10263 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
10264 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
10265 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010266 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010267 case OMPC_dist_schedule:
10268 Res = ActOnOpenMPDistScheduleClause(
10269 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
10270 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
10271 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010272 case OMPC_defaultmap:
10273 enum { Modifier, DefaultmapKind };
10274 Res = ActOnOpenMPDefaultmapClause(
10275 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
10276 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000010277 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
10278 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010279 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000010280 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010281 case OMPC_num_threads:
10282 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010283 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010284 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010285 case OMPC_collapse:
10286 case OMPC_default:
10287 case OMPC_proc_bind:
10288 case OMPC_private:
10289 case OMPC_firstprivate:
10290 case OMPC_lastprivate:
10291 case OMPC_shared:
10292 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010293 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010294 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010295 case OMPC_linear:
10296 case OMPC_aligned:
10297 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010298 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010299 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010300 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010301 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010302 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010303 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010304 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010305 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010306 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010307 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010308 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010309 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010310 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010311 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010312 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010313 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010314 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010315 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010316 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010317 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010318 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010319 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010320 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010321 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010322 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010323 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010324 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010325 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010326 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010327 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010328 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010329 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010330 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010331 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010332 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010333 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010334 llvm_unreachable("Clause is not allowed.");
10335 }
10336 return Res;
10337}
10338
Alexey Bataev6402bca2015-12-28 07:25:51 +000010339static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
10340 OpenMPScheduleClauseModifier M2,
10341 SourceLocation M1Loc, SourceLocation M2Loc) {
10342 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
10343 SmallVector<unsigned, 2> Excluded;
10344 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
10345 Excluded.push_back(M2);
10346 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
10347 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
10348 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
10349 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
10350 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
10351 << getListOfPossibleValues(OMPC_schedule,
10352 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
10353 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10354 Excluded)
10355 << getOpenMPClauseName(OMPC_schedule);
10356 return true;
10357 }
10358 return false;
10359}
10360
Alexey Bataev56dafe82014-06-20 07:16:17 +000010361OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010362 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010363 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010364 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10365 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
10366 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
10367 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
10368 return nullptr;
10369 // OpenMP, 2.7.1, Loop Construct, Restrictions
10370 // Either the monotonic modifier or the nonmonotonic modifier can be specified
10371 // but not both.
10372 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
10373 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
10374 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
10375 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
10376 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
10377 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
10378 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
10379 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
10380 return nullptr;
10381 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010382 if (Kind == OMPC_SCHEDULE_unknown) {
10383 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000010384 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
10385 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
10386 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10387 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10388 Exclude);
10389 } else {
10390 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10391 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010392 }
10393 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10394 << Values << getOpenMPClauseName(OMPC_schedule);
10395 return nullptr;
10396 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000010397 // OpenMP, 2.7.1, Loop Construct, Restrictions
10398 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
10399 // schedule(guided).
10400 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
10401 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
10402 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
10403 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
10404 diag::err_omp_schedule_nonmonotonic_static);
10405 return nullptr;
10406 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010407 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010408 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000010409 if (ChunkSize) {
10410 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10411 !ChunkSize->isInstantiationDependent() &&
10412 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010413 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000010414 ExprResult Val =
10415 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10416 if (Val.isInvalid())
10417 return nullptr;
10418
10419 ValExpr = Val.get();
10420
10421 // OpenMP [2.7.1, Restrictions]
10422 // chunk_size must be a loop invariant integer expression with a positive
10423 // value.
10424 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000010425 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10426 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10427 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000010428 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000010429 return nullptr;
10430 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000010431 } else if (getOpenMPCaptureRegionForClause(
10432 DSAStack->getCurrentDirective(), OMPC_schedule) !=
10433 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010434 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010435 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010436 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000010437 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10438 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010439 }
10440 }
10441 }
10442
Alexey Bataev6402bca2015-12-28 07:25:51 +000010443 return new (Context)
10444 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000010445 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010446}
10447
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010448OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
10449 SourceLocation StartLoc,
10450 SourceLocation EndLoc) {
10451 OMPClause *Res = nullptr;
10452 switch (Kind) {
10453 case OMPC_ordered:
10454 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
10455 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000010456 case OMPC_nowait:
10457 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
10458 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010459 case OMPC_untied:
10460 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
10461 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010462 case OMPC_mergeable:
10463 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
10464 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010465 case OMPC_read:
10466 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
10467 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000010468 case OMPC_write:
10469 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
10470 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000010471 case OMPC_update:
10472 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
10473 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000010474 case OMPC_capture:
10475 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
10476 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010477 case OMPC_seq_cst:
10478 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
10479 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000010480 case OMPC_threads:
10481 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
10482 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010483 case OMPC_simd:
10484 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
10485 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000010486 case OMPC_nogroup:
10487 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
10488 break;
Kelvin Li1408f912018-09-26 04:28:39 +000010489 case OMPC_unified_address:
10490 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
10491 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000010492 case OMPC_unified_shared_memory:
10493 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10494 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010495 case OMPC_reverse_offload:
10496 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
10497 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010498 case OMPC_dynamic_allocators:
10499 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
10500 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010501 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010502 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010503 case OMPC_num_threads:
10504 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010505 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010506 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010507 case OMPC_collapse:
10508 case OMPC_schedule:
10509 case OMPC_private:
10510 case OMPC_firstprivate:
10511 case OMPC_lastprivate:
10512 case OMPC_shared:
10513 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010514 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010515 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010516 case OMPC_linear:
10517 case OMPC_aligned:
10518 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010519 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010520 case OMPC_default:
10521 case OMPC_proc_bind:
10522 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010523 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010524 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010525 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010526 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010527 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010528 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010529 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010530 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010531 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000010532 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010533 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010534 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010535 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010536 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010537 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010538 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010539 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010540 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010541 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010542 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010543 llvm_unreachable("Clause is not allowed.");
10544 }
10545 return Res;
10546}
10547
Alexey Bataev236070f2014-06-20 11:19:47 +000010548OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10549 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000010550 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000010551 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10552}
10553
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010554OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10555 SourceLocation EndLoc) {
10556 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10557}
10558
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010559OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10560 SourceLocation EndLoc) {
10561 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10562}
10563
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010564OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10565 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010566 return new (Context) OMPReadClause(StartLoc, EndLoc);
10567}
10568
Alexey Bataevdea47612014-07-23 07:46:59 +000010569OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10570 SourceLocation EndLoc) {
10571 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10572}
10573
Alexey Bataev67a4f222014-07-23 10:25:33 +000010574OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10575 SourceLocation EndLoc) {
10576 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10577}
10578
Alexey Bataev459dec02014-07-24 06:46:57 +000010579OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10580 SourceLocation EndLoc) {
10581 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10582}
10583
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010584OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10585 SourceLocation EndLoc) {
10586 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10587}
10588
Alexey Bataev346265e2015-09-25 10:37:12 +000010589OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10590 SourceLocation EndLoc) {
10591 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10592}
10593
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010594OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10595 SourceLocation EndLoc) {
10596 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10597}
10598
Alexey Bataevb825de12015-12-07 10:51:44 +000010599OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10600 SourceLocation EndLoc) {
10601 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10602}
10603
Kelvin Li1408f912018-09-26 04:28:39 +000010604OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10605 SourceLocation EndLoc) {
10606 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10607}
10608
Patrick Lyster4a370b92018-10-01 13:47:43 +000010609OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10610 SourceLocation EndLoc) {
10611 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10612}
10613
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010614OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10615 SourceLocation EndLoc) {
10616 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10617}
10618
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010619OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10620 SourceLocation EndLoc) {
10621 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10622}
10623
Alexey Bataevc5e02582014-06-16 07:08:35 +000010624OMPClause *Sema::ActOnOpenMPVarListClause(
10625 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010626 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10627 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10628 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010629 OpenMPLinearClauseKind LinKind,
10630 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010631 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10632 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10633 SourceLocation StartLoc = Locs.StartLoc;
10634 SourceLocation LParenLoc = Locs.LParenLoc;
10635 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010636 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010637 switch (Kind) {
10638 case OMPC_private:
10639 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10640 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010641 case OMPC_firstprivate:
10642 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10643 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010644 case OMPC_lastprivate:
10645 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10646 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010647 case OMPC_shared:
10648 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10649 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010650 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010651 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010652 EndLoc, ReductionOrMapperIdScopeSpec,
10653 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010654 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010655 case OMPC_task_reduction:
10656 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010657 EndLoc, ReductionOrMapperIdScopeSpec,
10658 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010659 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010660 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010661 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10662 EndLoc, ReductionOrMapperIdScopeSpec,
10663 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010664 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010665 case OMPC_linear:
10666 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010667 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010668 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010669 case OMPC_aligned:
10670 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10671 ColonLoc, EndLoc);
10672 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010673 case OMPC_copyin:
10674 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10675 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010676 case OMPC_copyprivate:
10677 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10678 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010679 case OMPC_flush:
10680 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10681 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010682 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010683 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010684 StartLoc, LParenLoc, EndLoc);
10685 break;
10686 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010687 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10688 ReductionOrMapperIdScopeSpec,
10689 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10690 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010691 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010692 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010693 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10694 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010695 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010696 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010697 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10698 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010699 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010700 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010701 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010702 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010703 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010704 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010705 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000010706 case OMPC_allocate:
10707 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10708 ColonLoc, EndLoc);
10709 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010710 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010711 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010712 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010713 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010714 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010715 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010716 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010717 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010718 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010719 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010720 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010721 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010722 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010723 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010724 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010725 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010726 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010727 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010728 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010729 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010730 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010731 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010732 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010733 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010734 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010735 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010736 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010737 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010738 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010739 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010740 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010741 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010742 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010743 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010744 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010745 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010746 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010747 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010748 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010749 llvm_unreachable("Clause is not allowed.");
10750 }
10751 return Res;
10752}
10753
Alexey Bataev90c228f2016-02-08 09:29:13 +000010754ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010755 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010756 ExprResult Res = BuildDeclRefExpr(
10757 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10758 if (!Res.isUsable())
10759 return ExprError();
10760 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10761 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10762 if (!Res.isUsable())
10763 return ExprError();
10764 }
10765 if (VK != VK_LValue && Res.get()->isGLValue()) {
10766 Res = DefaultLvalueConversion(Res.get());
10767 if (!Res.isUsable())
10768 return ExprError();
10769 }
10770 return Res;
10771}
10772
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010773OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10774 SourceLocation StartLoc,
10775 SourceLocation LParenLoc,
10776 SourceLocation EndLoc) {
10777 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010778 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010779 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010780 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010781 SourceLocation ELoc;
10782 SourceRange ERange;
10783 Expr *SimpleRefExpr = RefExpr;
10784 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010785 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010786 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010787 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010788 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010789 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010790 ValueDecl *D = Res.first;
10791 if (!D)
10792 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010793
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010794 QualType Type = D->getType();
10795 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010796
10797 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10798 // A variable that appears in a private clause must not have an incomplete
10799 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010800 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010801 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010802 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010803
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010804 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10805 // A variable that is privatized must not have a const-qualified type
10806 // unless it is of class type with a mutable member. This restriction does
10807 // not apply to the firstprivate clause.
10808 //
10809 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10810 // A variable that appears in a private clause must not have a
10811 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010812 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010813 continue;
10814
Alexey Bataev758e55e2013-09-06 18:03:48 +000010815 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10816 // in a Construct]
10817 // Variables with the predetermined data-sharing attributes may not be
10818 // listed in data-sharing attributes clauses, except for the cases
10819 // listed below. For these exceptions only, listing a predetermined
10820 // variable in a data-sharing attribute clause is allowed and overrides
10821 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010822 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010823 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010824 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10825 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010826 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010827 continue;
10828 }
10829
Alexey Bataeve3727102018-04-18 15:57:46 +000010830 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010831 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010832 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010833 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010834 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10835 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010836 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010837 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010838 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010839 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010840 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010841 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010842 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010843 continue;
10844 }
10845
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010846 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10847 // A list item cannot appear in both a map clause and a data-sharing
10848 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010849 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010850 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010851 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010852 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010853 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10854 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10855 ConflictKind = WhereFoundClauseKind;
10856 return true;
10857 })) {
10858 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010859 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010860 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010861 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010862 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010863 continue;
10864 }
10865 }
10866
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010867 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10868 // A variable of class type (or array thereof) that appears in a private
10869 // clause requires an accessible, unambiguous default constructor for the
10870 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010871 // Generate helper private variable and initialize it with the default
10872 // value. The address of the original variable is replaced by the address of
10873 // the new private variable in CodeGen. This new variable is not added to
10874 // IdResolver, so the code in the OpenMP region uses original variable for
10875 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010876 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010877 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010878 buildVarDecl(*this, ELoc, Type, D->getName(),
10879 D->hasAttrs() ? &D->getAttrs() : nullptr,
10880 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010881 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010882 if (VDPrivate->isInvalidDecl())
10883 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010884 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010885 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010886
Alexey Bataev90c228f2016-02-08 09:29:13 +000010887 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010888 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010889 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010890 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010891 Vars.push_back((VD || CurContext->isDependentContext())
10892 ? RefExpr->IgnoreParens()
10893 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010894 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010895 }
10896
Alexey Bataeved09d242014-05-28 05:53:51 +000010897 if (Vars.empty())
10898 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010899
Alexey Bataev03b340a2014-10-21 03:16:40 +000010900 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10901 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010902}
10903
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010904namespace {
10905class DiagsUninitializedSeveretyRAII {
10906private:
10907 DiagnosticsEngine &Diags;
10908 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010909 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010910
10911public:
10912 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10913 bool IsIgnored)
10914 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10915 if (!IsIgnored) {
10916 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10917 /*Map*/ diag::Severity::Ignored, Loc);
10918 }
10919 }
10920 ~DiagsUninitializedSeveretyRAII() {
10921 if (!IsIgnored)
10922 Diags.popMappings(SavedLoc);
10923 }
10924};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010925}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010926
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010927OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10928 SourceLocation StartLoc,
10929 SourceLocation LParenLoc,
10930 SourceLocation EndLoc) {
10931 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010932 SmallVector<Expr *, 8> PrivateCopies;
10933 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010934 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010935 bool IsImplicitClause =
10936 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010937 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010938
Alexey Bataeve3727102018-04-18 15:57:46 +000010939 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010940 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010941 SourceLocation ELoc;
10942 SourceRange ERange;
10943 Expr *SimpleRefExpr = RefExpr;
10944 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010945 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010946 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010947 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010948 PrivateCopies.push_back(nullptr);
10949 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010950 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010951 ValueDecl *D = Res.first;
10952 if (!D)
10953 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010954
Alexey Bataev60da77e2016-02-29 05:54:20 +000010955 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010956 QualType Type = D->getType();
10957 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010958
10959 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10960 // A variable that appears in a private clause must not have an incomplete
10961 // type or a reference type.
10962 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010963 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010964 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010965 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010966
10967 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10968 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010969 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010970 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010971 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010972
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010973 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010974 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010975 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010976 DSAStackTy::DSAVarData DVar =
10977 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010978 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010979 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010980 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010981 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10982 // A list item that specifies a given variable may not appear in more
10983 // than one clause on the same directive, except that a variable may be
10984 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010985 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10986 // A list item may appear in a firstprivate or lastprivate clause but not
10987 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010988 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010989 (isOpenMPDistributeDirective(CurrDir) ||
10990 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010991 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010992 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010993 << getOpenMPClauseName(DVar.CKind)
10994 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010995 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010996 continue;
10997 }
10998
10999 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11000 // in a Construct]
11001 // Variables with the predetermined data-sharing attributes may not be
11002 // listed in data-sharing attributes clauses, except for the cases
11003 // listed below. For these exceptions only, listing a predetermined
11004 // variable in a data-sharing attribute clause is allowed and overrides
11005 // the variable's predetermined data-sharing attributes.
11006 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11007 // in a Construct, C/C++, p.2]
11008 // Variables with const-qualified type having no mutable member may be
11009 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000011010 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011011 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
11012 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011013 << getOpenMPClauseName(DVar.CKind)
11014 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011015 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011016 continue;
11017 }
11018
11019 // OpenMP [2.9.3.4, Restrictions, p.2]
11020 // A list item that is private within a parallel region must not appear
11021 // in a firstprivate clause on a worksharing construct if any of the
11022 // worksharing regions arising from the worksharing construct ever bind
11023 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011024 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11025 // A list item that is private within a teams region must not appear in a
11026 // firstprivate clause on a distribute construct if any of the distribute
11027 // regions arising from the distribute construct ever bind to any of the
11028 // teams regions arising from the teams construct.
11029 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11030 // A list item that appears in a reduction clause of a teams construct
11031 // must not appear in a firstprivate clause on a distribute construct if
11032 // any of the distribute regions arising from the distribute construct
11033 // ever bind to any of the teams regions arising from the teams construct.
11034 if ((isOpenMPWorksharingDirective(CurrDir) ||
11035 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011036 !isOpenMPParallelDirective(CurrDir) &&
11037 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011038 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011039 if (DVar.CKind != OMPC_shared &&
11040 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011041 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011042 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000011043 Diag(ELoc, diag::err_omp_required_access)
11044 << getOpenMPClauseName(OMPC_firstprivate)
11045 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011046 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011047 continue;
11048 }
11049 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011050 // OpenMP [2.9.3.4, Restrictions, p.3]
11051 // A list item that appears in a reduction clause of a parallel construct
11052 // must not appear in a firstprivate clause on a worksharing or task
11053 // construct if any of the worksharing or task regions arising from the
11054 // worksharing or task construct ever bind to any of the parallel regions
11055 // arising from the parallel construct.
11056 // OpenMP [2.9.3.4, Restrictions, p.4]
11057 // A list item that appears in a reduction clause in worksharing
11058 // construct must not appear in a firstprivate clause in a task construct
11059 // encountered during execution of any of the worksharing regions arising
11060 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000011061 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011062 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011063 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
11064 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011065 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011066 isOpenMPWorksharingDirective(K) ||
11067 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011068 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011069 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011070 if (DVar.CKind == OMPC_reduction &&
11071 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011072 isOpenMPWorksharingDirective(DVar.DKind) ||
11073 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011074 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
11075 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000011076 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011077 continue;
11078 }
11079 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000011080
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011081 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11082 // A list item cannot appear in both a map clause and a data-sharing
11083 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000011084 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011085 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011086 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011087 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000011088 [&ConflictKind](
11089 OMPClauseMappableExprCommon::MappableExprComponentListRef,
11090 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000011091 ConflictKind = WhereFoundClauseKind;
11092 return true;
11093 })) {
11094 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011095 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000011096 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011097 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000011098 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011099 continue;
11100 }
11101 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011102 }
11103
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011104 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011105 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000011106 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011107 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11108 << getOpenMPClauseName(OMPC_firstprivate) << Type
11109 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11110 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011111 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011112 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011113 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011114 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000011115 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011116 continue;
11117 }
11118
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011119 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011120 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011121 buildVarDecl(*this, ELoc, Type, D->getName(),
11122 D->hasAttrs() ? &D->getAttrs() : nullptr,
11123 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011124 // Generate helper private variable and initialize it with the value of the
11125 // original variable. The address of the original variable is replaced by
11126 // the address of the new private variable in the CodeGen. This new variable
11127 // is not added to IdResolver, so the code in the OpenMP region uses
11128 // original variable for proper diagnostics and variable capturing.
11129 Expr *VDInitRefExpr = nullptr;
11130 // For arrays generate initializer for single element and replace it by the
11131 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011132 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011133 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011134 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011135 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011136 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011137 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011138 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
11139 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000011140 InitializedEntity Entity =
11141 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011142 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
11143
11144 InitializationSequence InitSeq(*this, Entity, Kind, Init);
11145 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
11146 if (Result.isInvalid())
11147 VDPrivate->setInvalidDecl();
11148 else
11149 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011150 // Remove temp variable declaration.
11151 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011152 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000011153 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
11154 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000011155 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11156 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000011157 AddInitializerToDecl(VDPrivate,
11158 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011159 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011160 }
11161 if (VDPrivate->isInvalidDecl()) {
11162 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011163 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011164 diag::note_omp_task_predetermined_firstprivate_here);
11165 }
11166 continue;
11167 }
11168 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011169 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000011170 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
11171 RefExpr->getExprLoc());
11172 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011173 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011174 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011175 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011176 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011177 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011178 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011179 ExprCaptures.push_back(Ref->getDecl());
11180 }
Alexey Bataev417089f2016-02-17 13:19:37 +000011181 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011182 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011183 Vars.push_back((VD || CurContext->isDependentContext())
11184 ? RefExpr->IgnoreParens()
11185 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011186 PrivateCopies.push_back(VDPrivateRefExpr);
11187 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011188 }
11189
Alexey Bataeved09d242014-05-28 05:53:51 +000011190 if (Vars.empty())
11191 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011192
11193 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011194 Vars, PrivateCopies, Inits,
11195 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011196}
11197
Alexander Musman1bb328c2014-06-04 13:06:39 +000011198OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
11199 SourceLocation StartLoc,
11200 SourceLocation LParenLoc,
11201 SourceLocation EndLoc) {
11202 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000011203 SmallVector<Expr *, 8> SrcExprs;
11204 SmallVector<Expr *, 8> DstExprs;
11205 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000011206 SmallVector<Decl *, 4> ExprCaptures;
11207 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000011208 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011209 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011210 SourceLocation ELoc;
11211 SourceRange ERange;
11212 Expr *SimpleRefExpr = RefExpr;
11213 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000011214 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011215 // It will be analyzed later.
11216 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011217 SrcExprs.push_back(nullptr);
11218 DstExprs.push_back(nullptr);
11219 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011220 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011221 ValueDecl *D = Res.first;
11222 if (!D)
11223 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011224
Alexey Bataev74caaf22016-02-20 04:09:36 +000011225 QualType Type = D->getType();
11226 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011227
11228 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
11229 // A variable that appears in a lastprivate clause must not have an
11230 // incomplete type or a reference type.
11231 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000011232 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000011233 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011234 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011235
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011236 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11237 // A variable that is privatized must not have a const-qualified type
11238 // unless it is of class type with a mutable member. This restriction does
11239 // not apply to the firstprivate clause.
11240 //
11241 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
11242 // A variable that appears in a lastprivate clause must not have a
11243 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011244 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011245 continue;
11246
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011247 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011248 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11249 // in a Construct]
11250 // Variables with the predetermined data-sharing attributes may not be
11251 // listed in data-sharing attributes clauses, except for the cases
11252 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011253 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11254 // A list item may appear in a firstprivate or lastprivate clause but not
11255 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000011256 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011257 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011258 (isOpenMPDistributeDirective(CurrDir) ||
11259 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000011260 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
11261 Diag(ELoc, diag::err_omp_wrong_dsa)
11262 << getOpenMPClauseName(DVar.CKind)
11263 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011264 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011265 continue;
11266 }
11267
Alexey Bataevf29276e2014-06-18 04:14:57 +000011268 // OpenMP [2.14.3.5, Restrictions, p.2]
11269 // A list item that is private within a parallel region, or that appears in
11270 // the reduction clause of a parallel construct, must not appear in a
11271 // lastprivate clause on a worksharing construct if any of the corresponding
11272 // worksharing regions ever binds to any of the corresponding parallel
11273 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000011274 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000011275 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011276 !isOpenMPParallelDirective(CurrDir) &&
11277 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000011278 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011279 if (DVar.CKind != OMPC_shared) {
11280 Diag(ELoc, diag::err_omp_required_access)
11281 << getOpenMPClauseName(OMPC_lastprivate)
11282 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011283 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011284 continue;
11285 }
11286 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011287
Alexander Musman1bb328c2014-06-04 13:06:39 +000011288 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000011289 // A variable of class type (or array thereof) that appears in a
11290 // lastprivate clause requires an accessible, unambiguous default
11291 // constructor for the class type, unless the list item is also specified
11292 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000011293 // A variable of class type (or array thereof) that appears in a
11294 // lastprivate clause requires an accessible, unambiguous copy assignment
11295 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000011296 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011297 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
11298 Type.getUnqualifiedType(), ".lastprivate.src",
11299 D->hasAttrs() ? &D->getAttrs() : nullptr);
11300 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000011301 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011302 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011303 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000011304 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011305 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000011306 // For arrays generate assignment operation for single element and replace
11307 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000011308 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
11309 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011310 if (AssignmentOp.isInvalid())
11311 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011312 AssignmentOp =
11313 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000011314 if (AssignmentOp.isInvalid())
11315 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011316
Alexey Bataev74caaf22016-02-20 04:09:36 +000011317 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011318 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011319 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011320 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011321 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011322 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011323 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011324 ExprCaptures.push_back(Ref->getDecl());
11325 }
11326 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000011327 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011328 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011329 ExprResult RefRes = DefaultLvalueConversion(Ref);
11330 if (!RefRes.isUsable())
11331 continue;
11332 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011333 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11334 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011335 if (!PostUpdateRes.isUsable())
11336 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011337 ExprPostUpdates.push_back(
11338 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011339 }
11340 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011341 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011342 Vars.push_back((VD || CurContext->isDependentContext())
11343 ? RefExpr->IgnoreParens()
11344 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000011345 SrcExprs.push_back(PseudoSrcExpr);
11346 DstExprs.push_back(PseudoDstExpr);
11347 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000011348 }
11349
11350 if (Vars.empty())
11351 return nullptr;
11352
11353 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000011354 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011355 buildPreInits(Context, ExprCaptures),
11356 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000011357}
11358
Alexey Bataev758e55e2013-09-06 18:03:48 +000011359OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11360 SourceLocation StartLoc,
11361 SourceLocation LParenLoc,
11362 SourceLocation EndLoc) {
11363 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011364 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011365 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011366 SourceLocation ELoc;
11367 SourceRange ERange;
11368 Expr *SimpleRefExpr = RefExpr;
11369 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011370 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000011371 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011372 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011373 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011374 ValueDecl *D = Res.first;
11375 if (!D)
11376 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011377
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011378 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011379 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11380 // in a Construct]
11381 // Variables with the predetermined data-sharing attributes may not be
11382 // listed in data-sharing attributes clauses, except for the cases
11383 // listed below. For these exceptions only, listing a predetermined
11384 // variable in a data-sharing attribute clause is allowed and overrides
11385 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011386 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000011387 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
11388 DVar.RefExpr) {
11389 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11390 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011391 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011392 continue;
11393 }
11394
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011395 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011396 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000011397 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011398 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011399 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
11400 ? RefExpr->IgnoreParens()
11401 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011402 }
11403
Alexey Bataeved09d242014-05-28 05:53:51 +000011404 if (Vars.empty())
11405 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011406
11407 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
11408}
11409
Alexey Bataevc5e02582014-06-16 07:08:35 +000011410namespace {
11411class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
11412 DSAStackTy *Stack;
11413
11414public:
11415 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011416 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
11417 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011418 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
11419 return false;
11420 if (DVar.CKind != OMPC_unknown)
11421 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011422 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011423 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011424 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011425 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011426 }
11427 return false;
11428 }
11429 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011430 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011431 if (Child && Visit(Child))
11432 return true;
11433 }
11434 return false;
11435 }
Alexey Bataev23b69422014-06-18 07:08:49 +000011436 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011437};
Alexey Bataev23b69422014-06-18 07:08:49 +000011438} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000011439
Alexey Bataev60da77e2016-02-29 05:54:20 +000011440namespace {
11441// Transform MemberExpression for specified FieldDecl of current class to
11442// DeclRefExpr to specified OMPCapturedExprDecl.
11443class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
11444 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000011445 ValueDecl *Field = nullptr;
11446 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011447
11448public:
11449 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
11450 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
11451
11452 ExprResult TransformMemberExpr(MemberExpr *E) {
11453 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
11454 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000011455 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011456 return CapturedExpr;
11457 }
11458 return BaseTransform::TransformMemberExpr(E);
11459 }
11460 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
11461};
11462} // namespace
11463
Alexey Bataev97d18bf2018-04-11 19:21:00 +000011464template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000011465static T filterLookupForUDReductionAndMapper(
11466 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011467 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011468 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011469 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011470 return Res;
11471 }
11472 }
11473 return T();
11474}
11475
Alexey Bataev43b90b72018-09-12 16:31:59 +000011476static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
11477 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
11478
11479 for (auto RD : D->redecls()) {
11480 // Don't bother with extra checks if we already know this one isn't visible.
11481 if (RD == D)
11482 continue;
11483
11484 auto ND = cast<NamedDecl>(RD);
11485 if (LookupResult::isVisible(SemaRef, ND))
11486 return ND;
11487 }
11488
11489 return nullptr;
11490}
11491
11492static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000011493argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000011494 SourceLocation Loc, QualType Ty,
11495 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11496 // Find all of the associated namespaces and classes based on the
11497 // arguments we have.
11498 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11499 Sema::AssociatedClassSet AssociatedClasses;
11500 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11501 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11502 AssociatedClasses);
11503
11504 // C++ [basic.lookup.argdep]p3:
11505 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11506 // and let Y be the lookup set produced by argument dependent
11507 // lookup (defined as follows). If X contains [...] then Y is
11508 // empty. Otherwise Y is the set of declarations found in the
11509 // namespaces associated with the argument types as described
11510 // below. The set of declarations found by the lookup of the name
11511 // is the union of X and Y.
11512 //
11513 // Here, we compute Y and add its members to the overloaded
11514 // candidate set.
11515 for (auto *NS : AssociatedNamespaces) {
11516 // When considering an associated namespace, the lookup is the
11517 // same as the lookup performed when the associated namespace is
11518 // used as a qualifier (3.4.3.2) except that:
11519 //
11520 // -- Any using-directives in the associated namespace are
11521 // ignored.
11522 //
11523 // -- Any namespace-scope friend functions declared in
11524 // associated classes are visible within their respective
11525 // namespaces even if they are not visible during an ordinary
11526 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011527 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011528 for (auto *D : R) {
11529 auto *Underlying = D;
11530 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11531 Underlying = USD->getTargetDecl();
11532
Michael Kruse4304e9d2019-02-19 16:38:20 +000011533 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11534 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011535 continue;
11536
11537 if (!SemaRef.isVisible(D)) {
11538 D = findAcceptableDecl(SemaRef, D);
11539 if (!D)
11540 continue;
11541 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11542 Underlying = USD->getTargetDecl();
11543 }
11544 Lookups.emplace_back();
11545 Lookups.back().addDecl(Underlying);
11546 }
11547 }
11548}
11549
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011550static ExprResult
11551buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11552 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11553 const DeclarationNameInfo &ReductionId, QualType Ty,
11554 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11555 if (ReductionIdScopeSpec.isInvalid())
11556 return ExprError();
11557 SmallVector<UnresolvedSet<8>, 4> Lookups;
11558 if (S) {
11559 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11560 Lookup.suppressDiagnostics();
11561 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011562 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011563 do {
11564 S = S->getParent();
11565 } while (S && !S->isDeclScope(D));
11566 if (S)
11567 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011568 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011569 Lookups.back().append(Lookup.begin(), Lookup.end());
11570 Lookup.clear();
11571 }
11572 } else if (auto *ULE =
11573 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11574 Lookups.push_back(UnresolvedSet<8>());
11575 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011576 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011577 if (D == PrevD)
11578 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011579 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011580 Lookups.back().addDecl(DRD);
11581 PrevD = D;
11582 }
11583 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011584 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11585 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011586 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011587 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011588 return !D->isInvalidDecl() &&
11589 (D->getType()->isDependentType() ||
11590 D->getType()->isInstantiationDependentType() ||
11591 D->getType()->containsUnexpandedParameterPack());
11592 })) {
11593 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011594 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011595 if (Set.empty())
11596 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011597 ResSet.append(Set.begin(), Set.end());
11598 // The last item marks the end of all declarations at the specified scope.
11599 ResSet.addDecl(Set[Set.size() - 1]);
11600 }
11601 return UnresolvedLookupExpr::Create(
11602 SemaRef.Context, /*NamingClass=*/nullptr,
11603 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11604 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11605 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011606 // Lookup inside the classes.
11607 // C++ [over.match.oper]p3:
11608 // For a unary operator @ with an operand of a type whose
11609 // cv-unqualified version is T1, and for a binary operator @ with
11610 // a left operand of a type whose cv-unqualified version is T1 and
11611 // a right operand of a type whose cv-unqualified version is T2,
11612 // three sets of candidate functions, designated member
11613 // candidates, non-member candidates and built-in candidates, are
11614 // constructed as follows:
11615 // -- If T1 is a complete class type or a class currently being
11616 // defined, the set of member candidates is the result of the
11617 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11618 // the set of member candidates is empty.
11619 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11620 Lookup.suppressDiagnostics();
11621 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11622 // Complete the type if it can be completed.
11623 // If the type is neither complete nor being defined, bail out now.
11624 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11625 TyRec->getDecl()->getDefinition()) {
11626 Lookup.clear();
11627 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11628 if (Lookup.empty()) {
11629 Lookups.emplace_back();
11630 Lookups.back().append(Lookup.begin(), Lookup.end());
11631 }
11632 }
11633 }
11634 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000011635 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000011636 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000011637 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11638 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11639 if (!D->isInvalidDecl() &&
11640 SemaRef.Context.hasSameType(D->getType(), Ty))
11641 return D;
11642 return nullptr;
11643 }))
11644 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11645 VK_LValue, Loc);
11646 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000011647 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11648 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11649 if (!D->isInvalidDecl() &&
11650 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11651 !Ty.isMoreQualifiedThan(D->getType()))
11652 return D;
11653 return nullptr;
11654 })) {
11655 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11656 /*DetectVirtual=*/false);
11657 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11658 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11659 VD->getType().getUnqualifiedType()))) {
11660 if (SemaRef.CheckBaseClassAccess(
11661 Loc, VD->getType(), Ty, Paths.front(),
11662 /*DiagID=*/0) != Sema::AR_inaccessible) {
11663 SemaRef.BuildBasePathArray(Paths, BasePath);
11664 return SemaRef.BuildDeclRefExpr(
11665 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11666 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011667 }
11668 }
11669 }
11670 }
11671 if (ReductionIdScopeSpec.isSet()) {
11672 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11673 return ExprError();
11674 }
11675 return ExprEmpty();
11676}
11677
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011678namespace {
11679/// Data for the reduction-based clauses.
11680struct ReductionData {
11681 /// List of original reduction items.
11682 SmallVector<Expr *, 8> Vars;
11683 /// List of private copies of the reduction items.
11684 SmallVector<Expr *, 8> Privates;
11685 /// LHS expressions for the reduction_op expressions.
11686 SmallVector<Expr *, 8> LHSs;
11687 /// RHS expressions for the reduction_op expressions.
11688 SmallVector<Expr *, 8> RHSs;
11689 /// Reduction operation expression.
11690 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011691 /// Taskgroup descriptors for the corresponding reduction items in
11692 /// in_reduction clauses.
11693 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011694 /// List of captures for clause.
11695 SmallVector<Decl *, 4> ExprCaptures;
11696 /// List of postupdate expressions.
11697 SmallVector<Expr *, 4> ExprPostUpdates;
11698 ReductionData() = delete;
11699 /// Reserves required memory for the reduction data.
11700 ReductionData(unsigned Size) {
11701 Vars.reserve(Size);
11702 Privates.reserve(Size);
11703 LHSs.reserve(Size);
11704 RHSs.reserve(Size);
11705 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011706 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011707 ExprCaptures.reserve(Size);
11708 ExprPostUpdates.reserve(Size);
11709 }
11710 /// Stores reduction item and reduction operation only (required for dependent
11711 /// reduction item).
11712 void push(Expr *Item, Expr *ReductionOp) {
11713 Vars.emplace_back(Item);
11714 Privates.emplace_back(nullptr);
11715 LHSs.emplace_back(nullptr);
11716 RHSs.emplace_back(nullptr);
11717 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011718 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011719 }
11720 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011721 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11722 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011723 Vars.emplace_back(Item);
11724 Privates.emplace_back(Private);
11725 LHSs.emplace_back(LHS);
11726 RHSs.emplace_back(RHS);
11727 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011728 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011729 }
11730};
11731} // namespace
11732
Alexey Bataeve3727102018-04-18 15:57:46 +000011733static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011734 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11735 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11736 const Expr *Length = OASE->getLength();
11737 if (Length == nullptr) {
11738 // For array sections of the form [1:] or [:], we would need to analyze
11739 // the lower bound...
11740 if (OASE->getColonLoc().isValid())
11741 return false;
11742
11743 // This is an array subscript which has implicit length 1!
11744 SingleElement = true;
11745 ArraySizes.push_back(llvm::APSInt::get(1));
11746 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011747 Expr::EvalResult Result;
11748 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011749 return false;
11750
Fangrui Song407659a2018-11-30 23:41:18 +000011751 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011752 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11753 ArraySizes.push_back(ConstantLengthValue);
11754 }
11755
11756 // Get the base of this array section and walk up from there.
11757 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11758
11759 // We require length = 1 for all array sections except the right-most to
11760 // guarantee that the memory region is contiguous and has no holes in it.
11761 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11762 Length = TempOASE->getLength();
11763 if (Length == nullptr) {
11764 // For array sections of the form [1:] or [:], we would need to analyze
11765 // the lower bound...
11766 if (OASE->getColonLoc().isValid())
11767 return false;
11768
11769 // This is an array subscript which has implicit length 1!
11770 ArraySizes.push_back(llvm::APSInt::get(1));
11771 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011772 Expr::EvalResult Result;
11773 if (!Length->EvaluateAsInt(Result, Context))
11774 return false;
11775
11776 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11777 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011778 return false;
11779
11780 ArraySizes.push_back(ConstantLengthValue);
11781 }
11782 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11783 }
11784
11785 // If we have a single element, we don't need to add the implicit lengths.
11786 if (!SingleElement) {
11787 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11788 // Has implicit length 1!
11789 ArraySizes.push_back(llvm::APSInt::get(1));
11790 Base = TempASE->getBase()->IgnoreParenImpCasts();
11791 }
11792 }
11793
11794 // This array section can be privatized as a single value or as a constant
11795 // sized array.
11796 return true;
11797}
11798
Alexey Bataeve3727102018-04-18 15:57:46 +000011799static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011800 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11801 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11802 SourceLocation ColonLoc, SourceLocation EndLoc,
11803 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011804 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011805 DeclarationName DN = ReductionId.getName();
11806 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011807 BinaryOperatorKind BOK = BO_Comma;
11808
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011809 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011810 // OpenMP [2.14.3.6, reduction clause]
11811 // C
11812 // reduction-identifier is either an identifier or one of the following
11813 // operators: +, -, *, &, |, ^, && and ||
11814 // C++
11815 // reduction-identifier is either an id-expression or one of the following
11816 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011817 switch (OOK) {
11818 case OO_Plus:
11819 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011820 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011821 break;
11822 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011823 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011824 break;
11825 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011826 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011827 break;
11828 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011829 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011830 break;
11831 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011832 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011833 break;
11834 case OO_AmpAmp:
11835 BOK = BO_LAnd;
11836 break;
11837 case OO_PipePipe:
11838 BOK = BO_LOr;
11839 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011840 case OO_New:
11841 case OO_Delete:
11842 case OO_Array_New:
11843 case OO_Array_Delete:
11844 case OO_Slash:
11845 case OO_Percent:
11846 case OO_Tilde:
11847 case OO_Exclaim:
11848 case OO_Equal:
11849 case OO_Less:
11850 case OO_Greater:
11851 case OO_LessEqual:
11852 case OO_GreaterEqual:
11853 case OO_PlusEqual:
11854 case OO_MinusEqual:
11855 case OO_StarEqual:
11856 case OO_SlashEqual:
11857 case OO_PercentEqual:
11858 case OO_CaretEqual:
11859 case OO_AmpEqual:
11860 case OO_PipeEqual:
11861 case OO_LessLess:
11862 case OO_GreaterGreater:
11863 case OO_LessLessEqual:
11864 case OO_GreaterGreaterEqual:
11865 case OO_EqualEqual:
11866 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011867 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011868 case OO_PlusPlus:
11869 case OO_MinusMinus:
11870 case OO_Comma:
11871 case OO_ArrowStar:
11872 case OO_Arrow:
11873 case OO_Call:
11874 case OO_Subscript:
11875 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011876 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011877 case NUM_OVERLOADED_OPERATORS:
11878 llvm_unreachable("Unexpected reduction identifier");
11879 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011880 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011881 if (II->isStr("max"))
11882 BOK = BO_GT;
11883 else if (II->isStr("min"))
11884 BOK = BO_LT;
11885 }
11886 break;
11887 }
11888 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011889 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011890 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011891 else
11892 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011893 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011894
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011895 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11896 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011897 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011898 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011899 // OpenMP [2.1, C/C++]
11900 // A list item is a variable or array section, subject to the restrictions
11901 // specified in Section 2.4 on page 42 and in each of the sections
11902 // describing clauses and directives for which a list appears.
11903 // OpenMP [2.14.3.3, Restrictions, p.1]
11904 // A variable that is part of another variable (as an array or
11905 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011906 if (!FirstIter && IR != ER)
11907 ++IR;
11908 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011909 SourceLocation ELoc;
11910 SourceRange ERange;
11911 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011912 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011913 /*AllowArraySection=*/true);
11914 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011915 // Try to find 'declare reduction' corresponding construct before using
11916 // builtin/overloaded operators.
11917 QualType Type = Context.DependentTy;
11918 CXXCastPath BasePath;
11919 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011920 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011921 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011922 Expr *ReductionOp = nullptr;
11923 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011924 (DeclareReductionRef.isUnset() ||
11925 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011926 ReductionOp = DeclareReductionRef.get();
11927 // It will be analyzed later.
11928 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011929 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011930 ValueDecl *D = Res.first;
11931 if (!D)
11932 continue;
11933
Alexey Bataev88202be2017-07-27 13:20:36 +000011934 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011935 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011936 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11937 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011938 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011939 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011940 } else if (OASE) {
11941 QualType BaseType =
11942 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11943 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011944 Type = ATy->getElementType();
11945 else
11946 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011947 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011948 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011949 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011950 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011951 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011952
Alexey Bataevc5e02582014-06-16 07:08:35 +000011953 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11954 // A variable that appears in a private clause must not have an incomplete
11955 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011956 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011957 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011958 continue;
11959 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011960 // A list item that appears in a reduction clause must not be
11961 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011962 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11963 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011964 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011965
11966 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011967 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11968 // If a list-item is a reference type then it must bind to the same object
11969 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011970 if (!ASE && !OASE) {
11971 if (VD) {
11972 VarDecl *VDDef = VD->getDefinition();
11973 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11974 DSARefChecker Check(Stack);
11975 if (Check.Visit(VDDef->getInit())) {
11976 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11977 << getOpenMPClauseName(ClauseKind) << ERange;
11978 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11979 continue;
11980 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011981 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011982 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011983
Alexey Bataevbc529672018-09-28 19:33:14 +000011984 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11985 // in a Construct]
11986 // Variables with the predetermined data-sharing attributes may not be
11987 // listed in data-sharing attributes clauses, except for the cases
11988 // listed below. For these exceptions only, listing a predetermined
11989 // variable in a data-sharing attribute clause is allowed and overrides
11990 // the variable's predetermined data-sharing attributes.
11991 // OpenMP [2.14.3.6, Restrictions, p.3]
11992 // Any number of reduction clauses can be specified on the directive,
11993 // but a list item can appear only once in the reduction clauses for that
11994 // directive.
11995 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11996 if (DVar.CKind == OMPC_reduction) {
11997 S.Diag(ELoc, diag::err_omp_once_referenced)
11998 << getOpenMPClauseName(ClauseKind);
11999 if (DVar.RefExpr)
12000 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
12001 continue;
12002 }
12003 if (DVar.CKind != OMPC_unknown) {
12004 S.Diag(ELoc, diag::err_omp_wrong_dsa)
12005 << getOpenMPClauseName(DVar.CKind)
12006 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000012007 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012008 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000012009 }
Alexey Bataevbc529672018-09-28 19:33:14 +000012010
12011 // OpenMP [2.14.3.6, Restrictions, p.1]
12012 // A list item that appears in a reduction clause of a worksharing
12013 // construct must be shared in the parallel regions to which any of the
12014 // worksharing regions arising from the worksharing construct bind.
12015 if (isOpenMPWorksharingDirective(CurrDir) &&
12016 !isOpenMPParallelDirective(CurrDir) &&
12017 !isOpenMPTeamsDirective(CurrDir)) {
12018 DVar = Stack->getImplicitDSA(D, true);
12019 if (DVar.CKind != OMPC_shared) {
12020 S.Diag(ELoc, diag::err_omp_required_access)
12021 << getOpenMPClauseName(OMPC_reduction)
12022 << getOpenMPClauseName(OMPC_shared);
12023 reportOriginalDsa(S, Stack, D, DVar);
12024 continue;
12025 }
12026 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000012027 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012028
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012029 // Try to find 'declare reduction' corresponding construct before using
12030 // builtin/overloaded operators.
12031 CXXCastPath BasePath;
12032 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012033 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012034 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
12035 if (DeclareReductionRef.isInvalid())
12036 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012037 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012038 (DeclareReductionRef.isUnset() ||
12039 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012040 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012041 continue;
12042 }
12043 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
12044 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012045 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012046 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012047 << Type << ReductionIdRange;
12048 continue;
12049 }
12050
12051 // OpenMP [2.14.3.6, reduction clause, Restrictions]
12052 // The type of a list item that appears in a reduction clause must be valid
12053 // for the reduction-identifier. For a max or min reduction in C, the type
12054 // of the list item must be an allowed arithmetic data type: char, int,
12055 // float, double, or _Bool, possibly modified with long, short, signed, or
12056 // unsigned. For a max or min reduction in C++, the type of the list item
12057 // must be an allowed arithmetic data type: char, wchar_t, int, float,
12058 // double, or bool, possibly modified with long, short, signed, or unsigned.
12059 if (DeclareReductionRef.isUnset()) {
12060 if ((BOK == BO_GT || BOK == BO_LT) &&
12061 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012062 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
12063 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000012064 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012065 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012066 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12067 VarDecl::DeclarationOnly;
12068 S.Diag(D->getLocation(),
12069 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012070 << D;
12071 }
12072 continue;
12073 }
12074 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012075 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000012076 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
12077 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012078 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012079 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12080 VarDecl::DeclarationOnly;
12081 S.Diag(D->getLocation(),
12082 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012083 << D;
12084 }
12085 continue;
12086 }
12087 }
12088
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012089 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012090 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
12091 D->hasAttrs() ? &D->getAttrs() : nullptr);
12092 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
12093 D->hasAttrs() ? &D->getAttrs() : nullptr);
12094 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012095
12096 // Try if we can determine constant lengths for all array sections and avoid
12097 // the VLA.
12098 bool ConstantLengthOASE = false;
12099 if (OASE) {
12100 bool SingleElement;
12101 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000012102 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012103 Context, OASE, SingleElement, ArraySizes);
12104
12105 // If we don't have a single element, we must emit a constant array type.
12106 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012107 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012108 PrivateTy = Context.getConstantArrayType(
12109 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012110 }
12111 }
12112
12113 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000012114 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000012115 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000012116 if (!Context.getTargetInfo().isVLASupported() &&
12117 S.shouldDiagnoseTargetSupportFromOpenMP()) {
12118 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12119 S.Diag(ELoc, diag::note_vla_unsupported);
12120 continue;
12121 }
David Majnemer9d168222016-08-05 17:44:54 +000012122 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012123 // Create pseudo array type for private copy. The size for this array will
12124 // be generated during codegen.
12125 // For array subscripts or single variables Private Ty is the same as Type
12126 // (type of the variable or single array element).
12127 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012128 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000012129 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012130 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000012131 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000012132 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012133 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012134 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012135 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012136 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012137 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
12138 D->hasAttrs() ? &D->getAttrs() : nullptr,
12139 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012140 // Add initializer for private variable.
12141 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012142 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
12143 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012144 if (DeclareReductionRef.isUsable()) {
12145 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
12146 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
12147 if (DRD->getInitializer()) {
12148 Init = DRDRef;
12149 RHSVD->setInit(DRDRef);
12150 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012151 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012152 } else {
12153 switch (BOK) {
12154 case BO_Add:
12155 case BO_Xor:
12156 case BO_Or:
12157 case BO_LOr:
12158 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
12159 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012160 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012161 break;
12162 case BO_Mul:
12163 case BO_LAnd:
12164 if (Type->isScalarType() || Type->isAnyComplexType()) {
12165 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012166 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012167 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012168 break;
12169 case BO_And: {
12170 // '&' reduction op - initializer is '~0'.
12171 QualType OrigType = Type;
12172 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
12173 Type = ComplexTy->getElementType();
12174 if (Type->isRealFloatingType()) {
12175 llvm::APFloat InitValue =
12176 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
12177 /*isIEEE=*/true);
12178 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12179 Type, ELoc);
12180 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012181 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012182 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
12183 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
12184 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12185 }
12186 if (Init && OrigType->isAnyComplexType()) {
12187 // Init = 0xFFFF + 0xFFFFi;
12188 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012189 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012190 }
12191 Type = OrigType;
12192 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012193 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012194 case BO_LT:
12195 case BO_GT: {
12196 // 'min' reduction op - initializer is 'Largest representable number in
12197 // the reduction list item type'.
12198 // 'max' reduction op - initializer is 'Least representable number in
12199 // the reduction list item type'.
12200 if (Type->isIntegerType() || Type->isPointerType()) {
12201 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000012202 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012203 QualType IntTy =
12204 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
12205 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012206 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
12207 : llvm::APInt::getMinValue(Size)
12208 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
12209 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012210 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12211 if (Type->isPointerType()) {
12212 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012213 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000012214 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012215 if (CastExpr.isInvalid())
12216 continue;
12217 Init = CastExpr.get();
12218 }
12219 } else if (Type->isRealFloatingType()) {
12220 llvm::APFloat InitValue = llvm::APFloat::getLargest(
12221 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
12222 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12223 Type, ELoc);
12224 }
12225 break;
12226 }
12227 case BO_PtrMemD:
12228 case BO_PtrMemI:
12229 case BO_MulAssign:
12230 case BO_Div:
12231 case BO_Rem:
12232 case BO_Sub:
12233 case BO_Shl:
12234 case BO_Shr:
12235 case BO_LE:
12236 case BO_GE:
12237 case BO_EQ:
12238 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000012239 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012240 case BO_AndAssign:
12241 case BO_XorAssign:
12242 case BO_OrAssign:
12243 case BO_Assign:
12244 case BO_AddAssign:
12245 case BO_SubAssign:
12246 case BO_DivAssign:
12247 case BO_RemAssign:
12248 case BO_ShlAssign:
12249 case BO_ShrAssign:
12250 case BO_Comma:
12251 llvm_unreachable("Unexpected reduction operation");
12252 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012253 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012254 if (Init && DeclareReductionRef.isUnset())
12255 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
12256 else if (!Init)
12257 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012258 if (RHSVD->isInvalidDecl())
12259 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000012260 if (!RHSVD->hasInit() &&
12261 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012262 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
12263 << Type << ReductionIdRange;
12264 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12265 VarDecl::DeclarationOnly;
12266 S.Diag(D->getLocation(),
12267 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000012268 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012269 continue;
12270 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012271 // Store initializer for single element in private copy. Will be used during
12272 // codegen.
12273 PrivateVD->setInit(RHSVD->getInit());
12274 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000012275 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012276 ExprResult ReductionOp;
12277 if (DeclareReductionRef.isUsable()) {
12278 QualType RedTy = DeclareReductionRef.get()->getType();
12279 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012280 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
12281 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012282 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012283 LHS = S.DefaultLvalueConversion(LHS.get());
12284 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012285 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12286 CK_UncheckedDerivedToBase, LHS.get(),
12287 &BasePath, LHS.get()->getValueKind());
12288 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12289 CK_UncheckedDerivedToBase, RHS.get(),
12290 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012291 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012292 FunctionProtoType::ExtProtoInfo EPI;
12293 QualType Params[] = {PtrRedTy, PtrRedTy};
12294 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
12295 auto *OVE = new (Context) OpaqueValueExpr(
12296 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012297 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012298 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000012299 ReductionOp =
12300 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012301 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012302 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012303 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012304 if (ReductionOp.isUsable()) {
12305 if (BOK != BO_LT && BOK != BO_GT) {
12306 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012307 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012308 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012309 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000012310 auto *ConditionalOp = new (Context)
12311 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
12312 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012313 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012314 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012315 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012316 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012317 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012318 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
12319 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012320 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012321 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012322 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012323 }
12324
Alexey Bataevfa312f32017-07-21 18:48:21 +000012325 // OpenMP [2.15.4.6, Restrictions, p.2]
12326 // A list item that appears in an in_reduction clause of a task construct
12327 // must appear in a task_reduction clause of a construct associated with a
12328 // taskgroup region that includes the participating task in its taskgroup
12329 // set. The construct associated with the innermost region that meets this
12330 // condition must specify the same reduction-identifier as the in_reduction
12331 // clause.
12332 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000012333 SourceRange ParentSR;
12334 BinaryOperatorKind ParentBOK;
12335 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000012336 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000012337 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012338 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
12339 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012340 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012341 Stack->getTopMostTaskgroupReductionData(
12342 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012343 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
12344 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
12345 if (!IsParentBOK && !IsParentReductionOp) {
12346 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
12347 continue;
12348 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000012349 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
12350 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
12351 IsParentReductionOp) {
12352 bool EmitError = true;
12353 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
12354 llvm::FoldingSetNodeID RedId, ParentRedId;
12355 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
12356 DeclareReductionRef.get()->Profile(RedId, Context,
12357 /*Canonical=*/true);
12358 EmitError = RedId != ParentRedId;
12359 }
12360 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012361 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000012362 diag::err_omp_reduction_identifier_mismatch)
12363 << ReductionIdRange << RefExpr->getSourceRange();
12364 S.Diag(ParentSR.getBegin(),
12365 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000012366 << ParentSR
12367 << (IsParentBOK ? ParentBOKDSA.RefExpr
12368 : ParentReductionOpDSA.RefExpr)
12369 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000012370 continue;
12371 }
12372 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012373 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
12374 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000012375 }
12376
Alexey Bataev60da77e2016-02-29 05:54:20 +000012377 DeclRefExpr *Ref = nullptr;
12378 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012379 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012380 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012381 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012382 VarsExpr =
12383 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
12384 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000012385 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012386 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012387 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012388 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012389 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012390 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012391 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012392 if (!RefRes.isUsable())
12393 continue;
12394 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012395 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12396 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012397 if (!PostUpdateRes.isUsable())
12398 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012399 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
12400 Stack->getCurrentDirective() == OMPD_taskgroup) {
12401 S.Diag(RefExpr->getExprLoc(),
12402 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000012403 << RefExpr->getSourceRange();
12404 continue;
12405 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012406 RD.ExprPostUpdates.emplace_back(
12407 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000012408 }
12409 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012410 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000012411 // All reduction items are still marked as reduction (to do not increase
12412 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012413 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012414 if (CurrDir == OMPD_taskgroup) {
12415 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012416 Stack->addTaskgroupReductionData(D, ReductionIdRange,
12417 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000012418 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012419 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012420 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012421 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
12422 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012423 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012424 return RD.Vars.empty();
12425}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012426
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012427OMPClause *Sema::ActOnOpenMPReductionClause(
12428 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12429 SourceLocation ColonLoc, SourceLocation EndLoc,
12430 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12431 ArrayRef<Expr *> UnresolvedReductions) {
12432 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012433 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012434 StartLoc, LParenLoc, ColonLoc, EndLoc,
12435 ReductionIdScopeSpec, ReductionId,
12436 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012437 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000012438
Alexey Bataevc5e02582014-06-16 07:08:35 +000012439 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012440 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12441 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12442 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12443 buildPreInits(Context, RD.ExprCaptures),
12444 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000012445}
12446
Alexey Bataev169d96a2017-07-18 20:17:46 +000012447OMPClause *Sema::ActOnOpenMPTaskReductionClause(
12448 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12449 SourceLocation ColonLoc, SourceLocation EndLoc,
12450 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12451 ArrayRef<Expr *> UnresolvedReductions) {
12452 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012453 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
12454 StartLoc, LParenLoc, ColonLoc, EndLoc,
12455 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012456 UnresolvedReductions, RD))
12457 return nullptr;
12458
12459 return OMPTaskReductionClause::Create(
12460 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12461 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12462 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12463 buildPreInits(Context, RD.ExprCaptures),
12464 buildPostUpdate(*this, RD.ExprPostUpdates));
12465}
12466
Alexey Bataevfa312f32017-07-21 18:48:21 +000012467OMPClause *Sema::ActOnOpenMPInReductionClause(
12468 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12469 SourceLocation ColonLoc, SourceLocation EndLoc,
12470 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12471 ArrayRef<Expr *> UnresolvedReductions) {
12472 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012473 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012474 StartLoc, LParenLoc, ColonLoc, EndLoc,
12475 ReductionIdScopeSpec, ReductionId,
12476 UnresolvedReductions, RD))
12477 return nullptr;
12478
12479 return OMPInReductionClause::Create(
12480 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12481 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000012482 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012483 buildPreInits(Context, RD.ExprCaptures),
12484 buildPostUpdate(*this, RD.ExprPostUpdates));
12485}
12486
Alexey Bataevecba70f2016-04-12 11:02:11 +000012487bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
12488 SourceLocation LinLoc) {
12489 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
12490 LinKind == OMPC_LINEAR_unknown) {
12491 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
12492 return true;
12493 }
12494 return false;
12495}
12496
Alexey Bataeve3727102018-04-18 15:57:46 +000012497bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000012498 OpenMPLinearClauseKind LinKind,
12499 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012500 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000012501 // A variable must not have an incomplete type or a reference type.
12502 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12503 return true;
12504 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12505 !Type->isReferenceType()) {
12506 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12507 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12508 return true;
12509 }
12510 Type = Type.getNonReferenceType();
12511
Joel E. Dennybae586f2019-01-04 22:12:13 +000012512 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12513 // A variable that is privatized must not have a const-qualified type
12514 // unless it is of class type with a mutable member. This restriction does
12515 // not apply to the firstprivate clause.
12516 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012517 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012518
12519 // A list item must be of integral or pointer type.
12520 Type = Type.getUnqualifiedType().getCanonicalType();
12521 const auto *Ty = Type.getTypePtrOrNull();
12522 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12523 !Ty->isPointerType())) {
12524 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12525 if (D) {
12526 bool IsDecl =
12527 !VD ||
12528 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12529 Diag(D->getLocation(),
12530 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12531 << D;
12532 }
12533 return true;
12534 }
12535 return false;
12536}
12537
Alexey Bataev182227b2015-08-20 10:54:39 +000012538OMPClause *Sema::ActOnOpenMPLinearClause(
12539 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12540 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12541 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012542 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012543 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012544 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012545 SmallVector<Decl *, 4> ExprCaptures;
12546 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012547 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012548 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012549 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012550 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012551 SourceLocation ELoc;
12552 SourceRange ERange;
12553 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012554 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012555 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012556 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012557 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012558 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012559 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012560 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012561 ValueDecl *D = Res.first;
12562 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012563 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012564
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012565 QualType Type = D->getType();
12566 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012567
12568 // OpenMP [2.14.3.7, linear clause]
12569 // A list-item cannot appear in more than one linear clause.
12570 // A list-item that appears in a linear clause cannot appear in any
12571 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012572 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012573 if (DVar.RefExpr) {
12574 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12575 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012576 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012577 continue;
12578 }
12579
Alexey Bataevecba70f2016-04-12 11:02:11 +000012580 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012581 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012582 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012583
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012584 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012585 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012586 buildVarDecl(*this, ELoc, Type, D->getName(),
12587 D->hasAttrs() ? &D->getAttrs() : nullptr,
12588 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012589 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012590 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012591 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012592 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012593 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012594 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012595 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012596 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012597 ExprCaptures.push_back(Ref->getDecl());
12598 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12599 ExprResult RefRes = DefaultLvalueConversion(Ref);
12600 if (!RefRes.isUsable())
12601 continue;
12602 ExprResult PostUpdateRes =
12603 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12604 SimpleRefExpr, RefRes.get());
12605 if (!PostUpdateRes.isUsable())
12606 continue;
12607 ExprPostUpdates.push_back(
12608 IgnoredValueConversions(PostUpdateRes.get()).get());
12609 }
12610 }
12611 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012612 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012613 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012614 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012615 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012616 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012617 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012618 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012619
12620 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012621 Vars.push_back((VD || CurContext->isDependentContext())
12622 ? RefExpr->IgnoreParens()
12623 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012624 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012625 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012626 }
12627
12628 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012629 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012630
12631 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012632 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012633 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12634 !Step->isInstantiationDependent() &&
12635 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012636 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012637 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012638 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012639 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012640 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012641
Alexander Musman3276a272015-03-21 10:12:56 +000012642 // Build var to save the step value.
12643 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012644 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012645 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012646 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012647 ExprResult CalcStep =
12648 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012649 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012650
Alexander Musman8dba6642014-04-22 13:09:42 +000012651 // Warn about zero linear step (it would be probably better specified as
12652 // making corresponding variables 'const').
12653 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012654 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12655 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012656 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12657 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012658 if (!IsConstant && CalcStep.isUsable()) {
12659 // Calculate the step beforehand instead of doing this on each iteration.
12660 // (This is not used if the number of iterations may be kfold-ed).
12661 CalcStepExpr = CalcStep.get();
12662 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012663 }
12664
Alexey Bataev182227b2015-08-20 10:54:39 +000012665 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12666 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012667 StepExpr, CalcStepExpr,
12668 buildPreInits(Context, ExprCaptures),
12669 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012670}
12671
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012672static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12673 Expr *NumIterations, Sema &SemaRef,
12674 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012675 // Walk the vars and build update/final expressions for the CodeGen.
12676 SmallVector<Expr *, 8> Updates;
12677 SmallVector<Expr *, 8> Finals;
12678 Expr *Step = Clause.getStep();
12679 Expr *CalcStep = Clause.getCalcStep();
12680 // OpenMP [2.14.3.7, linear clause]
12681 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012682 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012683 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012684 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012685 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12686 bool HasErrors = false;
12687 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012688 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012689 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12690 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012691 SourceLocation ELoc;
12692 SourceRange ERange;
12693 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012694 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012695 ValueDecl *D = Res.first;
12696 if (Res.second || !D) {
12697 Updates.push_back(nullptr);
12698 Finals.push_back(nullptr);
12699 HasErrors = true;
12700 continue;
12701 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012702 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012703 // OpenMP [2.15.11, distribute simd Construct]
12704 // A list item may not appear in a linear clause, unless it is the loop
12705 // iteration variable.
12706 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12707 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12708 SemaRef.Diag(ELoc,
12709 diag::err_omp_linear_distribute_var_non_loop_iteration);
12710 Updates.push_back(nullptr);
12711 Finals.push_back(nullptr);
12712 HasErrors = true;
12713 continue;
12714 }
Alexander Musman3276a272015-03-21 10:12:56 +000012715 Expr *InitExpr = *CurInit;
12716
12717 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012718 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012719 Expr *CapturedRef;
12720 if (LinKind == OMPC_LINEAR_uval)
12721 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12722 else
12723 CapturedRef =
12724 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12725 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12726 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012727
12728 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012729 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012730 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012731 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012732 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012733 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012734 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012735 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012736 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012737 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012738
12739 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012740 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012741 if (!Info.first)
12742 Final =
12743 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12744 InitExpr, NumIterations, Step, /*Subtract=*/false);
12745 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012746 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012747 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012748 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012749
Alexander Musman3276a272015-03-21 10:12:56 +000012750 if (!Update.isUsable() || !Final.isUsable()) {
12751 Updates.push_back(nullptr);
12752 Finals.push_back(nullptr);
12753 HasErrors = true;
12754 } else {
12755 Updates.push_back(Update.get());
12756 Finals.push_back(Final.get());
12757 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012758 ++CurInit;
12759 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012760 }
12761 Clause.setUpdates(Updates);
12762 Clause.setFinals(Finals);
12763 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012764}
12765
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012766OMPClause *Sema::ActOnOpenMPAlignedClause(
12767 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12768 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012769 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012770 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012771 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12772 SourceLocation ELoc;
12773 SourceRange ERange;
12774 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012775 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012776 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012777 // It will be analyzed later.
12778 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012779 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012780 ValueDecl *D = Res.first;
12781 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012782 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012783
Alexey Bataev1efd1662016-03-29 10:59:56 +000012784 QualType QType = D->getType();
12785 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012786
12787 // OpenMP [2.8.1, simd construct, Restrictions]
12788 // The type of list items appearing in the aligned clause must be
12789 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012790 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012791 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012792 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012793 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012794 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012795 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012796 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012797 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012798 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012799 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012800 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012801 continue;
12802 }
12803
12804 // OpenMP [2.8.1, simd construct, Restrictions]
12805 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012806 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012807 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012808 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12809 << getOpenMPClauseName(OMPC_aligned);
12810 continue;
12811 }
12812
Alexey Bataev1efd1662016-03-29 10:59:56 +000012813 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012814 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012815 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12816 Vars.push_back(DefaultFunctionArrayConversion(
12817 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12818 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012819 }
12820
12821 // OpenMP [2.8.1, simd construct, Description]
12822 // The parameter of the aligned clause, alignment, must be a constant
12823 // positive integer expression.
12824 // If no optional parameter is specified, implementation-defined default
12825 // alignments for SIMD instructions on the target platforms are assumed.
12826 if (Alignment != nullptr) {
12827 ExprResult AlignResult =
12828 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12829 if (AlignResult.isInvalid())
12830 return nullptr;
12831 Alignment = AlignResult.get();
12832 }
12833 if (Vars.empty())
12834 return nullptr;
12835
12836 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12837 EndLoc, Vars, Alignment);
12838}
12839
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012840OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12841 SourceLocation StartLoc,
12842 SourceLocation LParenLoc,
12843 SourceLocation EndLoc) {
12844 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012845 SmallVector<Expr *, 8> SrcExprs;
12846 SmallVector<Expr *, 8> DstExprs;
12847 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012848 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012849 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12850 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012851 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012852 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012853 SrcExprs.push_back(nullptr);
12854 DstExprs.push_back(nullptr);
12855 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012856 continue;
12857 }
12858
Alexey Bataeved09d242014-05-28 05:53:51 +000012859 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012860 // OpenMP [2.1, C/C++]
12861 // A list item is a variable name.
12862 // OpenMP [2.14.4.1, Restrictions, p.1]
12863 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012864 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012865 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012866 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12867 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012868 continue;
12869 }
12870
12871 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012872 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012873
12874 QualType Type = VD->getType();
12875 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12876 // It will be analyzed later.
12877 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012878 SrcExprs.push_back(nullptr);
12879 DstExprs.push_back(nullptr);
12880 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012881 continue;
12882 }
12883
12884 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12885 // A list item that appears in a copyin clause must be threadprivate.
12886 if (!DSAStack->isThreadPrivate(VD)) {
12887 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012888 << getOpenMPClauseName(OMPC_copyin)
12889 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012890 continue;
12891 }
12892
12893 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12894 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012895 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012896 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012897 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12898 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012899 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012900 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012901 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012902 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012903 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012904 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012905 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012906 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012907 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012908 // For arrays generate assignment operation for single element and replace
12909 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012910 ExprResult AssignmentOp =
12911 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12912 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012913 if (AssignmentOp.isInvalid())
12914 continue;
12915 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012916 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012917 if (AssignmentOp.isInvalid())
12918 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012919
12920 DSAStack->addDSA(VD, DE, OMPC_copyin);
12921 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012922 SrcExprs.push_back(PseudoSrcExpr);
12923 DstExprs.push_back(PseudoDstExpr);
12924 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012925 }
12926
Alexey Bataeved09d242014-05-28 05:53:51 +000012927 if (Vars.empty())
12928 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012929
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012930 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12931 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012932}
12933
Alexey Bataevbae9a792014-06-27 10:37:06 +000012934OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12935 SourceLocation StartLoc,
12936 SourceLocation LParenLoc,
12937 SourceLocation EndLoc) {
12938 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012939 SmallVector<Expr *, 8> SrcExprs;
12940 SmallVector<Expr *, 8> DstExprs;
12941 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012942 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012943 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12944 SourceLocation ELoc;
12945 SourceRange ERange;
12946 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012947 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012948 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012949 // It will be analyzed later.
12950 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012951 SrcExprs.push_back(nullptr);
12952 DstExprs.push_back(nullptr);
12953 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012954 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012955 ValueDecl *D = Res.first;
12956 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012957 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012958
Alexey Bataeve122da12016-03-17 10:50:17 +000012959 QualType Type = D->getType();
12960 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012961
12962 // OpenMP [2.14.4.2, Restrictions, p.2]
12963 // A list item that appears in a copyprivate clause may not appear in a
12964 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012965 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012966 DSAStackTy::DSAVarData DVar =
12967 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012968 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12969 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012970 Diag(ELoc, diag::err_omp_wrong_dsa)
12971 << getOpenMPClauseName(DVar.CKind)
12972 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012973 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012974 continue;
12975 }
12976
12977 // OpenMP [2.11.4.2, Restrictions, p.1]
12978 // All list items that appear in a copyprivate clause must be either
12979 // threadprivate or private in the enclosing context.
12980 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012981 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012982 if (DVar.CKind == OMPC_shared) {
12983 Diag(ELoc, diag::err_omp_required_access)
12984 << getOpenMPClauseName(OMPC_copyprivate)
12985 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012986 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012987 continue;
12988 }
12989 }
12990 }
12991
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012992 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012993 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012994 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012995 << getOpenMPClauseName(OMPC_copyprivate) << Type
12996 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012997 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012998 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012999 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000013000 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013001 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000013002 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013003 continue;
13004 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013005
Alexey Bataevbae9a792014-06-27 10:37:06 +000013006 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13007 // A variable of class type (or array thereof) that appears in a
13008 // copyin clause requires an accessible, unambiguous copy assignment
13009 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013010 Type = Context.getBaseElementType(Type.getNonReferenceType())
13011 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013012 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013013 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000013014 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013015 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
13016 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013017 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000013018 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013019 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
13020 ExprResult AssignmentOp = BuildBinOp(
13021 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013022 if (AssignmentOp.isInvalid())
13023 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013024 AssignmentOp =
13025 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013026 if (AssignmentOp.isInvalid())
13027 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013028
13029 // No need to mark vars as copyprivate, they are already threadprivate or
13030 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000013031 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000013032 Vars.push_back(
13033 VD ? RefExpr->IgnoreParens()
13034 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000013035 SrcExprs.push_back(PseudoSrcExpr);
13036 DstExprs.push_back(PseudoDstExpr);
13037 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000013038 }
13039
13040 if (Vars.empty())
13041 return nullptr;
13042
Alexey Bataeva63048e2015-03-23 06:18:07 +000013043 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13044 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013045}
13046
Alexey Bataev6125da92014-07-21 11:26:11 +000013047OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
13048 SourceLocation StartLoc,
13049 SourceLocation LParenLoc,
13050 SourceLocation EndLoc) {
13051 if (VarList.empty())
13052 return nullptr;
13053
13054 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
13055}
Alexey Bataevdea47612014-07-23 07:46:59 +000013056
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013057OMPClause *
13058Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
13059 SourceLocation DepLoc, SourceLocation ColonLoc,
13060 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13061 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013062 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013063 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013064 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013065 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000013066 return nullptr;
13067 }
13068 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013069 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
13070 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000013071 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013072 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013073 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13074 /*Last=*/OMPC_DEPEND_unknown, Except)
13075 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013076 return nullptr;
13077 }
13078 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000013079 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013080 llvm::APSInt DepCounter(/*BitWidth=*/32);
13081 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000013082 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
13083 if (const Expr *OrderedCountExpr =
13084 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013085 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
13086 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013087 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013088 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013089 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000013090 assert(RefExpr && "NULL expr in OpenMP shared clause.");
13091 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
13092 // It will be analyzed later.
13093 Vars.push_back(RefExpr);
13094 continue;
13095 }
13096
13097 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000013098 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000013099 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000013100 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013101 DepCounter >= TotalDepCount) {
13102 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
13103 continue;
13104 }
13105 ++DepCounter;
13106 // OpenMP [2.13.9, Summary]
13107 // depend(dependence-type : vec), where dependence-type is:
13108 // 'sink' and where vec is the iteration vector, which has the form:
13109 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
13110 // where n is the value specified by the ordered clause in the loop
13111 // directive, xi denotes the loop iteration variable of the i-th nested
13112 // loop associated with the loop directive, and di is a constant
13113 // non-negative integer.
13114 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013115 // It will be analyzed later.
13116 Vars.push_back(RefExpr);
13117 continue;
13118 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013119 SimpleExpr = SimpleExpr->IgnoreImplicit();
13120 OverloadedOperatorKind OOK = OO_None;
13121 SourceLocation OOLoc;
13122 Expr *LHS = SimpleExpr;
13123 Expr *RHS = nullptr;
13124 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
13125 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
13126 OOLoc = BO->getOperatorLoc();
13127 LHS = BO->getLHS()->IgnoreParenImpCasts();
13128 RHS = BO->getRHS()->IgnoreParenImpCasts();
13129 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
13130 OOK = OCE->getOperator();
13131 OOLoc = OCE->getOperatorLoc();
13132 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
13133 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
13134 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
13135 OOK = MCE->getMethodDecl()
13136 ->getNameInfo()
13137 .getName()
13138 .getCXXOverloadedOperator();
13139 OOLoc = MCE->getCallee()->getExprLoc();
13140 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
13141 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013142 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013143 SourceLocation ELoc;
13144 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000013145 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013146 if (Res.second) {
13147 // It will be analyzed later.
13148 Vars.push_back(RefExpr);
13149 }
13150 ValueDecl *D = Res.first;
13151 if (!D)
13152 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013153
Alexey Bataev17daedf2018-02-15 22:42:57 +000013154 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
13155 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
13156 continue;
13157 }
13158 if (RHS) {
13159 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
13160 RHS, OMPC_depend, /*StrictlyPositive=*/false);
13161 if (RHSRes.isInvalid())
13162 continue;
13163 }
13164 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013165 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013166 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013167 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000013168 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000013169 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000013170 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
13171 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000013172 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000013173 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000013174 continue;
13175 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013176 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013177 } else {
13178 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
13179 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
13180 (ASE &&
13181 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
13182 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
13183 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13184 << RefExpr->getSourceRange();
13185 continue;
13186 }
13187 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
13188 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
13189 ExprResult Res =
13190 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
13191 getDiagnostics().setSuppressAllDiagnostics(Suppress);
13192 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
13193 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13194 << RefExpr->getSourceRange();
13195 continue;
13196 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013197 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013198 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013199 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013200
13201 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
13202 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013203 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013204 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
13205 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
13206 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
13207 }
13208 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
13209 Vars.empty())
13210 return nullptr;
13211
Alexey Bataev8b427062016-05-25 12:36:08 +000013212 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000013213 DepKind, DepLoc, ColonLoc, Vars,
13214 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000013215 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
13216 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000013217 DSAStack->addDoacrossDependClause(C, OpsOffs);
13218 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013219}
Michael Wonge710d542015-08-07 16:16:36 +000013220
13221OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
13222 SourceLocation LParenLoc,
13223 SourceLocation EndLoc) {
13224 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013225 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000013226
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013227 // OpenMP [2.9.1, Restrictions]
13228 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013229 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000013230 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013231 return nullptr;
13232
Alexey Bataev931e19b2017-10-02 16:32:39 +000013233 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013234 OpenMPDirectiveKind CaptureRegion =
13235 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
13236 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013237 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013238 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013239 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13240 HelperValStmt = buildPreInits(Context, Captures);
13241 }
13242
Alexey Bataev8451efa2018-01-15 19:06:12 +000013243 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
13244 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000013245}
Kelvin Li0bff7af2015-11-23 05:32:03 +000013246
Alexey Bataeve3727102018-04-18 15:57:46 +000013247static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000013248 DSAStackTy *Stack, QualType QTy,
13249 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000013250 NamedDecl *ND;
13251 if (QTy->isIncompleteType(&ND)) {
13252 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
13253 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013254 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000013255 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
13256 !QTy.isTrivialType(SemaRef.Context))
13257 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013258 return true;
13259}
13260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013261/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013262/// (array section or array subscript) does NOT specify the whole size of the
13263/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013264static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013265 const Expr *E,
13266 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013267 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013268
13269 // If this is an array subscript, it refers to the whole size if the size of
13270 // the dimension is constant and equals 1. Also, an array section assumes the
13271 // format of an array subscript if no colon is used.
13272 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013273 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013274 return ATy->getSize().getSExtValue() != 1;
13275 // Size can't be evaluated statically.
13276 return false;
13277 }
13278
13279 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013280 const Expr *LowerBound = OASE->getLowerBound();
13281 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013282
13283 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000013284 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013285 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000013286 Expr::EvalResult Result;
13287 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013288 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000013289
13290 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013291 if (ConstLowerBound.getSExtValue())
13292 return true;
13293 }
13294
13295 // If we don't have a length we covering the whole dimension.
13296 if (!Length)
13297 return false;
13298
13299 // If the base is a pointer, we don't have a way to get the size of the
13300 // pointee.
13301 if (BaseQTy->isPointerType())
13302 return false;
13303
13304 // We can only check if the length is the same as the size of the dimension
13305 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000013306 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013307 if (!CATy)
13308 return false;
13309
Fangrui Song407659a2018-11-30 23:41:18 +000013310 Expr::EvalResult Result;
13311 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013312 return false; // Can't get the integer value as a constant.
13313
Fangrui Song407659a2018-11-30 23:41:18 +000013314 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013315 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
13316}
13317
13318// Return true if it can be proven that the provided array expression (array
13319// section or array subscript) does NOT specify a single element of the array
13320// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013321static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000013322 const Expr *E,
13323 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013324 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013325
13326 // An array subscript always refer to a single element. Also, an array section
13327 // assumes the format of an array subscript if no colon is used.
13328 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
13329 return false;
13330
13331 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013332 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013333
13334 // If we don't have a length we have to check if the array has unitary size
13335 // for this dimension. Also, we should always expect a length if the base type
13336 // is pointer.
13337 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013338 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013339 return ATy->getSize().getSExtValue() != 1;
13340 // We cannot assume anything.
13341 return false;
13342 }
13343
13344 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000013345 Expr::EvalResult Result;
13346 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013347 return false; // Can't get the integer value as a constant.
13348
Fangrui Song407659a2018-11-30 23:41:18 +000013349 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013350 return ConstLength.getSExtValue() != 1;
13351}
13352
Samuel Antao661c0902016-05-26 17:39:58 +000013353// Return the expression of the base of the mappable expression or null if it
13354// cannot be determined and do all the necessary checks to see if the expression
13355// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000013356// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013357static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000013358 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000013359 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013360 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013361 SourceLocation ELoc = E->getExprLoc();
13362 SourceRange ERange = E->getSourceRange();
13363
13364 // The base of elements of list in a map clause have to be either:
13365 // - a reference to variable or field.
13366 // - a member expression.
13367 // - an array expression.
13368 //
13369 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
13370 // reference to 'r'.
13371 //
13372 // If we have:
13373 //
13374 // struct SS {
13375 // Bla S;
13376 // foo() {
13377 // #pragma omp target map (S.Arr[:12]);
13378 // }
13379 // }
13380 //
13381 // We want to retrieve the member expression 'this->S';
13382
Alexey Bataeve3727102018-04-18 15:57:46 +000013383 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013384
Samuel Antao5de996e2016-01-22 20:21:36 +000013385 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
13386 // If a list item is an array section, it must specify contiguous storage.
13387 //
13388 // For this restriction it is sufficient that we make sure only references
13389 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013390 // exist except in the rightmost expression (unless they cover the whole
13391 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000013392 //
13393 // r.ArrS[3:5].Arr[6:7]
13394 //
13395 // r.ArrS[3:5].x
13396 //
13397 // but these would be valid:
13398 // r.ArrS[3].Arr[6:7]
13399 //
13400 // r.ArrS[3].x
13401
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013402 bool AllowUnitySizeArraySection = true;
13403 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013404
Dmitry Polukhin644a9252016-03-11 07:58:34 +000013405 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013406 E = E->IgnoreParenImpCasts();
13407
13408 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
13409 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000013410 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013411
13412 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013413
13414 // If we got a reference to a declaration, we should not expect any array
13415 // section before that.
13416 AllowUnitySizeArraySection = false;
13417 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013418
13419 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013420 CurComponents.emplace_back(CurE, CurE->getDecl());
13421 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013422 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000013423
13424 if (isa<CXXThisExpr>(BaseE))
13425 // We found a base expression: this->Val.
13426 RelevantExpr = CurE;
13427 else
13428 E = BaseE;
13429
13430 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013431 if (!NoDiagnose) {
13432 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
13433 << CurE->getSourceRange();
13434 return nullptr;
13435 }
13436 if (RelevantExpr)
13437 return nullptr;
13438 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013439 }
13440
13441 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
13442
13443 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
13444 // A bit-field cannot appear in a map clause.
13445 //
13446 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013447 if (!NoDiagnose) {
13448 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
13449 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
13450 return nullptr;
13451 }
13452 if (RelevantExpr)
13453 return nullptr;
13454 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013455 }
13456
13457 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13458 // If the type of a list item is a reference to a type T then the type
13459 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013460 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013461
13462 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
13463 // A list item cannot be a variable that is a member of a structure with
13464 // a union type.
13465 //
Alexey Bataeve3727102018-04-18 15:57:46 +000013466 if (CurType->isUnionType()) {
13467 if (!NoDiagnose) {
13468 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
13469 << CurE->getSourceRange();
13470 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013471 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013472 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013473 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013474
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013475 // If we got a member expression, we should not expect any array section
13476 // before that:
13477 //
13478 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
13479 // If a list item is an element of a structure, only the rightmost symbol
13480 // of the variable reference can be an array section.
13481 //
13482 AllowUnitySizeArraySection = false;
13483 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013484
13485 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013486 CurComponents.emplace_back(CurE, FD);
13487 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013488 E = CurE->getBase()->IgnoreParenImpCasts();
13489
13490 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013491 if (!NoDiagnose) {
13492 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13493 << 0 << CurE->getSourceRange();
13494 return nullptr;
13495 }
13496 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013497 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013498
13499 // If we got an array subscript that express the whole dimension we
13500 // can have any array expressions before. If it only expressing part of
13501 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000013502 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013503 E->getType()))
13504 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013505
Patrick Lystere13b1e32019-01-02 19:28:48 +000013506 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13507 Expr::EvalResult Result;
13508 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13509 if (!Result.Val.getInt().isNullValue()) {
13510 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13511 diag::err_omp_invalid_map_this_expr);
13512 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13513 diag::note_omp_invalid_subscript_on_this_ptr_map);
13514 }
13515 }
13516 RelevantExpr = TE;
13517 }
13518
Samuel Antao90927002016-04-26 14:54:23 +000013519 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013520 CurComponents.emplace_back(CurE, nullptr);
13521 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013522 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013523 E = CurE->getBase()->IgnoreParenImpCasts();
13524
Alexey Bataev27041fa2017-12-05 15:22:49 +000013525 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013526 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13527
Samuel Antao5de996e2016-01-22 20:21:36 +000013528 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13529 // If the type of a list item is a reference to a type T then the type
13530 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013531 if (CurType->isReferenceType())
13532 CurType = CurType->getPointeeType();
13533
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013534 bool IsPointer = CurType->isAnyPointerType();
13535
13536 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013537 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13538 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013539 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013540 }
13541
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013542 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013543 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013544 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013545 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013546
Samuel Antaodab51bb2016-07-18 23:22:11 +000013547 if (AllowWholeSizeArraySection) {
13548 // Any array section is currently allowed. Allowing a whole size array
13549 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013550 //
13551 // If this array section refers to the whole dimension we can still
13552 // accept other array sections before this one, except if the base is a
13553 // pointer. Otherwise, only unitary sections are accepted.
13554 if (NotWhole || IsPointer)
13555 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013556 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013557 // A unity or whole array section is not allowed and that is not
13558 // compatible with the properties of the current array section.
13559 SemaRef.Diag(
13560 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13561 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013562 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013563 }
Samuel Antao90927002016-04-26 14:54:23 +000013564
Patrick Lystere13b1e32019-01-02 19:28:48 +000013565 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13566 Expr::EvalResult ResultR;
13567 Expr::EvalResult ResultL;
13568 if (CurE->getLength()->EvaluateAsInt(ResultR,
13569 SemaRef.getASTContext())) {
13570 if (!ResultR.Val.getInt().isOneValue()) {
13571 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13572 diag::err_omp_invalid_map_this_expr);
13573 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13574 diag::note_omp_invalid_length_on_this_ptr_mapping);
13575 }
13576 }
13577 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13578 ResultL, SemaRef.getASTContext())) {
13579 if (!ResultL.Val.getInt().isNullValue()) {
13580 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13581 diag::err_omp_invalid_map_this_expr);
13582 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13583 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13584 }
13585 }
13586 RelevantExpr = TE;
13587 }
13588
Samuel Antao90927002016-04-26 14:54:23 +000013589 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013590 CurComponents.emplace_back(CurE, nullptr);
13591 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013592 if (!NoDiagnose) {
13593 // If nothing else worked, this is not a valid map clause expression.
13594 SemaRef.Diag(
13595 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13596 << ERange;
13597 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013598 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013599 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013600 }
13601
13602 return RelevantExpr;
13603}
13604
13605// Return true if expression E associated with value VD has conflicts with other
13606// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013607static bool checkMapConflicts(
13608 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013609 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013610 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13611 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013612 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013613 SourceLocation ELoc = E->getExprLoc();
13614 SourceRange ERange = E->getSourceRange();
13615
13616 // In order to easily check the conflicts we need to match each component of
13617 // the expression under test with the components of the expressions that are
13618 // already in the stack.
13619
Samuel Antao5de996e2016-01-22 20:21:36 +000013620 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013621 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013622 "Map clause expression with unexpected base!");
13623
13624 // Variables to help detecting enclosing problems in data environment nests.
13625 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013626 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013627
Samuel Antao90927002016-04-26 14:54:23 +000013628 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13629 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013630 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13631 ERange, CKind, &EnclosingExpr,
13632 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13633 StackComponents,
13634 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013635 assert(!StackComponents.empty() &&
13636 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013637 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013638 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013639 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013640
Samuel Antao90927002016-04-26 14:54:23 +000013641 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013642 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013643
Samuel Antao5de996e2016-01-22 20:21:36 +000013644 // Expressions must start from the same base. Here we detect at which
13645 // point both expressions diverge from each other and see if we can
13646 // detect if the memory referred to both expressions is contiguous and
13647 // do not overlap.
13648 auto CI = CurComponents.rbegin();
13649 auto CE = CurComponents.rend();
13650 auto SI = StackComponents.rbegin();
13651 auto SE = StackComponents.rend();
13652 for (; CI != CE && SI != SE; ++CI, ++SI) {
13653
13654 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13655 // At most one list item can be an array item derived from a given
13656 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013657 if (CurrentRegionOnly &&
13658 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13659 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13660 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13661 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13662 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013663 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013664 << CI->getAssociatedExpression()->getSourceRange();
13665 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13666 diag::note_used_here)
13667 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013668 return true;
13669 }
13670
13671 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013672 if (CI->getAssociatedExpression()->getStmtClass() !=
13673 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013674 break;
13675
13676 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013677 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013678 break;
13679 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013680 // Check if the extra components of the expressions in the enclosing
13681 // data environment are redundant for the current base declaration.
13682 // If they are, the maps completely overlap, which is legal.
13683 for (; SI != SE; ++SI) {
13684 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013685 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013686 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013687 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013688 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013689 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013690 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013691 Type =
13692 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13693 }
13694 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013695 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013696 SemaRef, SI->getAssociatedExpression(), Type))
13697 break;
13698 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013699
13700 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13701 // List items of map clauses in the same construct must not share
13702 // original storage.
13703 //
13704 // If the expressions are exactly the same or one is a subset of the
13705 // other, it means they are sharing storage.
13706 if (CI == CE && SI == SE) {
13707 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013708 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013709 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013710 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013711 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013712 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13713 << ERange;
13714 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013715 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13716 << RE->getSourceRange();
13717 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013718 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013719 // If we find the same expression in the enclosing data environment,
13720 // that is legal.
13721 IsEnclosedByDataEnvironmentExpr = true;
13722 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013723 }
13724
Samuel Antao90927002016-04-26 14:54:23 +000013725 QualType DerivedType =
13726 std::prev(CI)->getAssociatedDeclaration()->getType();
13727 SourceLocation DerivedLoc =
13728 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013729
13730 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13731 // If the type of a list item is a reference to a type T then the type
13732 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013733 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013734
13735 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13736 // A variable for which the type is pointer and an array section
13737 // derived from that variable must not appear as list items of map
13738 // clauses of the same construct.
13739 //
13740 // Also, cover one of the cases in:
13741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13742 // If any part of the original storage of a list item has corresponding
13743 // storage in the device data environment, all of the original storage
13744 // must have corresponding storage in the device data environment.
13745 //
13746 if (DerivedType->isAnyPointerType()) {
13747 if (CI == CE || SI == SE) {
13748 SemaRef.Diag(
13749 DerivedLoc,
13750 diag::err_omp_pointer_mapped_along_with_derived_section)
13751 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013752 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13753 << RE->getSourceRange();
13754 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013755 }
13756 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013757 SI->getAssociatedExpression()->getStmtClass() ||
13758 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13759 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013760 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013761 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013762 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013763 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13764 << RE->getSourceRange();
13765 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013766 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013767 }
13768
13769 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13770 // List items of map clauses in the same construct must not share
13771 // original storage.
13772 //
13773 // An expression is a subset of the other.
13774 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013775 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013776 if (CI != CE || SI != SE) {
13777 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13778 // a pointer.
13779 auto Begin =
13780 CI != CE ? CurComponents.begin() : StackComponents.begin();
13781 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13782 auto It = Begin;
13783 while (It != End && !It->getAssociatedDeclaration())
13784 std::advance(It, 1);
13785 assert(It != End &&
13786 "Expected at least one component with the declaration.");
13787 if (It != Begin && It->getAssociatedDeclaration()
13788 ->getType()
13789 .getCanonicalType()
13790 ->isAnyPointerType()) {
13791 IsEnclosedByDataEnvironmentExpr = false;
13792 EnclosingExpr = nullptr;
13793 return false;
13794 }
13795 }
Samuel Antao661c0902016-05-26 17:39:58 +000013796 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013797 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013798 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013799 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13800 << ERange;
13801 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013802 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13803 << RE->getSourceRange();
13804 return true;
13805 }
13806
13807 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013808 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013809 if (!CurrentRegionOnly && SI != SE)
13810 EnclosingExpr = RE;
13811
13812 // The current expression is a subset of the expression in the data
13813 // environment.
13814 IsEnclosedByDataEnvironmentExpr |=
13815 (!CurrentRegionOnly && CI != CE && SI == SE);
13816
13817 return false;
13818 });
13819
13820 if (CurrentRegionOnly)
13821 return FoundError;
13822
13823 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13824 // If any part of the original storage of a list item has corresponding
13825 // storage in the device data environment, all of the original storage must
13826 // have corresponding storage in the device data environment.
13827 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13828 // If a list item is an element of a structure, and a different element of
13829 // the structure has a corresponding list item in the device data environment
13830 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013831 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013832 // data environment prior to the task encountering the construct.
13833 //
13834 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13835 SemaRef.Diag(ELoc,
13836 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13837 << ERange;
13838 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13839 << EnclosingExpr->getSourceRange();
13840 return true;
13841 }
13842
13843 return FoundError;
13844}
13845
Michael Kruse4304e9d2019-02-19 16:38:20 +000013846// Look up the user-defined mapper given the mapper name and mapped type, and
13847// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000013848static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13849 CXXScopeSpec &MapperIdScopeSpec,
13850 const DeclarationNameInfo &MapperId,
13851 QualType Type,
13852 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013853 if (MapperIdScopeSpec.isInvalid())
13854 return ExprError();
13855 // Find all user-defined mappers with the given MapperId.
13856 SmallVector<UnresolvedSet<8>, 4> Lookups;
13857 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13858 Lookup.suppressDiagnostics();
13859 if (S) {
13860 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13861 NamedDecl *D = Lookup.getRepresentativeDecl();
13862 while (S && !S->isDeclScope(D))
13863 S = S->getParent();
13864 if (S)
13865 S = S->getParent();
13866 Lookups.emplace_back();
13867 Lookups.back().append(Lookup.begin(), Lookup.end());
13868 Lookup.clear();
13869 }
13870 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13871 // Extract the user-defined mappers with the given MapperId.
13872 Lookups.push_back(UnresolvedSet<8>());
13873 for (NamedDecl *D : ULE->decls()) {
13874 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13875 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13876 Lookups.back().addDecl(DMD);
13877 }
13878 }
13879 // Defer the lookup for dependent types. The results will be passed through
13880 // UnresolvedMapper on instantiation.
13881 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13882 Type->isInstantiationDependentType() ||
13883 Type->containsUnexpandedParameterPack() ||
13884 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13885 return !D->isInvalidDecl() &&
13886 (D->getType()->isDependentType() ||
13887 D->getType()->isInstantiationDependentType() ||
13888 D->getType()->containsUnexpandedParameterPack());
13889 })) {
13890 UnresolvedSet<8> URS;
13891 for (const UnresolvedSet<8> &Set : Lookups) {
13892 if (Set.empty())
13893 continue;
13894 URS.append(Set.begin(), Set.end());
13895 }
13896 return UnresolvedLookupExpr::Create(
13897 SemaRef.Context, /*NamingClass=*/nullptr,
13898 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13899 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13900 }
13901 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13902 // The type must be of struct, union or class type in C and C++
13903 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13904 return ExprEmpty();
13905 SourceLocation Loc = MapperId.getLoc();
13906 // Perform argument dependent lookup.
13907 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13908 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13909 // Return the first user-defined mapper with the desired type.
13910 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13911 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13912 if (!D->isInvalidDecl() &&
13913 SemaRef.Context.hasSameType(D->getType(), Type))
13914 return D;
13915 return nullptr;
13916 }))
13917 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13918 // Find the first user-defined mapper with a type derived from the desired
13919 // type.
13920 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13921 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13922 if (!D->isInvalidDecl() &&
13923 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13924 !Type.isMoreQualifiedThan(D->getType()))
13925 return D;
13926 return nullptr;
13927 })) {
13928 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13929 /*DetectVirtual=*/false);
13930 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13931 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13932 VD->getType().getUnqualifiedType()))) {
13933 if (SemaRef.CheckBaseClassAccess(
13934 Loc, VD->getType(), Type, Paths.front(),
13935 /*DiagID=*/0) != Sema::AR_inaccessible) {
13936 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13937 }
13938 }
13939 }
13940 }
13941 // Report error if a mapper is specified, but cannot be found.
13942 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13943 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13944 << Type << MapperId.getName();
13945 return ExprError();
13946 }
13947 return ExprEmpty();
13948}
13949
Samuel Antao661c0902016-05-26 17:39:58 +000013950namespace {
13951// Utility struct that gathers all the related lists associated with a mappable
13952// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013953struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013954 // The list of expressions.
13955 ArrayRef<Expr *> VarList;
13956 // The list of processed expressions.
13957 SmallVector<Expr *, 16> ProcessedVarList;
13958 // The mappble components for each expression.
13959 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13960 // The base declaration of the variable.
13961 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013962 // The reference to the user-defined mapper associated with every expression.
13963 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013964
13965 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13966 // We have a list of components and base declarations for each entry in the
13967 // variable list.
13968 VarComponents.reserve(VarList.size());
13969 VarBaseDeclarations.reserve(VarList.size());
13970 }
13971};
13972}
13973
13974// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013975// \a CKind. In the check process the valid expressions, mappable expression
13976// components, variables, and user-defined mappers are extracted and used to
13977// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13978// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13979// and \a MapperId are expected to be valid if the clause kind is 'map'.
13980static void checkMappableExpressionList(
13981 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13982 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013983 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13984 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013985 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013986 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013987 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13988 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013989 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013990
13991 // If the identifier of user-defined mapper is not specified, it is "default".
13992 // We do not change the actual name in this clause to distinguish whether a
13993 // mapper is specified explicitly, i.e., it is not explicitly specified when
13994 // MapperId.getName() is empty.
13995 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13996 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13997 MapperId.setName(DeclNames.getIdentifier(
13998 &SemaRef.getASTContext().Idents.get("default")));
13999 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014000
14001 // Iterators to find the current unresolved mapper expression.
14002 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
14003 bool UpdateUMIt = false;
14004 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014005
Samuel Antao90927002016-04-26 14:54:23 +000014006 // Keep track of the mappable components and base declarations in this clause.
14007 // Each entry in the list is going to have a list of components associated. We
14008 // record each set of the components so that we can build the clause later on.
14009 // In the end we should have the same amount of declarations and component
14010 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000014011
Alexey Bataeve3727102018-04-18 15:57:46 +000014012 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014013 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014014 SourceLocation ELoc = RE->getExprLoc();
14015
Michael Kruse4304e9d2019-02-19 16:38:20 +000014016 // Find the current unresolved mapper expression.
14017 if (UpdateUMIt && UMIt != UMEnd) {
14018 UMIt++;
14019 assert(
14020 UMIt != UMEnd &&
14021 "Expect the size of UnresolvedMappers to match with that of VarList");
14022 }
14023 UpdateUMIt = true;
14024 if (UMIt != UMEnd)
14025 UnresolvedMapper = *UMIt;
14026
Alexey Bataeve3727102018-04-18 15:57:46 +000014027 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014028
14029 if (VE->isValueDependent() || VE->isTypeDependent() ||
14030 VE->isInstantiationDependent() ||
14031 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000014032 // Try to find the associated user-defined mapper.
14033 ExprResult ER = buildUserDefinedMapperRef(
14034 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14035 VE->getType().getCanonicalType(), UnresolvedMapper);
14036 if (ER.isInvalid())
14037 continue;
14038 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000014039 // We can only analyze this information once the missing information is
14040 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000014041 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014042 continue;
14043 }
14044
Alexey Bataeve3727102018-04-18 15:57:46 +000014045 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014046
Samuel Antao5de996e2016-01-22 20:21:36 +000014047 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000014048 SemaRef.Diag(ELoc,
14049 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000014050 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014051 continue;
14052 }
14053
Samuel Antao90927002016-04-26 14:54:23 +000014054 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
14055 ValueDecl *CurDeclaration = nullptr;
14056
14057 // Obtain the array or member expression bases if required. Also, fill the
14058 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000014059 const Expr *BE = checkMapClauseExpressionBase(
14060 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000014061 if (!BE)
14062 continue;
14063
Samuel Antao90927002016-04-26 14:54:23 +000014064 assert(!CurComponents.empty() &&
14065 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014066
Patrick Lystere13b1e32019-01-02 19:28:48 +000014067 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
14068 // Add store "this" pointer to class in DSAStackTy for future checking
14069 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000014070 // Try to find the associated user-defined mapper.
14071 ExprResult ER = buildUserDefinedMapperRef(
14072 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14073 VE->getType().getCanonicalType(), UnresolvedMapper);
14074 if (ER.isInvalid())
14075 continue;
14076 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000014077 // Skip restriction checking for variable or field declarations
14078 MVLI.ProcessedVarList.push_back(RE);
14079 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14080 MVLI.VarComponents.back().append(CurComponents.begin(),
14081 CurComponents.end());
14082 MVLI.VarBaseDeclarations.push_back(nullptr);
14083 continue;
14084 }
14085
Samuel Antao90927002016-04-26 14:54:23 +000014086 // For the following checks, we rely on the base declaration which is
14087 // expected to be associated with the last component. The declaration is
14088 // expected to be a variable or a field (if 'this' is being mapped).
14089 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
14090 assert(CurDeclaration && "Null decl on map clause.");
14091 assert(
14092 CurDeclaration->isCanonicalDecl() &&
14093 "Expecting components to have associated only canonical declarations.");
14094
14095 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000014096 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000014097
14098 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000014099 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014100
14101 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000014102 // threadprivate variables cannot appear in a map clause.
14103 // OpenMP 4.5 [2.10.5, target update Construct]
14104 // threadprivate variables cannot appear in a from clause.
14105 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014106 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014107 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
14108 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000014109 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014110 continue;
14111 }
14112
Samuel Antao5de996e2016-01-22 20:21:36 +000014113 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
14114 // A list item cannot appear in both a map clause and a data-sharing
14115 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000014116
Samuel Antao5de996e2016-01-22 20:21:36 +000014117 // Check conflicts with other map clause expressions. We check the conflicts
14118 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000014119 // environment, because the restrictions are different. We only have to
14120 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000014121 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014122 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014123 break;
Samuel Antao661c0902016-05-26 17:39:58 +000014124 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014125 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014126 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014127 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014128
Samuel Antao661c0902016-05-26 17:39:58 +000014129 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000014130 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14131 // If the type of a list item is a reference to a type T then the type will
14132 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000014133 auto I = llvm::find_if(
14134 CurComponents,
14135 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
14136 return MC.getAssociatedDeclaration();
14137 });
14138 assert(I != CurComponents.end() && "Null decl on map clause.");
14139 QualType Type =
14140 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014141
Samuel Antao661c0902016-05-26 17:39:58 +000014142 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
14143 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000014144 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000014145 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014146 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000014147 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000014148 continue;
14149
Samuel Antao661c0902016-05-26 17:39:58 +000014150 if (CKind == OMPC_map) {
14151 // target enter data
14152 // OpenMP [2.10.2, Restrictions, p. 99]
14153 // A map-type must be specified in all map clauses and must be either
14154 // to or alloc.
14155 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
14156 if (DKind == OMPD_target_enter_data &&
14157 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
14158 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14159 << (IsMapTypeImplicit ? 1 : 0)
14160 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14161 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014162 continue;
14163 }
Samuel Antao661c0902016-05-26 17:39:58 +000014164
14165 // target exit_data
14166 // OpenMP [2.10.3, Restrictions, p. 102]
14167 // A map-type must be specified in all map clauses and must be either
14168 // from, release, or delete.
14169 if (DKind == OMPD_target_exit_data &&
14170 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
14171 MapType == OMPC_MAP_delete)) {
14172 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14173 << (IsMapTypeImplicit ? 1 : 0)
14174 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14175 << getOpenMPDirectiveName(DKind);
14176 continue;
14177 }
14178
14179 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
14180 // A list item cannot appear in both a map clause and a data-sharing
14181 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000014182 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
14183 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014184 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000014185 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000014186 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000014187 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000014188 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014189 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000014190 continue;
14191 }
14192 }
Michael Kruse01f670d2019-02-22 22:29:42 +000014193 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014194
Michael Kruse01f670d2019-02-22 22:29:42 +000014195 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000014196 ExprResult ER = buildUserDefinedMapperRef(
14197 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14198 Type.getCanonicalType(), UnresolvedMapper);
14199 if (ER.isInvalid())
14200 continue;
14201 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014202
Samuel Antao90927002016-04-26 14:54:23 +000014203 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000014204 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000014205
14206 // Store the components in the stack so that they can be used to check
14207 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000014208 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
14209 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000014210
14211 // Save the components and declaration to create the clause. For purposes of
14212 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000014213 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000014214 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14215 MVLI.VarComponents.back().append(CurComponents.begin(),
14216 CurComponents.end());
14217 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
14218 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014219 }
Samuel Antao661c0902016-05-26 17:39:58 +000014220}
14221
Michael Kruse4304e9d2019-02-19 16:38:20 +000014222OMPClause *Sema::ActOnOpenMPMapClause(
14223 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14224 ArrayRef<SourceLocation> MapTypeModifiersLoc,
14225 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
14226 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
14227 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
14228 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
14229 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
14230 OMPC_MAP_MODIFIER_unknown,
14231 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000014232 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
14233
14234 // Process map-type-modifiers, flag errors for duplicate modifiers.
14235 unsigned Count = 0;
14236 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
14237 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
14238 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
14239 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
14240 continue;
14241 }
14242 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000014243 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000014244 Modifiers[Count] = MapTypeModifiers[I];
14245 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
14246 ++Count;
14247 }
14248
Michael Kruse4304e9d2019-02-19 16:38:20 +000014249 MappableVarListInfo MVLI(VarList);
14250 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014251 MapperIdScopeSpec, MapperId, UnresolvedMappers,
14252 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000014253
Samuel Antao5de996e2016-01-22 20:21:36 +000014254 // We need to produce a map clause even if we don't have variables so that
14255 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000014256 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
14257 MVLI.VarBaseDeclarations, MVLI.VarComponents,
14258 MVLI.UDMapperList, Modifiers, ModifiersLoc,
14259 MapperIdScopeSpec.getWithLocInContext(Context),
14260 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014261}
Kelvin Li099bb8c2015-11-24 20:50:12 +000014262
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014263QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
14264 TypeResult ParsedType) {
14265 assert(ParsedType.isUsable());
14266
14267 QualType ReductionType = GetTypeFromParser(ParsedType.get());
14268 if (ReductionType.isNull())
14269 return QualType();
14270
14271 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
14272 // A type name in a declare reduction directive cannot be a function type, an
14273 // array type, a reference type, or a type qualified with const, volatile or
14274 // restrict.
14275 if (ReductionType.hasQualifiers()) {
14276 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
14277 return QualType();
14278 }
14279
14280 if (ReductionType->isFunctionType()) {
14281 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
14282 return QualType();
14283 }
14284 if (ReductionType->isReferenceType()) {
14285 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
14286 return QualType();
14287 }
14288 if (ReductionType->isArrayType()) {
14289 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
14290 return QualType();
14291 }
14292 return ReductionType;
14293}
14294
14295Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
14296 Scope *S, DeclContext *DC, DeclarationName Name,
14297 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
14298 AccessSpecifier AS, Decl *PrevDeclInScope) {
14299 SmallVector<Decl *, 8> Decls;
14300 Decls.reserve(ReductionTypes.size());
14301
14302 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000014303 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014304 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
14305 // A reduction-identifier may not be re-declared in the current scope for the
14306 // same type or for a type that is compatible according to the base language
14307 // rules.
14308 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14309 OMPDeclareReductionDecl *PrevDRD = nullptr;
14310 bool InCompoundScope = true;
14311 if (S != nullptr) {
14312 // Find previous declaration with the same name not referenced in other
14313 // declarations.
14314 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14315 InCompoundScope =
14316 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14317 LookupName(Lookup, S);
14318 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14319 /*AllowInlineNamespace=*/false);
14320 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000014321 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014322 while (Filter.hasNext()) {
14323 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
14324 if (InCompoundScope) {
14325 auto I = UsedAsPrevious.find(PrevDecl);
14326 if (I == UsedAsPrevious.end())
14327 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000014328 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014329 UsedAsPrevious[D] = true;
14330 }
14331 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14332 PrevDecl->getLocation();
14333 }
14334 Filter.done();
14335 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014336 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014337 if (!PrevData.second) {
14338 PrevDRD = PrevData.first;
14339 break;
14340 }
14341 }
14342 }
14343 } else if (PrevDeclInScope != nullptr) {
14344 auto *PrevDRDInScope = PrevDRD =
14345 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
14346 do {
14347 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
14348 PrevDRDInScope->getLocation();
14349 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
14350 } while (PrevDRDInScope != nullptr);
14351 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014352 for (const auto &TyData : ReductionTypes) {
14353 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014354 bool Invalid = false;
14355 if (I != PreviousRedeclTypes.end()) {
14356 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
14357 << TyData.first;
14358 Diag(I->second, diag::note_previous_definition);
14359 Invalid = true;
14360 }
14361 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
14362 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
14363 Name, TyData.first, PrevDRD);
14364 DC->addDecl(DRD);
14365 DRD->setAccess(AS);
14366 Decls.push_back(DRD);
14367 if (Invalid)
14368 DRD->setInvalidDecl();
14369 else
14370 PrevDRD = DRD;
14371 }
14372
14373 return DeclGroupPtrTy::make(
14374 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
14375}
14376
14377void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
14378 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14379
14380 // Enter new function scope.
14381 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014382 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014383 getCurFunction()->setHasOMPDeclareReductionCombiner();
14384
14385 if (S != nullptr)
14386 PushDeclContext(S, DRD);
14387 else
14388 CurContext = DRD;
14389
Faisal Valid143a0c2017-04-01 21:30:49 +000014390 PushExpressionEvaluationContext(
14391 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014392
14393 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014394 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
14395 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
14396 // uses semantics of argument handles by value, but it should be passed by
14397 // reference. C lang does not support references, so pass all parameters as
14398 // pointers.
14399 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014400 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014401 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014402 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
14403 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
14404 // uses semantics of argument handles by value, but it should be passed by
14405 // reference. C lang does not support references, so pass all parameters as
14406 // pointers.
14407 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014408 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014409 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
14410 if (S != nullptr) {
14411 PushOnScopeChains(OmpInParm, S);
14412 PushOnScopeChains(OmpOutParm, S);
14413 } else {
14414 DRD->addDecl(OmpInParm);
14415 DRD->addDecl(OmpOutParm);
14416 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014417 Expr *InE =
14418 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
14419 Expr *OutE =
14420 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
14421 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014422}
14423
14424void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
14425 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14426 DiscardCleanupsInEvaluationContext();
14427 PopExpressionEvaluationContext();
14428
14429 PopDeclContext();
14430 PopFunctionScopeInfo();
14431
14432 if (Combiner != nullptr)
14433 DRD->setCombiner(Combiner);
14434 else
14435 DRD->setInvalidDecl();
14436}
14437
Alexey Bataev070f43a2017-09-06 14:49:58 +000014438VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014439 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14440
14441 // Enter new function scope.
14442 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014443 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014444
14445 if (S != nullptr)
14446 PushDeclContext(S, DRD);
14447 else
14448 CurContext = DRD;
14449
Faisal Valid143a0c2017-04-01 21:30:49 +000014450 PushExpressionEvaluationContext(
14451 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014452
14453 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014454 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
14455 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
14456 // uses semantics of argument handles by value, but it should be passed by
14457 // reference. C lang does not support references, so pass all parameters as
14458 // pointers.
14459 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014460 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014461 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014462 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
14463 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
14464 // uses semantics of argument handles by value, but it should be passed by
14465 // reference. C lang does not support references, so pass all parameters as
14466 // pointers.
14467 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014468 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014469 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014470 if (S != nullptr) {
14471 PushOnScopeChains(OmpPrivParm, S);
14472 PushOnScopeChains(OmpOrigParm, S);
14473 } else {
14474 DRD->addDecl(OmpPrivParm);
14475 DRD->addDecl(OmpOrigParm);
14476 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014477 Expr *OrigE =
14478 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
14479 Expr *PrivE =
14480 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
14481 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000014482 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014483}
14484
Alexey Bataev070f43a2017-09-06 14:49:58 +000014485void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
14486 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014487 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14488 DiscardCleanupsInEvaluationContext();
14489 PopExpressionEvaluationContext();
14490
14491 PopDeclContext();
14492 PopFunctionScopeInfo();
14493
Alexey Bataev070f43a2017-09-06 14:49:58 +000014494 if (Initializer != nullptr) {
14495 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14496 } else if (OmpPrivParm->hasInit()) {
14497 DRD->setInitializer(OmpPrivParm->getInit(),
14498 OmpPrivParm->isDirectInit()
14499 ? OMPDeclareReductionDecl::DirectInit
14500 : OMPDeclareReductionDecl::CopyInit);
14501 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014502 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000014503 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014504}
14505
14506Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14507 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014508 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014509 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014510 if (S)
14511 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14512 /*AddToContext=*/false);
14513 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014514 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014515 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014516 }
14517 return DeclReductions;
14518}
14519
Michael Kruse251e1482019-02-01 20:25:04 +000014520TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14521 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14522 QualType T = TInfo->getType();
14523 if (D.isInvalidType())
14524 return true;
14525
14526 if (getLangOpts().CPlusPlus) {
14527 // Check that there are no default arguments (C++ only).
14528 CheckExtraCXXDefaultArguments(D);
14529 }
14530
14531 return CreateParsedType(T, TInfo);
14532}
14533
14534QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14535 TypeResult ParsedType) {
14536 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14537
14538 QualType MapperType = GetTypeFromParser(ParsedType.get());
14539 assert(!MapperType.isNull() && "Expect valid mapper type");
14540
14541 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14542 // The type must be of struct, union or class type in C and C++
14543 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14544 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14545 return QualType();
14546 }
14547 return MapperType;
14548}
14549
14550OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14551 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14552 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14553 Decl *PrevDeclInScope) {
14554 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14555 forRedeclarationInCurContext());
14556 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14557 // A mapper-identifier may not be redeclared in the current scope for the
14558 // same type or for a type that is compatible according to the base language
14559 // rules.
14560 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14561 OMPDeclareMapperDecl *PrevDMD = nullptr;
14562 bool InCompoundScope = true;
14563 if (S != nullptr) {
14564 // Find previous declaration with the same name not referenced in other
14565 // declarations.
14566 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14567 InCompoundScope =
14568 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14569 LookupName(Lookup, S);
14570 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14571 /*AllowInlineNamespace=*/false);
14572 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14573 LookupResult::Filter Filter = Lookup.makeFilter();
14574 while (Filter.hasNext()) {
14575 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14576 if (InCompoundScope) {
14577 auto I = UsedAsPrevious.find(PrevDecl);
14578 if (I == UsedAsPrevious.end())
14579 UsedAsPrevious[PrevDecl] = false;
14580 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14581 UsedAsPrevious[D] = true;
14582 }
14583 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14584 PrevDecl->getLocation();
14585 }
14586 Filter.done();
14587 if (InCompoundScope) {
14588 for (const auto &PrevData : UsedAsPrevious) {
14589 if (!PrevData.second) {
14590 PrevDMD = PrevData.first;
14591 break;
14592 }
14593 }
14594 }
14595 } else if (PrevDeclInScope) {
14596 auto *PrevDMDInScope = PrevDMD =
14597 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14598 do {
14599 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14600 PrevDMDInScope->getLocation();
14601 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14602 } while (PrevDMDInScope != nullptr);
14603 }
14604 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14605 bool Invalid = false;
14606 if (I != PreviousRedeclTypes.end()) {
14607 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14608 << MapperType << Name;
14609 Diag(I->second, diag::note_previous_definition);
14610 Invalid = true;
14611 }
14612 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14613 MapperType, VN, PrevDMD);
14614 DC->addDecl(DMD);
14615 DMD->setAccess(AS);
14616 if (Invalid)
14617 DMD->setInvalidDecl();
14618
14619 // Enter new function scope.
14620 PushFunctionScope();
14621 setFunctionHasBranchProtectedScope();
14622
14623 CurContext = DMD;
14624
14625 return DMD;
14626}
14627
14628void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14629 Scope *S,
14630 QualType MapperType,
14631 SourceLocation StartLoc,
14632 DeclarationName VN) {
14633 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14634 if (S)
14635 PushOnScopeChains(VD, S);
14636 else
14637 DMD->addDecl(VD);
14638 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14639 DMD->setMapperVarRef(MapperVarRefExpr);
14640}
14641
14642Sema::DeclGroupPtrTy
14643Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14644 ArrayRef<OMPClause *> ClauseList) {
14645 PopDeclContext();
14646 PopFunctionScopeInfo();
14647
14648 if (D) {
14649 if (S)
14650 PushOnScopeChains(D, S, /*AddToContext=*/false);
14651 D->CreateClauses(Context, ClauseList);
14652 }
14653
14654 return DeclGroupPtrTy::make(DeclGroupRef(D));
14655}
14656
David Majnemer9d168222016-08-05 17:44:54 +000014657OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014658 SourceLocation StartLoc,
14659 SourceLocation LParenLoc,
14660 SourceLocation EndLoc) {
14661 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014662 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014663
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014664 // OpenMP [teams Constrcut, Restrictions]
14665 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014666 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014667 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014668 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014669
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014670 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014671 OpenMPDirectiveKind CaptureRegion =
14672 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14673 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014674 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014675 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014676 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14677 HelperValStmt = buildPreInits(Context, Captures);
14678 }
14679
14680 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14681 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014682}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014683
14684OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14685 SourceLocation StartLoc,
14686 SourceLocation LParenLoc,
14687 SourceLocation EndLoc) {
14688 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014689 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014690
14691 // OpenMP [teams Constrcut, Restrictions]
14692 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014693 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014694 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014695 return nullptr;
14696
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014697 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014698 OpenMPDirectiveKind CaptureRegion =
14699 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14700 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014701 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014702 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014703 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14704 HelperValStmt = buildPreInits(Context, Captures);
14705 }
14706
14707 return new (Context) OMPThreadLimitClause(
14708 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014709}
Alexey Bataeva0569352015-12-01 10:17:31 +000014710
14711OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14712 SourceLocation StartLoc,
14713 SourceLocation LParenLoc,
14714 SourceLocation EndLoc) {
14715 Expr *ValExpr = Priority;
14716
14717 // OpenMP [2.9.1, task Constrcut]
14718 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014719 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014720 /*StrictlyPositive=*/false))
14721 return nullptr;
14722
14723 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14724}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014725
14726OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14727 SourceLocation StartLoc,
14728 SourceLocation LParenLoc,
14729 SourceLocation EndLoc) {
14730 Expr *ValExpr = Grainsize;
14731
14732 // OpenMP [2.9.2, taskloop Constrcut]
14733 // The parameter of the grainsize clause must be a positive integer
14734 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014735 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014736 /*StrictlyPositive=*/true))
14737 return nullptr;
14738
14739 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14740}
Alexey Bataev382967a2015-12-08 12:06:20 +000014741
14742OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14743 SourceLocation StartLoc,
14744 SourceLocation LParenLoc,
14745 SourceLocation EndLoc) {
14746 Expr *ValExpr = NumTasks;
14747
14748 // OpenMP [2.9.2, taskloop Constrcut]
14749 // The parameter of the num_tasks clause must be a positive integer
14750 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014751 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014752 /*StrictlyPositive=*/true))
14753 return nullptr;
14754
14755 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14756}
14757
Alexey Bataev28c75412015-12-15 08:19:24 +000014758OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14759 SourceLocation LParenLoc,
14760 SourceLocation EndLoc) {
14761 // OpenMP [2.13.2, critical construct, Description]
14762 // ... where hint-expression is an integer constant expression that evaluates
14763 // to a valid lock hint.
14764 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14765 if (HintExpr.isInvalid())
14766 return nullptr;
14767 return new (Context)
14768 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14769}
14770
Carlo Bertollib4adf552016-01-15 18:50:31 +000014771OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14772 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14773 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14774 SourceLocation EndLoc) {
14775 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14776 std::string Values;
14777 Values += "'";
14778 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14779 Values += "'";
14780 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14781 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14782 return nullptr;
14783 }
14784 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014785 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014786 if (ChunkSize) {
14787 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14788 !ChunkSize->isInstantiationDependent() &&
14789 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014790 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014791 ExprResult Val =
14792 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14793 if (Val.isInvalid())
14794 return nullptr;
14795
14796 ValExpr = Val.get();
14797
14798 // OpenMP [2.7.1, Restrictions]
14799 // chunk_size must be a loop invariant integer expression with a positive
14800 // value.
14801 llvm::APSInt Result;
14802 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14803 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14804 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14805 << "dist_schedule" << ChunkSize->getSourceRange();
14806 return nullptr;
14807 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014808 } else if (getOpenMPCaptureRegionForClause(
14809 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14810 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014811 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014812 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014813 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014814 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14815 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014816 }
14817 }
14818 }
14819
14820 return new (Context)
14821 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014822 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014823}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014824
14825OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14826 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14827 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14828 SourceLocation KindLoc, SourceLocation EndLoc) {
14829 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014830 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014831 std::string Value;
14832 SourceLocation Loc;
14833 Value += "'";
14834 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14835 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014836 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014837 Loc = MLoc;
14838 } else {
14839 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014840 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014841 Loc = KindLoc;
14842 }
14843 Value += "'";
14844 Diag(Loc, diag::err_omp_unexpected_clause_value)
14845 << Value << getOpenMPClauseName(OMPC_defaultmap);
14846 return nullptr;
14847 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014848 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014849
14850 return new (Context)
14851 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14852}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014853
14854bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14855 DeclContext *CurLexicalContext = getCurLexicalContext();
14856 if (!CurLexicalContext->isFileContext() &&
14857 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014858 !CurLexicalContext->isExternCXXContext() &&
14859 !isa<CXXRecordDecl>(CurLexicalContext) &&
14860 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14861 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14862 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014863 Diag(Loc, diag::err_omp_region_not_file_context);
14864 return false;
14865 }
Kelvin Libc38e632018-09-10 02:07:09 +000014866 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014867 return true;
14868}
14869
14870void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014871 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014872 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014873 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014874}
14875
David Majnemer9d168222016-08-05 17:44:54 +000014876void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14877 CXXScopeSpec &ScopeSpec,
14878 const DeclarationNameInfo &Id,
14879 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14880 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014881 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14882 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14883
14884 if (Lookup.isAmbiguous())
14885 return;
14886 Lookup.suppressDiagnostics();
14887
14888 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000014889 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014890 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000014891 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014892 CTK_ErrorRecovery)) {
14893 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14894 << Id.getName());
14895 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14896 return;
14897 }
14898
14899 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14900 return;
14901 }
14902
14903 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014904 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14905 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014906 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14907 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014908 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14909 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14910 cast<ValueDecl>(ND));
14911 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014912 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014913 ND->addAttr(A);
14914 if (ASTMutationListener *ML = Context.getASTMutationListener())
14915 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014916 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014917 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014918 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14919 << Id.getName();
14920 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014921 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014922 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014923 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014924}
14925
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014926static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14927 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014928 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014929 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014930 auto *VD = cast<VarDecl>(D);
14931 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14932 return;
14933 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14934 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014935}
14936
14937static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14938 Sema &SemaRef, DSAStackTy *Stack,
14939 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014940 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14941 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14942 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014943}
14944
Kelvin Li1ce87c72017-12-12 20:08:12 +000014945void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14946 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014947 if (!D || D->isInvalidDecl())
14948 return;
14949 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014950 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014951 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014952 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014953 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14954 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014955 return;
14956 // 2.10.6: threadprivate variable cannot appear in a declare target
14957 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014958 if (DSAStack->isThreadPrivate(VD)) {
14959 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014960 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014961 return;
14962 }
14963 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014964 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14965 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014966 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014967 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14968 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14969 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014970 assert(IdLoc.isValid() && "Source location is expected");
14971 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14972 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14973 return;
14974 }
14975 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014976 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14977 // Problem if any with var declared with incomplete type will be reported
14978 // as normal, so no need to check it here.
14979 if ((E || !VD->getType()->isIncompleteType()) &&
14980 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14981 return;
14982 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14983 // Checking declaration inside declare target region.
14984 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14985 isa<FunctionTemplateDecl>(D)) {
14986 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14987 Context, OMPDeclareTargetDeclAttr::MT_To);
14988 D->addAttr(A);
14989 if (ASTMutationListener *ML = Context.getASTMutationListener())
14990 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14991 }
14992 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014993 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014994 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014995 if (!E)
14996 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014997 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14998}
Samuel Antao661c0902016-05-26 17:39:58 +000014999
15000OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000015001 CXXScopeSpec &MapperIdScopeSpec,
15002 DeclarationNameInfo &MapperId,
15003 const OMPVarListLocTy &Locs,
15004 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000015005 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015006 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
15007 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000015008 if (MVLI.ProcessedVarList.empty())
15009 return nullptr;
15010
Michael Kruse01f670d2019-02-22 22:29:42 +000015011 return OMPToClause::Create(
15012 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15013 MVLI.VarComponents, MVLI.UDMapperList,
15014 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000015015}
Samuel Antaoec172c62016-05-26 17:49:04 +000015016
15017OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000015018 CXXScopeSpec &MapperIdScopeSpec,
15019 DeclarationNameInfo &MapperId,
15020 const OMPVarListLocTy &Locs,
15021 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015022 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015023 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
15024 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000015025 if (MVLI.ProcessedVarList.empty())
15026 return nullptr;
15027
Michael Kruse0336c752019-02-25 20:34:15 +000015028 return OMPFromClause::Create(
15029 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15030 MVLI.VarComponents, MVLI.UDMapperList,
15031 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000015032}
Carlo Bertolli2404b172016-07-13 15:37:16 +000015033
15034OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015035 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000015036 MappableVarListInfo MVLI(VarList);
15037 SmallVector<Expr *, 8> PrivateCopies;
15038 SmallVector<Expr *, 8> Inits;
15039
Alexey Bataeve3727102018-04-18 15:57:46 +000015040 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015041 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
15042 SourceLocation ELoc;
15043 SourceRange ERange;
15044 Expr *SimpleRefExpr = RefExpr;
15045 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15046 if (Res.second) {
15047 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000015048 MVLI.ProcessedVarList.push_back(RefExpr);
15049 PrivateCopies.push_back(nullptr);
15050 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015051 }
15052 ValueDecl *D = Res.first;
15053 if (!D)
15054 continue;
15055
15056 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000015057 Type = Type.getNonReferenceType().getUnqualifiedType();
15058
15059 auto *VD = dyn_cast<VarDecl>(D);
15060
15061 // Item should be a pointer or reference to pointer.
15062 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015063 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
15064 << 0 << RefExpr->getSourceRange();
15065 continue;
15066 }
Samuel Antaocc10b852016-07-28 14:23:26 +000015067
15068 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000015069 auto VDPrivate =
15070 buildVarDecl(*this, ELoc, Type, D->getName(),
15071 D->hasAttrs() ? &D->getAttrs() : nullptr,
15072 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000015073 if (VDPrivate->isInvalidDecl())
15074 continue;
15075
15076 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000015077 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000015078 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15079
15080 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000015081 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000015082 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000015083 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
15084 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000015085 AddInitializerToDecl(VDPrivate,
15086 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000015087 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000015088
15089 // If required, build a capture to implement the privatization initialized
15090 // with the current list item value.
15091 DeclRefExpr *Ref = nullptr;
15092 if (!VD)
15093 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15094 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
15095 PrivateCopies.push_back(VDPrivateRefExpr);
15096 Inits.push_back(VDInitRefExpr);
15097
15098 // We need to add a data sharing attribute for this variable to make sure it
15099 // is correctly captured. A variable that shows up in a use_device_ptr has
15100 // similar properties of a first private variable.
15101 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15102
15103 // Create a mappable component for the list item. List items in this clause
15104 // only need a component.
15105 MVLI.VarBaseDeclarations.push_back(D);
15106 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15107 MVLI.VarComponents.back().push_back(
15108 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000015109 }
15110
Samuel Antaocc10b852016-07-28 14:23:26 +000015111 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000015112 return nullptr;
15113
Samuel Antaocc10b852016-07-28 14:23:26 +000015114 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000015115 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
15116 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015117}
Carlo Bertolli70594e92016-07-13 17:16:49 +000015118
15119OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015120 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000015121 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000015122 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000015123 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000015124 SourceLocation ELoc;
15125 SourceRange ERange;
15126 Expr *SimpleRefExpr = RefExpr;
15127 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15128 if (Res.second) {
15129 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000015130 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015131 }
15132 ValueDecl *D = Res.first;
15133 if (!D)
15134 continue;
15135
15136 QualType Type = D->getType();
15137 // item should be a pointer or array or reference to pointer or array
15138 if (!Type.getNonReferenceType()->isPointerType() &&
15139 !Type.getNonReferenceType()->isArrayType()) {
15140 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
15141 << 0 << RefExpr->getSourceRange();
15142 continue;
15143 }
Samuel Antao6890b092016-07-28 14:25:09 +000015144
15145 // Check if the declaration in the clause does not show up in any data
15146 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000015147 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000015148 if (isOpenMPPrivate(DVar.CKind)) {
15149 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15150 << getOpenMPClauseName(DVar.CKind)
15151 << getOpenMPClauseName(OMPC_is_device_ptr)
15152 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015153 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000015154 continue;
15155 }
15156
Alexey Bataeve3727102018-04-18 15:57:46 +000015157 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000015158 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000015159 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000015160 [&ConflictExpr](
15161 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
15162 OpenMPClauseKind) -> bool {
15163 ConflictExpr = R.front().getAssociatedExpression();
15164 return true;
15165 })) {
15166 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
15167 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
15168 << ConflictExpr->getSourceRange();
15169 continue;
15170 }
15171
15172 // Store the components in the stack so that they can be used to check
15173 // against other clauses later on.
15174 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
15175 DSAStack->addMappableExpressionComponents(
15176 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
15177
15178 // Record the expression we've just processed.
15179 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
15180
15181 // Create a mappable component for the list item. List items in this clause
15182 // only need a component. We use a null declaration to signal fields in
15183 // 'this'.
15184 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
15185 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
15186 "Unexpected device pointer expression!");
15187 MVLI.VarBaseDeclarations.push_back(
15188 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
15189 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15190 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015191 }
15192
Samuel Antao6890b092016-07-28 14:25:09 +000015193 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000015194 return nullptr;
15195
Michael Kruse4304e9d2019-02-19 16:38:20 +000015196 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
15197 MVLI.VarBaseDeclarations,
15198 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015199}
Alexey Bataeve04483e2019-03-27 14:14:31 +000015200
15201OMPClause *Sema::ActOnOpenMPAllocateClause(
15202 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15203 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15204 if (Allocator) {
15205 // OpenMP [2.11.4 allocate Clause, Description]
15206 // allocator is an expression of omp_allocator_handle_t type.
15207 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
15208 return nullptr;
15209
15210 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
15211 if (AllocatorRes.isInvalid())
15212 return nullptr;
15213 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
15214 DSAStack->getOMPAllocatorHandleT(),
15215 Sema::AA_Initializing,
15216 /*AllowExplicit=*/true);
15217 if (AllocatorRes.isInvalid())
15218 return nullptr;
15219 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000015220 } else {
15221 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
15222 // allocate clauses that appear on a target construct or on constructs in a
15223 // target region must specify an allocator expression unless a requires
15224 // directive with the dynamic_allocators clause is present in the same
15225 // compilation unit.
15226 if (LangOpts.OpenMPIsDevice &&
15227 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
15228 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000015229 }
15230 // Analyze and build list of variables.
15231 SmallVector<Expr *, 8> Vars;
15232 for (Expr *RefExpr : VarList) {
15233 assert(RefExpr && "NULL expr in OpenMP private clause.");
15234 SourceLocation ELoc;
15235 SourceRange ERange;
15236 Expr *SimpleRefExpr = RefExpr;
15237 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15238 if (Res.second) {
15239 // It will be analyzed later.
15240 Vars.push_back(RefExpr);
15241 }
15242 ValueDecl *D = Res.first;
15243 if (!D)
15244 continue;
15245
15246 auto *VD = dyn_cast<VarDecl>(D);
15247 DeclRefExpr *Ref = nullptr;
15248 if (!VD && !CurContext->isDependentContext())
15249 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15250 Vars.push_back((VD || CurContext->isDependentContext())
15251 ? RefExpr->IgnoreParens()
15252 : Ref);
15253 }
15254
15255 if (Vars.empty())
15256 return nullptr;
15257
15258 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
15259 ColonLoc, EndLoc, Vars);
15260}