blob: 7e75a98070878ca90c59d82dac2bf1d928414172 [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()) ||
1579 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1580 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1581 !Context.getTargetInfo().hasInt128Type()))
1582 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1583 << Ty << E->getSourceRange();
1584}
1585
Alexey Bataeve3727102018-04-18 15:57:46 +00001586bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001587 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1588
Alexey Bataeve3727102018-04-18 15:57:46 +00001589 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001590 bool IsByRef = true;
1591
1592 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001593 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001594 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001595
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001596 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001597 // This table summarizes how a given variable should be passed to the device
1598 // given its type and the clauses where it appears. This table is based on
1599 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1600 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1601 //
1602 // =========================================================================
1603 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1604 // | |(tofrom:scalar)| | pvt | | | |
1605 // =========================================================================
1606 // | scl | | | | - | | bycopy|
1607 // | scl | | - | x | - | - | bycopy|
1608 // | scl | | x | - | - | - | null |
1609 // | scl | x | | | - | | byref |
1610 // | scl | x | - | x | - | - | bycopy|
1611 // | scl | x | x | - | - | - | null |
1612 // | scl | | - | - | - | x | byref |
1613 // | scl | x | - | - | - | x | byref |
1614 //
1615 // | agg | n.a. | | | - | | byref |
1616 // | agg | n.a. | - | x | - | - | byref |
1617 // | agg | n.a. | x | - | - | - | null |
1618 // | agg | n.a. | - | - | - | x | byref |
1619 // | agg | n.a. | - | - | - | x[] | byref |
1620 //
1621 // | ptr | n.a. | | | - | | bycopy|
1622 // | ptr | n.a. | - | x | - | - | bycopy|
1623 // | ptr | n.a. | x | - | - | - | null |
1624 // | ptr | n.a. | - | - | - | x | byref |
1625 // | ptr | n.a. | - | - | - | x[] | bycopy|
1626 // | ptr | n.a. | - | - | x | | bycopy|
1627 // | ptr | n.a. | - | - | x | x | bycopy|
1628 // | ptr | n.a. | - | - | x | x[] | bycopy|
1629 // =========================================================================
1630 // Legend:
1631 // scl - scalar
1632 // ptr - pointer
1633 // agg - aggregate
1634 // x - applies
1635 // - - invalid in this combination
1636 // [] - mapped with an array section
1637 // byref - should be mapped by reference
1638 // byval - should be mapped by value
1639 // null - initialize a local variable to null on the device
1640 //
1641 // Observations:
1642 // - All scalar declarations that show up in a map clause have to be passed
1643 // by reference, because they may have been mapped in the enclosing data
1644 // environment.
1645 // - If the scalar value does not fit the size of uintptr, it has to be
1646 // passed by reference, regardless the result in the table above.
1647 // - For pointers mapped by value that have either an implicit map or an
1648 // array section, the runtime library may pass the NULL value to the
1649 // device instead of the value passed to it by the compiler.
1650
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001651 if (Ty->isReferenceType())
1652 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001653
1654 // Locate map clauses and see if the variable being captured is referred to
1655 // in any of those clauses. Here we only care about variables, not fields,
1656 // because fields are part of aggregates.
1657 bool IsVariableUsedInMapClause = false;
1658 bool IsVariableAssociatedWithSection = false;
1659
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001660 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001661 D, Level,
1662 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1663 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001664 MapExprComponents,
1665 OpenMPClauseKind WhereFoundClauseKind) {
1666 // Only the map clause information influences how a variable is
1667 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001668 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001669 if (WhereFoundClauseKind != OMPC_map)
1670 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001671
1672 auto EI = MapExprComponents.rbegin();
1673 auto EE = MapExprComponents.rend();
1674
1675 assert(EI != EE && "Invalid map expression!");
1676
1677 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1678 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1679
1680 ++EI;
1681 if (EI == EE)
1682 return false;
1683
1684 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1685 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1686 isa<MemberExpr>(EI->getAssociatedExpression())) {
1687 IsVariableAssociatedWithSection = true;
1688 // There is nothing more we need to know about this variable.
1689 return true;
1690 }
1691
1692 // Keep looking for more map info.
1693 return false;
1694 });
1695
1696 if (IsVariableUsedInMapClause) {
1697 // If variable is identified in a map clause it is always captured by
1698 // reference except if it is a pointer that is dereferenced somehow.
1699 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1700 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001701 // By default, all the data that has a scalar type is mapped by copy
1702 // (except for reduction variables).
1703 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001704 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1705 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001706 !Ty->isScalarType() ||
1707 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1708 DSAStack->hasExplicitDSA(
1709 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001710 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001711 }
1712
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001713 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001714 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001715 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1716 !Ty->isAnyPointerType()) ||
1717 !DSAStack->hasExplicitDSA(
1718 D,
1719 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1720 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001721 // If the variable is artificial and must be captured by value - try to
1722 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001723 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1724 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001725 }
1726
Samuel Antao86ace552016-04-27 22:40:57 +00001727 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001728 // and alignment, because the runtime library only deals with uintptr types.
1729 // If it does not fit the uintptr size, we need to pass the data by reference
1730 // instead.
1731 if (!IsByRef &&
1732 (Ctx.getTypeSizeInChars(Ty) >
1733 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001734 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001735 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001736 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001737
1738 return IsByRef;
1739}
1740
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001741unsigned Sema::getOpenMPNestingLevel() const {
1742 assert(getLangOpts().OpenMP);
1743 return DSAStack->getNestingLevel();
1744}
1745
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001746bool Sema::isInOpenMPTargetExecutionDirective() const {
1747 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1748 !DSAStack->isClauseParsingMode()) ||
1749 DSAStack->hasDirective(
1750 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1751 SourceLocation) -> bool {
1752 return isOpenMPTargetExecutionDirective(K);
1753 },
1754 false);
1755}
1756
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001757VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1758 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001759 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001760 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001761
Richard Smith0621a8f2019-05-31 00:45:10 +00001762 // If we want to determine whether the variable should be captured from the
1763 // perspective of the current capturing scope, and we've already left all the
1764 // capturing scopes of the top directive on the stack, check from the
1765 // perspective of its parent directive (if any) instead.
1766 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1767 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1768
Samuel Antao4be30e92015-10-02 17:14:03 +00001769 // If we are attempting to capture a global variable in a directive with
1770 // 'target' we return true so that this global is also mapped to the device.
1771 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001772 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001773 if (VD && !VD->hasLocalStorage() &&
1774 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1775 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001776 // Try to mark variable as declare target if it is used in capturing
1777 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001778 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001779 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001780 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001781 } else if (isInOpenMPTargetExecutionDirective()) {
1782 // If the declaration is enclosed in a 'declare target' directive,
1783 // then it should not be captured.
1784 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001785 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001786 return nullptr;
1787 return VD;
1788 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001789 }
Alexey Bataev60705422018-10-30 15:50:12 +00001790 // Capture variables captured by reference in lambdas for target-based
1791 // directives.
Richard Smith0621a8f2019-05-31 00:45:10 +00001792 // FIXME: Triggering capture from here is completely inappropriate.
Alexey Bataev60705422018-10-30 15:50:12 +00001793 if (VD && !DSAStack->isClauseParsingMode()) {
1794 if (const auto *RD = VD->getType()
1795 .getCanonicalType()
1796 .getNonReferenceType()
1797 ->getAsCXXRecordDecl()) {
1798 bool SavedForceCaptureByReferenceInTargetExecutable =
1799 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1800 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Richard Smith0621a8f2019-05-31 00:45:10 +00001801 InParentDirectiveRAII.disable();
Alexey Bataevd1840e52018-11-16 21:13:33 +00001802 if (RD->isLambda()) {
1803 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1804 FieldDecl *ThisCapture;
1805 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001806 for (const LambdaCapture &LC : RD->captures()) {
1807 if (LC.getCaptureKind() == LCK_ByRef) {
1808 VarDecl *VD = LC.getCapturedVar();
1809 DeclContext *VDC = VD->getDeclContext();
1810 if (!VDC->Encloses(CurContext))
1811 continue;
1812 DSAStackTy::DSAVarData DVarPrivate =
1813 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1814 // Do not capture already captured variables.
1815 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1816 DVarPrivate.CKind == OMPC_unknown &&
1817 !DSAStack->checkMappableExprComponentListsForDecl(
1818 D, /*CurrentRegionOnly=*/true,
1819 [](OMPClauseMappableExprCommon::
1820 MappableExprComponentListRef,
1821 OpenMPClauseKind) { return true; }))
1822 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1823 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001824 QualType ThisTy = getCurrentThisType();
1825 if (!ThisTy.isNull() &&
1826 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1827 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001828 }
1829 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001830 }
Richard Smith0621a8f2019-05-31 00:45:10 +00001831 if (CheckScopeInfo && DSAStack->isBodyComplete())
1832 InParentDirectiveRAII.enable();
Alexey Bataev60705422018-10-30 15:50:12 +00001833 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1834 SavedForceCaptureByReferenceInTargetExecutable);
1835 }
1836 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001837
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001838 if (CheckScopeInfo) {
1839 bool OpenMPFound = false;
1840 for (unsigned I = StopAt + 1; I > 0; --I) {
1841 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1842 if(!isa<CapturingScopeInfo>(FSI))
1843 return nullptr;
1844 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1845 if (RSI->CapRegionKind == CR_OpenMP) {
1846 OpenMPFound = true;
1847 break;
1848 }
1849 }
1850 if (!OpenMPFound)
1851 return nullptr;
1852 }
1853
Alexey Bataev48977c32015-08-04 08:10:48 +00001854 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1855 (!DSAStack->isClauseParsingMode() ||
1856 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001857 auto &&Info = DSAStack->isLoopControlVariable(D);
1858 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001859 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001860 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001861 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001862 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001863 DSAStackTy::DSAVarData DVarPrivate =
1864 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001865 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001866 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001867 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1868 [](OpenMPDirectiveKind) { return true; },
1869 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001870 // The variable is not private or it is the variable in the directive with
1871 // default(none) clause and not used in any clause.
1872 if (DVarPrivate.CKind != OMPC_unknown ||
1873 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001874 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001875 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001876 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001877}
1878
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001879void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1880 unsigned Level) const {
1881 SmallVector<OpenMPDirectiveKind, 4> Regions;
1882 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1883 FunctionScopesIndex -= Regions.size();
1884}
1885
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001886void Sema::startOpenMPLoop() {
1887 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1888 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1889 DSAStack->loopInit();
1890}
1891
Alexey Bataeve3727102018-04-18 15:57:46 +00001892bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001893 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001894 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1895 if (DSAStack->getAssociatedLoops() > 0 &&
1896 !DSAStack->isLoopStarted()) {
1897 DSAStack->resetPossibleLoopCounter(D);
1898 DSAStack->loopStart();
1899 return true;
1900 }
1901 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1902 DSAStack->isLoopControlVariable(D).first) &&
1903 !DSAStack->hasExplicitDSA(
1904 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1905 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1906 return true;
1907 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001908 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001909 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001910 (DSAStack->isClauseParsingMode() &&
1911 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001912 // Consider taskgroup reduction descriptor variable a private to avoid
1913 // possible capture in the region.
1914 (DSAStack->hasExplicitDirective(
1915 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1916 Level) &&
1917 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001918}
1919
Alexey Bataeve3727102018-04-18 15:57:46 +00001920void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1921 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001922 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1923 D = getCanonicalDecl(D);
1924 OpenMPClauseKind OMPC = OMPC_unknown;
1925 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1926 const unsigned NewLevel = I - 1;
1927 if (DSAStack->hasExplicitDSA(D,
1928 [&OMPC](const OpenMPClauseKind K) {
1929 if (isOpenMPPrivate(K)) {
1930 OMPC = K;
1931 return true;
1932 }
1933 return false;
1934 },
1935 NewLevel))
1936 break;
1937 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1938 D, NewLevel,
1939 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1940 OpenMPClauseKind) { return true; })) {
1941 OMPC = OMPC_map;
1942 break;
1943 }
1944 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1945 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001946 OMPC = OMPC_map;
1947 if (D->getType()->isScalarType() &&
1948 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1949 DefaultMapAttributes::DMA_tofrom_scalar)
1950 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001951 break;
1952 }
1953 }
1954 if (OMPC != OMPC_unknown)
1955 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1956}
1957
Alexey Bataeve3727102018-04-18 15:57:46 +00001958bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1959 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001960 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1961 // Return true if the current level is no longer enclosed in a target region.
1962
Alexey Bataeve3727102018-04-18 15:57:46 +00001963 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001964 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001965 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1966 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001967}
1968
Alexey Bataeved09d242014-05-28 05:53:51 +00001969void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001970
1971void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1972 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001973 Scope *CurScope, SourceLocation Loc) {
1974 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001975 PushExpressionEvaluationContext(
1976 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001977}
1978
Alexey Bataevaac108a2015-06-23 04:51:00 +00001979void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1980 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001981}
1982
Alexey Bataevaac108a2015-06-23 04:51:00 +00001983void Sema::EndOpenMPClause() {
1984 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001985}
1986
Alexey Bataeve106f252019-04-01 14:25:31 +00001987static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
1988 ArrayRef<OMPClause *> Clauses);
1989
Alexey Bataev758e55e2013-09-06 18:03:48 +00001990void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001991 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1992 // A variable of class type (or array thereof) that appears in a lastprivate
1993 // clause requires an accessible, unambiguous default constructor for the
1994 // class type, unless the list item is also specified in a firstprivate
1995 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001996 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1997 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001998 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1999 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002000 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002001 if (DE->isValueDependent() || DE->isTypeDependent()) {
2002 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002003 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002004 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002005 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002006 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002007 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002008 const DSAStackTy::DSAVarData DVar =
2009 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002010 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002011 // Generate helper private variable and initialize it with the
2012 // default value. The address of the original variable is replaced
2013 // by the address of the new private variable in CodeGen. This new
2014 // variable is not added to IdResolver, so the code in the OpenMP
2015 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002016 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002017 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002018 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002019 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002020 if (VDPrivate->isInvalidDecl()) {
2021 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002022 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002023 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002024 PrivateCopies.push_back(buildDeclRefExpr(
2025 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002026 } else {
2027 // The variable is also a firstprivate, so initialization sequence
2028 // for private copy is generated already.
2029 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002030 }
2031 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002032 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002033 }
2034 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002035 // Check allocate clauses.
2036 if (!CurContext->isDependentContext())
2037 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002038 }
2039
Alexey Bataev758e55e2013-09-06 18:03:48 +00002040 DSAStack->pop();
2041 DiscardCleanupsInEvaluationContext();
2042 PopExpressionEvaluationContext();
2043}
2044
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002045static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2046 Expr *NumIterations, Sema &SemaRef,
2047 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002048
Alexey Bataeva769e072013-03-22 06:34:35 +00002049namespace {
2050
Alexey Bataeve3727102018-04-18 15:57:46 +00002051class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002052private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002053 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002054
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002055public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002056 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002057 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002058 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002059 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002060 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002061 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2062 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002063 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002064 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002065 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002066
2067 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2068 return llvm::make_unique<VarDeclFilterCCC>(*this);
2069 }
2070
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002071};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002072
Alexey Bataeve3727102018-04-18 15:57:46 +00002073class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002074private:
2075 Sema &SemaRef;
2076
2077public:
2078 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2079 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2080 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002081 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2082 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002083 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2084 SemaRef.getCurScope());
2085 }
2086 return false;
2087 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002088
2089 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2090 return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
2091 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002092};
2093
Alexey Bataeved09d242014-05-28 05:53:51 +00002094} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002095
2096ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2097 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002098 const DeclarationNameInfo &Id,
2099 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002100 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2101 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2102
2103 if (Lookup.isAmbiguous())
2104 return ExprError();
2105
2106 VarDecl *VD;
2107 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002108 VarDeclFilterCCC CCC(*this);
2109 if (TypoCorrection Corrected =
2110 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2111 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002112 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002113 PDiag(Lookup.empty()
2114 ? diag::err_undeclared_var_use_suggest
2115 : diag::err_omp_expected_var_arg_suggest)
2116 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002117 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002118 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002119 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2120 : diag::err_omp_expected_var_arg)
2121 << Id.getName();
2122 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002123 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002124 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2125 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2126 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2127 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002128 }
2129 Lookup.suppressDiagnostics();
2130
2131 // OpenMP [2.9.2, Syntax, C/C++]
2132 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002133 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002134 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002135 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002136 bool IsDecl =
2137 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002138 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002139 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2140 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002141 return ExprError();
2142 }
2143
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002144 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002145 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002146 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2147 // A threadprivate directive for file-scope variables must appear outside
2148 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002149 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2150 !getCurLexicalContext()->isTranslationUnit()) {
2151 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002152 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002153 bool IsDecl =
2154 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2155 Diag(VD->getLocation(),
2156 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2157 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002158 return ExprError();
2159 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002160 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2161 // A threadprivate directive for static class member variables must appear
2162 // in the class definition, in the same scope in which the member
2163 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002164 if (CanonicalVD->isStaticDataMember() &&
2165 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2166 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002167 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002168 bool IsDecl =
2169 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2170 Diag(VD->getLocation(),
2171 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2172 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002173 return ExprError();
2174 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002175 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2176 // A threadprivate directive for namespace-scope variables must appear
2177 // outside any definition or declaration other than the namespace
2178 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002179 if (CanonicalVD->getDeclContext()->isNamespace() &&
2180 (!getCurLexicalContext()->isFileContext() ||
2181 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2182 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002183 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002184 bool IsDecl =
2185 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2186 Diag(VD->getLocation(),
2187 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2188 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002189 return ExprError();
2190 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002191 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2192 // A threadprivate directive for static block-scope variables must appear
2193 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002194 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002195 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002196 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002197 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002198 bool IsDecl =
2199 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2200 Diag(VD->getLocation(),
2201 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2202 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002203 return ExprError();
2204 }
2205
2206 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2207 // A threadprivate directive must lexically precede all references to any
2208 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002209 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2210 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002211 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002212 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002213 return ExprError();
2214 }
2215
2216 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002217 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2218 SourceLocation(), VD,
2219 /*RefersToEnclosingVariableOrCapture=*/false,
2220 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002221}
2222
Alexey Bataeved09d242014-05-28 05:53:51 +00002223Sema::DeclGroupPtrTy
2224Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2225 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002226 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002227 CurContext->addDecl(D);
2228 return DeclGroupPtrTy::make(DeclGroupRef(D));
2229 }
David Blaikie0403cb12016-01-15 23:43:25 +00002230 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002231}
2232
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002233namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002234class LocalVarRefChecker final
2235 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002236 Sema &SemaRef;
2237
2238public:
2239 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002240 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002241 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002242 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002243 diag::err_omp_local_var_in_threadprivate_init)
2244 << E->getSourceRange();
2245 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2246 << VD << VD->getSourceRange();
2247 return true;
2248 }
2249 }
2250 return false;
2251 }
2252 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002253 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002254 if (Child && Visit(Child))
2255 return true;
2256 }
2257 return false;
2258 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002259 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002260};
2261} // namespace
2262
Alexey Bataeved09d242014-05-28 05:53:51 +00002263OMPThreadPrivateDecl *
2264Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002265 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002266 for (Expr *RefExpr : VarList) {
2267 auto *DE = cast<DeclRefExpr>(RefExpr);
2268 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002269 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002270
Alexey Bataev376b4a42016-02-09 09:41:09 +00002271 // Mark variable as used.
2272 VD->setReferenced();
2273 VD->markUsed(Context);
2274
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002275 QualType QType = VD->getType();
2276 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2277 // It will be analyzed later.
2278 Vars.push_back(DE);
2279 continue;
2280 }
2281
Alexey Bataeva769e072013-03-22 06:34:35 +00002282 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2283 // A threadprivate variable must not have an incomplete type.
2284 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002285 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002286 continue;
2287 }
2288
2289 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2290 // A threadprivate variable must not have a reference type.
2291 if (VD->getType()->isReferenceType()) {
2292 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002293 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2294 bool IsDecl =
2295 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2296 Diag(VD->getLocation(),
2297 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2298 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002299 continue;
2300 }
2301
Samuel Antaof8b50122015-07-13 22:54:53 +00002302 // Check if this is a TLS variable. If TLS is not being supported, produce
2303 // the corresponding diagnostic.
2304 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2305 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2306 getLangOpts().OpenMPUseTLS &&
2307 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002308 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2309 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002310 Diag(ILoc, diag::err_omp_var_thread_local)
2311 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002312 bool IsDecl =
2313 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2314 Diag(VD->getLocation(),
2315 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2316 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002317 continue;
2318 }
2319
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002320 // Check if initial value of threadprivate variable reference variable with
2321 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002322 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002323 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002324 if (Checker.Visit(Init))
2325 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002326 }
2327
Alexey Bataeved09d242014-05-28 05:53:51 +00002328 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002329 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002330 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2331 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002332 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002333 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002334 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002335 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002336 if (!Vars.empty()) {
2337 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2338 Vars);
2339 D->setAccess(AS_public);
2340 }
2341 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002342}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002343
Alexey Bataev27ef9512019-03-20 20:14:22 +00002344static OMPAllocateDeclAttr::AllocatorTypeTy
2345getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2346 if (!Allocator)
2347 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2348 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2349 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002350 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002351 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002352 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002353 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002354 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2355 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2356 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002357 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002358 llvm::FoldingSetNodeID AEId, DAEId;
2359 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2360 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2361 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002362 AllocatorKindRes = AllocatorKind;
2363 break;
2364 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002365 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002366 return AllocatorKindRes;
2367}
2368
Alexey Bataeve106f252019-04-01 14:25:31 +00002369static bool checkPreviousOMPAllocateAttribute(
2370 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2371 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2372 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2373 return false;
2374 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2375 Expr *PrevAllocator = A->getAllocator();
2376 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2377 getAllocatorKind(S, Stack, PrevAllocator);
2378 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2379 if (AllocatorsMatch &&
2380 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2381 Allocator && PrevAllocator) {
2382 const Expr *AE = Allocator->IgnoreParenImpCasts();
2383 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2384 llvm::FoldingSetNodeID AEId, PAEId;
2385 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2386 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2387 AllocatorsMatch = AEId == PAEId;
2388 }
2389 if (!AllocatorsMatch) {
2390 SmallString<256> AllocatorBuffer;
2391 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2392 if (Allocator)
2393 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2394 SmallString<256> PrevAllocatorBuffer;
2395 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2396 if (PrevAllocator)
2397 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2398 S.getPrintingPolicy());
2399
2400 SourceLocation AllocatorLoc =
2401 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2402 SourceRange AllocatorRange =
2403 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2404 SourceLocation PrevAllocatorLoc =
2405 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2406 SourceRange PrevAllocatorRange =
2407 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2408 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2409 << (Allocator ? 1 : 0) << AllocatorStream.str()
2410 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2411 << AllocatorRange;
2412 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2413 << PrevAllocatorRange;
2414 return true;
2415 }
2416 return false;
2417}
2418
2419static void
2420applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2421 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2422 Expr *Allocator, SourceRange SR) {
2423 if (VD->hasAttr<OMPAllocateDeclAttr>())
2424 return;
2425 if (Allocator &&
2426 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2427 Allocator->isInstantiationDependent() ||
2428 Allocator->containsUnexpandedParameterPack()))
2429 return;
2430 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2431 Allocator, SR);
2432 VD->addAttr(A);
2433 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2434 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2435}
2436
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002437Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2438 SourceLocation Loc, ArrayRef<Expr *> VarList,
2439 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2440 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2441 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002442 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002443 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2444 // allocate directives that appear in a target region must specify an
2445 // allocator clause unless a requires directive with the dynamic_allocators
2446 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002447 if (LangOpts.OpenMPIsDevice &&
2448 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002449 targetDiag(Loc, diag::err_expected_allocator_clause);
2450 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002451 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002452 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002453 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2454 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002455 SmallVector<Expr *, 8> Vars;
2456 for (Expr *RefExpr : VarList) {
2457 auto *DE = cast<DeclRefExpr>(RefExpr);
2458 auto *VD = cast<VarDecl>(DE->getDecl());
2459
2460 // Check if this is a TLS variable or global register.
2461 if (VD->getTLSKind() != VarDecl::TLS_None ||
2462 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2463 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2464 !VD->isLocalVarDecl()))
2465 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002466
Alexey Bataev282555a2019-03-19 20:33:44 +00002467 // If the used several times in the allocate directive, the same allocator
2468 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002469 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2470 AllocatorKind, Allocator))
2471 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002472
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002473 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2474 // If a list item has a static storage type, the allocator expression in the
2475 // allocator clause must be a constant expression that evaluates to one of
2476 // the predefined memory allocator values.
2477 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002478 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002479 Diag(Allocator->getExprLoc(),
2480 diag::err_omp_expected_predefined_allocator)
2481 << Allocator->getSourceRange();
2482 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2483 VarDecl::DeclarationOnly;
2484 Diag(VD->getLocation(),
2485 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2486 << VD;
2487 continue;
2488 }
2489 }
2490
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002491 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002492 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2493 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002494 }
2495 if (Vars.empty())
2496 return nullptr;
2497 if (!Owner)
2498 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002499 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002500 D->setAccess(AS_public);
2501 Owner->addDecl(D);
2502 return DeclGroupPtrTy::make(DeclGroupRef(D));
2503}
2504
2505Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002506Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2507 ArrayRef<OMPClause *> ClauseList) {
2508 OMPRequiresDecl *D = nullptr;
2509 if (!CurContext->isFileContext()) {
2510 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2511 } else {
2512 D = CheckOMPRequiresDecl(Loc, ClauseList);
2513 if (D) {
2514 CurContext->addDecl(D);
2515 DSAStack->addRequiresDecl(D);
2516 }
2517 }
2518 return DeclGroupPtrTy::make(DeclGroupRef(D));
2519}
2520
2521OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2522 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002523 /// For target specific clauses, the requires directive cannot be
2524 /// specified after the handling of any of the target regions in the
2525 /// current compilation unit.
2526 ArrayRef<SourceLocation> TargetLocations =
2527 DSAStack->getEncounteredTargetLocs();
2528 if (!TargetLocations.empty()) {
2529 for (const OMPClause *CNew : ClauseList) {
2530 // Check if any of the requires clauses affect target regions.
2531 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2532 isa<OMPUnifiedAddressClause>(CNew) ||
2533 isa<OMPReverseOffloadClause>(CNew) ||
2534 isa<OMPDynamicAllocatorsClause>(CNew)) {
2535 Diag(Loc, diag::err_omp_target_before_requires)
2536 << getOpenMPClauseName(CNew->getClauseKind());
2537 for (SourceLocation TargetLoc : TargetLocations) {
2538 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2539 }
2540 }
2541 }
2542 }
2543
Kelvin Li1408f912018-09-26 04:28:39 +00002544 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2545 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2546 ClauseList);
2547 return nullptr;
2548}
2549
Alexey Bataeve3727102018-04-18 15:57:46 +00002550static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2551 const ValueDecl *D,
2552 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002553 bool IsLoopIterVar = false) {
2554 if (DVar.RefExpr) {
2555 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2556 << getOpenMPClauseName(DVar.CKind);
2557 return;
2558 }
2559 enum {
2560 PDSA_StaticMemberShared,
2561 PDSA_StaticLocalVarShared,
2562 PDSA_LoopIterVarPrivate,
2563 PDSA_LoopIterVarLinear,
2564 PDSA_LoopIterVarLastprivate,
2565 PDSA_ConstVarShared,
2566 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002567 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002568 PDSA_LocalVarPrivate,
2569 PDSA_Implicit
2570 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002571 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002572 auto ReportLoc = D->getLocation();
2573 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002574 if (IsLoopIterVar) {
2575 if (DVar.CKind == OMPC_private)
2576 Reason = PDSA_LoopIterVarPrivate;
2577 else if (DVar.CKind == OMPC_lastprivate)
2578 Reason = PDSA_LoopIterVarLastprivate;
2579 else
2580 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002581 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2582 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002583 Reason = PDSA_TaskVarFirstprivate;
2584 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002585 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002586 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002587 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002588 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002589 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002590 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002591 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002592 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002593 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002594 ReportHint = true;
2595 Reason = PDSA_LocalVarPrivate;
2596 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002597 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002598 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002599 << Reason << ReportHint
2600 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2601 } else if (DVar.ImplicitDSALoc.isValid()) {
2602 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2603 << getOpenMPClauseName(DVar.CKind);
2604 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002605}
2606
Alexey Bataev758e55e2013-09-06 18:03:48 +00002607namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002608class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002609 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002610 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002611 bool ErrorFound = false;
2612 CapturedStmt *CS = nullptr;
2613 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2614 llvm::SmallVector<Expr *, 4> ImplicitMap;
2615 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2616 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002617
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002618 void VisitSubCaptures(OMPExecutableDirective *S) {
2619 // Check implicitly captured variables.
2620 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2621 return;
2622 for (const CapturedStmt::Capture &Cap :
2623 S->getInnermostCapturedStmt()->captures()) {
2624 if (!Cap.capturesVariable())
2625 continue;
2626 VarDecl *VD = Cap.getCapturedVar();
2627 // Do not try to map the variable if it or its sub-component was mapped
2628 // already.
2629 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2630 Stack->checkMappableExprComponentListsForDecl(
2631 VD, /*CurrentRegionOnly=*/true,
2632 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2633 OpenMPClauseKind) { return true; }))
2634 continue;
2635 DeclRefExpr *DRE = buildDeclRefExpr(
2636 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2637 Cap.getLocation(), /*RefersToCapture=*/true);
2638 Visit(DRE);
2639 }
2640 }
2641
Alexey Bataev758e55e2013-09-06 18:03:48 +00002642public:
2643 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002644 if (E->isTypeDependent() || E->isValueDependent() ||
2645 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2646 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002647 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002648 // Check the datasharing rules for the expressions in the clauses.
2649 if (!CS) {
2650 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2651 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2652 Visit(CED->getInit());
2653 return;
2654 }
2655 }
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002656 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002657 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002658 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002659 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002660
Alexey Bataeve3727102018-04-18 15:57:46 +00002661 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002662 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002663 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002664 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002665
Alexey Bataevafe50572017-10-06 17:00:28 +00002666 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002667 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002668 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002669 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002670 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002671 return;
2672
Alexey Bataeve3727102018-04-18 15:57:46 +00002673 SourceLocation ELoc = E->getExprLoc();
2674 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002675 // The default(none) clause requires that each variable that is referenced
2676 // in the construct, and does not have a predetermined data-sharing
2677 // attribute, must have its data-sharing attribute explicitly determined
2678 // by being listed in a data-sharing attribute clause.
2679 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002680 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002681 VarsWithInheritedDSA.count(VD) == 0) {
2682 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002683 return;
2684 }
2685
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002686 if (isOpenMPTargetExecutionDirective(DKind) &&
2687 !Stack->isLoopControlVariable(VD).first) {
2688 if (!Stack->checkMappableExprComponentListsForDecl(
2689 VD, /*CurrentRegionOnly=*/true,
2690 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2691 StackComponents,
2692 OpenMPClauseKind) {
2693 // Variable is used if it has been marked as an array, array
2694 // section or the variable iself.
2695 return StackComponents.size() == 1 ||
2696 std::all_of(
2697 std::next(StackComponents.rbegin()),
2698 StackComponents.rend(),
2699 [](const OMPClauseMappableExprCommon::
2700 MappableComponent &MC) {
2701 return MC.getAssociatedDeclaration() ==
2702 nullptr &&
2703 (isa<OMPArraySectionExpr>(
2704 MC.getAssociatedExpression()) ||
2705 isa<ArraySubscriptExpr>(
2706 MC.getAssociatedExpression()));
2707 });
2708 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002709 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002710 // By default lambdas are captured as firstprivates.
2711 if (const auto *RD =
2712 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002713 IsFirstprivate = RD->isLambda();
2714 IsFirstprivate =
2715 IsFirstprivate ||
2716 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002717 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002718 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002719 ImplicitFirstprivate.emplace_back(E);
2720 else
2721 ImplicitMap.emplace_back(E);
2722 return;
2723 }
2724 }
2725
Alexey Bataev758e55e2013-09-06 18:03:48 +00002726 // OpenMP [2.9.3.6, Restrictions, p.2]
2727 // A list item that appears in a reduction clause of the innermost
2728 // enclosing worksharing or parallel construct may not be accessed in an
2729 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002730 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002731 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2732 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002733 return isOpenMPParallelDirective(K) ||
2734 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2735 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002736 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002737 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002738 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002739 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002740 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002741 return;
2742 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002743
2744 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002745 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002746 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002747 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002748 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002749 return;
2750 }
2751
2752 // Store implicitly used globals with declare target link for parent
2753 // target.
2754 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2755 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2756 Stack->addToParentTargetRegionLinkGlobals(E);
2757 return;
2758 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002759 }
2760 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002761 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002762 if (E->isTypeDependent() || E->isValueDependent() ||
2763 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2764 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002765 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002766 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002767 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002768 if (!FD)
2769 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002770 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002771 // Check if the variable has explicit DSA set and stop analysis if it
2772 // so.
2773 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2774 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002775
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002776 if (isOpenMPTargetExecutionDirective(DKind) &&
2777 !Stack->isLoopControlVariable(FD).first &&
2778 !Stack->checkMappableExprComponentListsForDecl(
2779 FD, /*CurrentRegionOnly=*/true,
2780 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2781 StackComponents,
2782 OpenMPClauseKind) {
2783 return isa<CXXThisExpr>(
2784 cast<MemberExpr>(
2785 StackComponents.back().getAssociatedExpression())
2786 ->getBase()
2787 ->IgnoreParens());
2788 })) {
2789 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2790 // A bit-field cannot appear in a map clause.
2791 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002792 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002793 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002794
2795 // Check to see if the member expression is referencing a class that
2796 // has already been explicitly mapped
2797 if (Stack->isClassPreviouslyMapped(TE->getType()))
2798 return;
2799
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002800 ImplicitMap.emplace_back(E);
2801 return;
2802 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002803
Alexey Bataeve3727102018-04-18 15:57:46 +00002804 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002805 // OpenMP [2.9.3.6, Restrictions, p.2]
2806 // A list item that appears in a reduction clause of the innermost
2807 // enclosing worksharing or parallel construct may not be accessed in
2808 // an explicit task.
2809 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002810 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2811 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002812 return isOpenMPParallelDirective(K) ||
2813 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2814 },
2815 /*FromParent=*/true);
2816 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2817 ErrorFound = true;
2818 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002819 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002820 return;
2821 }
2822
2823 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002824 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002825 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002826 !Stack->isLoopControlVariable(FD).first) {
2827 // Check if there is a captured expression for the current field in the
2828 // region. Do not mark it as firstprivate unless there is no captured
2829 // expression.
2830 // TODO: try to make it firstprivate.
2831 if (DVar.CKind != OMPC_unknown)
2832 ImplicitFirstprivate.push_back(E);
2833 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002834 return;
2835 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002836 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002837 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002838 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002839 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002840 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002841 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002842 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2843 if (!Stack->checkMappableExprComponentListsForDecl(
2844 VD, /*CurrentRegionOnly=*/true,
2845 [&CurComponents](
2846 OMPClauseMappableExprCommon::MappableExprComponentListRef
2847 StackComponents,
2848 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002849 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002850 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002851 for (const auto &SC : llvm::reverse(StackComponents)) {
2852 // Do both expressions have the same kind?
2853 if (CCI->getAssociatedExpression()->getStmtClass() !=
2854 SC.getAssociatedExpression()->getStmtClass())
2855 if (!(isa<OMPArraySectionExpr>(
2856 SC.getAssociatedExpression()) &&
2857 isa<ArraySubscriptExpr>(
2858 CCI->getAssociatedExpression())))
2859 return false;
2860
Alexey Bataeve3727102018-04-18 15:57:46 +00002861 const Decl *CCD = CCI->getAssociatedDeclaration();
2862 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002863 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2864 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2865 if (SCD != CCD)
2866 return false;
2867 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002868 if (CCI == CCE)
2869 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002870 }
2871 return true;
2872 })) {
2873 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002874 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002875 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002876 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002877 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002878 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002879 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002880 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002881 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002882 // for task|target directives.
2883 // Skip analysis of arguments of implicitly defined map clause for target
2884 // directives.
2885 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2886 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002887 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002888 if (CC)
2889 Visit(CC);
2890 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002891 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002892 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002893 // Check implicitly captured variables.
2894 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002895 }
2896 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002897 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002898 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002899 // Check implicitly captured variables in the task-based directives to
2900 // check if they must be firstprivatized.
2901 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002902 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002903 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002904 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002905
Alexey Bataeve3727102018-04-18 15:57:46 +00002906 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002907 ArrayRef<Expr *> getImplicitFirstprivate() const {
2908 return ImplicitFirstprivate;
2909 }
2910 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002911 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002912 return VarsWithInheritedDSA;
2913 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002914
Alexey Bataev7ff55242014-06-19 09:13:45 +00002915 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002916 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2917 // Process declare target link variables for the target directives.
2918 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2919 for (DeclRefExpr *E : Stack->getLinkGlobals())
2920 Visit(E);
2921 }
2922 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002923};
Alexey Bataeved09d242014-05-28 05:53:51 +00002924} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002925
Alexey Bataevbae9a792014-06-27 10:37:06 +00002926void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002927 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002928 case OMPD_parallel:
2929 case OMPD_parallel_for:
2930 case OMPD_parallel_for_simd:
2931 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002932 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002933 case OMPD_teams_distribute:
2934 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002935 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002936 QualType KmpInt32PtrTy =
2937 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002938 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002939 std::make_pair(".global_tid.", KmpInt32PtrTy),
2940 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2941 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002942 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002943 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2944 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002945 break;
2946 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002947 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002948 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002949 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002950 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002951 case OMPD_target_teams_distribute:
2952 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002953 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2954 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2955 QualType KmpInt32PtrTy =
2956 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2957 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002958 FunctionProtoType::ExtProtoInfo EPI;
2959 EPI.Variadic = true;
2960 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2961 Sema::CapturedParamNameType Params[] = {
2962 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002963 std::make_pair(".part_id.", KmpInt32PtrTy),
2964 std::make_pair(".privates.", VoidPtrTy),
2965 std::make_pair(
2966 ".copy_fn.",
2967 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002968 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2969 std::make_pair(StringRef(), QualType()) // __context with shared vars
2970 };
2971 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2972 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002973 // Mark this captured region as inlined, because we don't use outlined
2974 // function directly.
2975 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2976 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002977 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002978 Sema::CapturedParamNameType ParamsTarget[] = {
2979 std::make_pair(StringRef(), QualType()) // __context with shared vars
2980 };
2981 // Start a captured region for 'target' with no implicit parameters.
2982 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2983 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002984 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002985 std::make_pair(".global_tid.", KmpInt32PtrTy),
2986 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2987 std::make_pair(StringRef(), QualType()) // __context with shared vars
2988 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002989 // Start a captured region for 'teams' or 'parallel'. Both regions have
2990 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002991 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002992 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002993 break;
2994 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002995 case OMPD_target:
2996 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002997 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2998 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2999 QualType KmpInt32PtrTy =
3000 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3001 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003002 FunctionProtoType::ExtProtoInfo EPI;
3003 EPI.Variadic = true;
3004 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3005 Sema::CapturedParamNameType Params[] = {
3006 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003007 std::make_pair(".part_id.", KmpInt32PtrTy),
3008 std::make_pair(".privates.", VoidPtrTy),
3009 std::make_pair(
3010 ".copy_fn.",
3011 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003012 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3013 std::make_pair(StringRef(), QualType()) // __context with shared vars
3014 };
3015 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3016 Params);
3017 // Mark this captured region as inlined, because we don't use outlined
3018 // function directly.
3019 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3020 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003021 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003022 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3023 std::make_pair(StringRef(), QualType()));
3024 break;
3025 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003026 case OMPD_simd:
3027 case OMPD_for:
3028 case OMPD_for_simd:
3029 case OMPD_sections:
3030 case OMPD_section:
3031 case OMPD_single:
3032 case OMPD_master:
3033 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003034 case OMPD_taskgroup:
3035 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003036 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003037 case OMPD_ordered:
3038 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003039 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003040 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003041 std::make_pair(StringRef(), QualType()) // __context with shared vars
3042 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003043 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3044 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003045 break;
3046 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003047 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003048 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3049 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3050 QualType KmpInt32PtrTy =
3051 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3052 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003053 FunctionProtoType::ExtProtoInfo EPI;
3054 EPI.Variadic = true;
3055 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003056 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003057 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003058 std::make_pair(".part_id.", KmpInt32PtrTy),
3059 std::make_pair(".privates.", VoidPtrTy),
3060 std::make_pair(
3061 ".copy_fn.",
3062 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003063 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003064 std::make_pair(StringRef(), QualType()) // __context with shared vars
3065 };
3066 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3067 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003068 // Mark this captured region as inlined, because we don't use outlined
3069 // function directly.
3070 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3071 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003072 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003073 break;
3074 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003075 case OMPD_taskloop:
3076 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003077 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003078 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3079 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003080 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003081 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3082 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003083 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003084 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3085 .withConst();
3086 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3087 QualType KmpInt32PtrTy =
3088 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3089 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003090 FunctionProtoType::ExtProtoInfo EPI;
3091 EPI.Variadic = true;
3092 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003093 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003094 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003095 std::make_pair(".part_id.", KmpInt32PtrTy),
3096 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003097 std::make_pair(
3098 ".copy_fn.",
3099 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3100 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3101 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003102 std::make_pair(".ub.", KmpUInt64Ty),
3103 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003104 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003105 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003106 std::make_pair(StringRef(), QualType()) // __context with shared vars
3107 };
3108 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3109 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003110 // Mark this captured region as inlined, because we don't use outlined
3111 // function directly.
3112 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3113 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003114 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003115 break;
3116 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003117 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003118 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003119 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003120 QualType KmpInt32PtrTy =
3121 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3122 Sema::CapturedParamNameType Params[] = {
3123 std::make_pair(".global_tid.", KmpInt32PtrTy),
3124 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003125 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3126 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003127 std::make_pair(StringRef(), QualType()) // __context with shared vars
3128 };
3129 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3130 Params);
3131 break;
3132 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003133 case OMPD_target_teams_distribute_parallel_for:
3134 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003135 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003136 QualType KmpInt32PtrTy =
3137 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003138 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003139
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003140 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003141 FunctionProtoType::ExtProtoInfo EPI;
3142 EPI.Variadic = true;
3143 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3144 Sema::CapturedParamNameType Params[] = {
3145 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003146 std::make_pair(".part_id.", KmpInt32PtrTy),
3147 std::make_pair(".privates.", VoidPtrTy),
3148 std::make_pair(
3149 ".copy_fn.",
3150 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003151 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3152 std::make_pair(StringRef(), QualType()) // __context with shared vars
3153 };
3154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3155 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003156 // Mark this captured region as inlined, because we don't use outlined
3157 // function directly.
3158 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3159 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003160 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003161 Sema::CapturedParamNameType ParamsTarget[] = {
3162 std::make_pair(StringRef(), QualType()) // __context with shared vars
3163 };
3164 // Start a captured region for 'target' with no implicit parameters.
3165 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3166 ParamsTarget);
3167
3168 Sema::CapturedParamNameType ParamsTeams[] = {
3169 std::make_pair(".global_tid.", KmpInt32PtrTy),
3170 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3171 std::make_pair(StringRef(), QualType()) // __context with shared vars
3172 };
3173 // Start a captured region for 'target' with no implicit parameters.
3174 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3175 ParamsTeams);
3176
3177 Sema::CapturedParamNameType ParamsParallel[] = {
3178 std::make_pair(".global_tid.", KmpInt32PtrTy),
3179 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003180 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3181 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003182 std::make_pair(StringRef(), QualType()) // __context with shared vars
3183 };
3184 // Start a captured region for 'teams' or 'parallel'. Both regions have
3185 // the same implicit parameters.
3186 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3187 ParamsParallel);
3188 break;
3189 }
3190
Alexey Bataev46506272017-12-05 17:41:34 +00003191 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003192 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003193 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003194 QualType KmpInt32PtrTy =
3195 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3196
3197 Sema::CapturedParamNameType ParamsTeams[] = {
3198 std::make_pair(".global_tid.", KmpInt32PtrTy),
3199 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3200 std::make_pair(StringRef(), QualType()) // __context with shared vars
3201 };
3202 // Start a captured region for 'target' with no implicit parameters.
3203 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3204 ParamsTeams);
3205
3206 Sema::CapturedParamNameType ParamsParallel[] = {
3207 std::make_pair(".global_tid.", KmpInt32PtrTy),
3208 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003209 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3210 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003211 std::make_pair(StringRef(), QualType()) // __context with shared vars
3212 };
3213 // Start a captured region for 'teams' or 'parallel'. Both regions have
3214 // the same implicit parameters.
3215 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3216 ParamsParallel);
3217 break;
3218 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003219 case OMPD_target_update:
3220 case OMPD_target_enter_data:
3221 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003222 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3223 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3224 QualType KmpInt32PtrTy =
3225 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3226 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003227 FunctionProtoType::ExtProtoInfo EPI;
3228 EPI.Variadic = true;
3229 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3230 Sema::CapturedParamNameType Params[] = {
3231 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003232 std::make_pair(".part_id.", KmpInt32PtrTy),
3233 std::make_pair(".privates.", VoidPtrTy),
3234 std::make_pair(
3235 ".copy_fn.",
3236 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003237 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3238 std::make_pair(StringRef(), QualType()) // __context with shared vars
3239 };
3240 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3241 Params);
3242 // Mark this captured region as inlined, because we don't use outlined
3243 // function directly.
3244 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3245 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003246 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003247 break;
3248 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003249 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003250 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003251 case OMPD_taskyield:
3252 case OMPD_barrier:
3253 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003254 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003255 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003256 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003257 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003258 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003259 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003260 case OMPD_declare_target:
3261 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003262 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003263 llvm_unreachable("OpenMP Directive is not allowed");
3264 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003265 llvm_unreachable("Unknown OpenMP directive");
3266 }
3267}
3268
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003269int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3270 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3271 getOpenMPCaptureRegions(CaptureRegions, DKind);
3272 return CaptureRegions.size();
3273}
3274
Alexey Bataev3392d762016-02-16 11:18:12 +00003275static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003276 Expr *CaptureExpr, bool WithInit,
3277 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003278 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003279 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003280 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003281 QualType Ty = Init->getType();
3282 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003283 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003284 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003285 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003286 Ty = C.getPointerType(Ty);
3287 ExprResult Res =
3288 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3289 if (!Res.isUsable())
3290 return nullptr;
3291 Init = Res.get();
3292 }
Alexey Bataev61205072016-03-02 04:57:40 +00003293 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003294 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003295 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003296 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003297 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003298 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003299 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003300 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003301 return CED;
3302}
3303
Alexey Bataev61205072016-03-02 04:57:40 +00003304static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3305 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003306 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003307 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003308 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003309 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003310 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3311 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003312 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003313 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003314}
3315
Alexey Bataev5a3af132016-03-29 08:58:54 +00003316static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003317 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003318 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003319 OMPCapturedExprDecl *CD = buildCaptureDecl(
3320 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3321 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003322 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3323 CaptureExpr->getExprLoc());
3324 }
3325 ExprResult Res = Ref;
3326 if (!S.getLangOpts().CPlusPlus &&
3327 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003328 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003329 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003330 if (!Res.isUsable())
3331 return ExprError();
3332 }
3333 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003334}
3335
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003336namespace {
3337// OpenMP directives parsed in this section are represented as a
3338// CapturedStatement with an associated statement. If a syntax error
3339// is detected during the parsing of the associated statement, the
3340// compiler must abort processing and close the CapturedStatement.
3341//
3342// Combined directives such as 'target parallel' have more than one
3343// nested CapturedStatements. This RAII ensures that we unwind out
3344// of all the nested CapturedStatements when an error is found.
3345class CaptureRegionUnwinderRAII {
3346private:
3347 Sema &S;
3348 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003349 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003350
3351public:
3352 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3353 OpenMPDirectiveKind DKind)
3354 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3355 ~CaptureRegionUnwinderRAII() {
3356 if (ErrorFound) {
3357 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3358 while (--ThisCaptureLevel >= 0)
3359 S.ActOnCapturedRegionError();
3360 }
3361 }
3362};
3363} // namespace
3364
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003365StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3366 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003367 bool ErrorFound = false;
3368 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3369 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003370 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003371 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003372 return StmtError();
3373 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003374
Alexey Bataev2ba67042017-11-28 21:11:44 +00003375 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3376 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003377 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003378 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003379 SmallVector<const OMPLinearClause *, 4> LCs;
3380 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003381 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003382 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003383 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3384 Clause->getClauseKind() == OMPC_in_reduction) {
3385 // Capture taskgroup task_reduction descriptors inside the tasking regions
3386 // with the corresponding in_reduction items.
3387 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003388 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003389 if (E)
3390 MarkDeclarationsReferencedInExpr(E);
3391 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003392 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003393 Clause->getClauseKind() == OMPC_copyprivate ||
3394 (getLangOpts().OpenMPUseTLS &&
3395 getASTContext().getTargetInfo().isTLSSupported() &&
3396 Clause->getClauseKind() == OMPC_copyin)) {
3397 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003398 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003399 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003400 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003401 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003402 }
3403 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003404 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003405 } else if (CaptureRegions.size() > 1 ||
3406 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003407 if (auto *C = OMPClauseWithPreInit::get(Clause))
3408 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003409 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003410 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003411 MarkDeclarationsReferencedInExpr(E);
3412 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003413 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003414 if (Clause->getClauseKind() == OMPC_schedule)
3415 SC = cast<OMPScheduleClause>(Clause);
3416 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003417 OC = cast<OMPOrderedClause>(Clause);
3418 else if (Clause->getClauseKind() == OMPC_linear)
3419 LCs.push_back(cast<OMPLinearClause>(Clause));
3420 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003421 // OpenMP, 2.7.1 Loop Construct, Restrictions
3422 // The nonmonotonic modifier cannot be specified if an ordered clause is
3423 // specified.
3424 if (SC &&
3425 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3426 SC->getSecondScheduleModifier() ==
3427 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3428 OC) {
3429 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3430 ? SC->getFirstScheduleModifierLoc()
3431 : SC->getSecondScheduleModifierLoc(),
3432 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003433 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003434 ErrorFound = true;
3435 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003436 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003437 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003438 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003439 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003440 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003441 ErrorFound = true;
3442 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003443 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3444 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3445 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003446 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003447 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3448 ErrorFound = true;
3449 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003450 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003451 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003452 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003453 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003454 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003455 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003456 // Mark all variables in private list clauses as used in inner region.
3457 // Required for proper codegen of combined directives.
3458 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003459 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003460 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003461 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3462 // Find the particular capture region for the clause if the
3463 // directive is a combined one with multiple capture regions.
3464 // If the directive is not a combined one, the capture region
3465 // associated with the clause is OMPD_unknown and is generated
3466 // only once.
3467 if (CaptureRegion == ThisCaptureRegion ||
3468 CaptureRegion == OMPD_unknown) {
3469 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003470 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003471 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3472 }
3473 }
3474 }
3475 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003476 if (++CompletedRegions == CaptureRegions.size())
3477 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003478 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003479 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003480 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003481}
3482
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003483static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3484 OpenMPDirectiveKind CancelRegion,
3485 SourceLocation StartLoc) {
3486 // CancelRegion is only needed for cancel and cancellation_point.
3487 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3488 return false;
3489
3490 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3491 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3492 return false;
3493
3494 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3495 << getOpenMPDirectiveName(CancelRegion);
3496 return true;
3497}
3498
Alexey Bataeve3727102018-04-18 15:57:46 +00003499static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003500 OpenMPDirectiveKind CurrentRegion,
3501 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003502 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003503 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003504 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003505 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3506 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003507 bool NestingProhibited = false;
3508 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003509 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003510 enum {
3511 NoRecommend,
3512 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003513 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003514 ShouldBeInTargetRegion,
3515 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003516 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003517 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003518 // OpenMP [2.16, Nesting of Regions]
3519 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003520 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003521 // An ordered construct with the simd clause is the only OpenMP
3522 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003523 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003524 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3525 // message.
3526 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3527 ? diag::err_omp_prohibited_region_simd
3528 : diag::warn_omp_nesting_simd);
3529 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003530 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003531 if (ParentRegion == OMPD_atomic) {
3532 // OpenMP [2.16, Nesting of Regions]
3533 // OpenMP constructs may not be nested inside an atomic region.
3534 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3535 return true;
3536 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003537 if (CurrentRegion == OMPD_section) {
3538 // OpenMP [2.7.2, sections Construct, Restrictions]
3539 // Orphaned section directives are prohibited. That is, the section
3540 // directives must appear within the sections construct and must not be
3541 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003542 if (ParentRegion != OMPD_sections &&
3543 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003544 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3545 << (ParentRegion != OMPD_unknown)
3546 << getOpenMPDirectiveName(ParentRegion);
3547 return true;
3548 }
3549 return false;
3550 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003551 // Allow some constructs (except teams and cancellation constructs) to be
3552 // orphaned (they could be used in functions, called from OpenMP regions
3553 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003554 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003555 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3556 CurrentRegion != OMPD_cancellation_point &&
3557 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003558 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003559 if (CurrentRegion == OMPD_cancellation_point ||
3560 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003561 // OpenMP [2.16, Nesting of Regions]
3562 // A cancellation point construct for which construct-type-clause is
3563 // taskgroup must be nested inside a task construct. A cancellation
3564 // point construct for which construct-type-clause is not taskgroup must
3565 // be closely nested inside an OpenMP construct that matches the type
3566 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003567 // A cancel construct for which construct-type-clause is taskgroup must be
3568 // nested inside a task construct. A cancel construct for which
3569 // construct-type-clause is not taskgroup must be closely nested inside an
3570 // OpenMP construct that matches the type specified in
3571 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003572 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003573 !((CancelRegion == OMPD_parallel &&
3574 (ParentRegion == OMPD_parallel ||
3575 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003576 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003577 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003578 ParentRegion == OMPD_target_parallel_for ||
3579 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003580 ParentRegion == OMPD_teams_distribute_parallel_for ||
3581 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003582 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3583 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003584 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3585 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003586 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003587 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003588 // OpenMP [2.16, Nesting of Regions]
3589 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003590 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003591 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003592 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003593 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3594 // OpenMP [2.16, Nesting of Regions]
3595 // A critical region may not be nested (closely or otherwise) inside a
3596 // critical region with the same name. Note that this restriction is not
3597 // sufficient to prevent deadlock.
3598 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003599 bool DeadLock = Stack->hasDirective(
3600 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3601 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003602 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003603 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3604 PreviousCriticalLoc = Loc;
3605 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003606 }
3607 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003608 },
3609 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003610 if (DeadLock) {
3611 SemaRef.Diag(StartLoc,
3612 diag::err_omp_prohibited_region_critical_same_name)
3613 << CurrentName.getName();
3614 if (PreviousCriticalLoc.isValid())
3615 SemaRef.Diag(PreviousCriticalLoc,
3616 diag::note_omp_previous_critical_region);
3617 return true;
3618 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003619 } else if (CurrentRegion == OMPD_barrier) {
3620 // OpenMP [2.16, Nesting of Regions]
3621 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003622 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003623 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3624 isOpenMPTaskingDirective(ParentRegion) ||
3625 ParentRegion == OMPD_master ||
3626 ParentRegion == OMPD_critical ||
3627 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003628 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003629 !isOpenMPParallelDirective(CurrentRegion) &&
3630 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003631 // OpenMP [2.16, Nesting of Regions]
3632 // A worksharing region may not be closely nested inside a worksharing,
3633 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003634 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3635 isOpenMPTaskingDirective(ParentRegion) ||
3636 ParentRegion == OMPD_master ||
3637 ParentRegion == OMPD_critical ||
3638 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003639 Recommend = ShouldBeInParallelRegion;
3640 } else if (CurrentRegion == OMPD_ordered) {
3641 // OpenMP [2.16, Nesting of Regions]
3642 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003643 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003644 // An ordered region must be closely nested inside a loop region (or
3645 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003646 // OpenMP [2.8.1,simd Construct, Restrictions]
3647 // An ordered construct with the simd clause is the only OpenMP construct
3648 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003649 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003650 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003651 !(isOpenMPSimdDirective(ParentRegion) ||
3652 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003653 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003654 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003655 // OpenMP [2.16, Nesting of Regions]
3656 // If specified, a teams construct must be contained within a target
3657 // construct.
3658 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003659 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003660 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003661 }
Kelvin Libf594a52016-12-17 05:48:59 +00003662 if (!NestingProhibited &&
3663 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3664 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3665 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003666 // OpenMP [2.16, Nesting of Regions]
3667 // distribute, parallel, parallel sections, parallel workshare, and the
3668 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3669 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003670 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3671 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003672 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003673 }
David Majnemer9d168222016-08-05 17:44:54 +00003674 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003675 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003676 // OpenMP 4.5 [2.17 Nesting of Regions]
3677 // The region associated with the distribute construct must be strictly
3678 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003679 NestingProhibited =
3680 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003681 Recommend = ShouldBeInTeamsRegion;
3682 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003683 if (!NestingProhibited &&
3684 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3685 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3686 // OpenMP 4.5 [2.17 Nesting of Regions]
3687 // If a target, target update, target data, target enter data, or
3688 // target exit data construct is encountered during execution of a
3689 // target region, the behavior is unspecified.
3690 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003691 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003692 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003693 if (isOpenMPTargetExecutionDirective(K)) {
3694 OffendingRegion = K;
3695 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003696 }
3697 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003698 },
3699 false /* don't skip top directive */);
3700 CloseNesting = false;
3701 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003702 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003703 if (OrphanSeen) {
3704 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3705 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3706 } else {
3707 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3708 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3709 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3710 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003711 return true;
3712 }
3713 }
3714 return false;
3715}
3716
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003717static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3718 ArrayRef<OMPClause *> Clauses,
3719 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3720 bool ErrorFound = false;
3721 unsigned NamedModifiersNumber = 0;
3722 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3723 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003724 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003725 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003726 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3727 // At most one if clause without a directive-name-modifier can appear on
3728 // the directive.
3729 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3730 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003731 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003732 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3733 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3734 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003735 } else if (CurNM != OMPD_unknown) {
3736 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003737 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003738 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003739 FoundNameModifiers[CurNM] = IC;
3740 if (CurNM == OMPD_unknown)
3741 continue;
3742 // Check if the specified name modifier is allowed for the current
3743 // directive.
3744 // At most one if clause with the particular directive-name-modifier can
3745 // appear on the directive.
3746 bool MatchFound = false;
3747 for (auto NM : AllowedNameModifiers) {
3748 if (CurNM == NM) {
3749 MatchFound = true;
3750 break;
3751 }
3752 }
3753 if (!MatchFound) {
3754 S.Diag(IC->getNameModifierLoc(),
3755 diag::err_omp_wrong_if_directive_name_modifier)
3756 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3757 ErrorFound = true;
3758 }
3759 }
3760 }
3761 // If any if clause on the directive includes a directive-name-modifier then
3762 // all if clauses on the directive must include a directive-name-modifier.
3763 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3764 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003765 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003766 diag::err_omp_no_more_if_clause);
3767 } else {
3768 std::string Values;
3769 std::string Sep(", ");
3770 unsigned AllowedCnt = 0;
3771 unsigned TotalAllowedNum =
3772 AllowedNameModifiers.size() - NamedModifiersNumber;
3773 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3774 ++Cnt) {
3775 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3776 if (!FoundNameModifiers[NM]) {
3777 Values += "'";
3778 Values += getOpenMPDirectiveName(NM);
3779 Values += "'";
3780 if (AllowedCnt + 2 == TotalAllowedNum)
3781 Values += " or ";
3782 else if (AllowedCnt + 1 != TotalAllowedNum)
3783 Values += Sep;
3784 ++AllowedCnt;
3785 }
3786 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003787 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003788 diag::err_omp_unnamed_if_clause)
3789 << (TotalAllowedNum > 1) << Values;
3790 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003791 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003792 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3793 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003794 ErrorFound = true;
3795 }
3796 return ErrorFound;
3797}
3798
Alexey Bataeve106f252019-04-01 14:25:31 +00003799static std::pair<ValueDecl *, bool>
3800getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
3801 SourceRange &ERange, bool AllowArraySection = false) {
3802 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3803 RefExpr->containsUnexpandedParameterPack())
3804 return std::make_pair(nullptr, true);
3805
3806 // OpenMP [3.1, C/C++]
3807 // A list item is a variable name.
3808 // OpenMP [2.9.3.3, Restrictions, p.1]
3809 // A variable that is part of another variable (as an array or
3810 // structure element) cannot appear in a private clause.
3811 RefExpr = RefExpr->IgnoreParens();
3812 enum {
3813 NoArrayExpr = -1,
3814 ArraySubscript = 0,
3815 OMPArraySection = 1
3816 } IsArrayExpr = NoArrayExpr;
3817 if (AllowArraySection) {
3818 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
3819 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
3820 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3821 Base = TempASE->getBase()->IgnoreParenImpCasts();
3822 RefExpr = Base;
3823 IsArrayExpr = ArraySubscript;
3824 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
3825 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
3826 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
3827 Base = TempOASE->getBase()->IgnoreParenImpCasts();
3828 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3829 Base = TempASE->getBase()->IgnoreParenImpCasts();
3830 RefExpr = Base;
3831 IsArrayExpr = OMPArraySection;
3832 }
3833 }
3834 ELoc = RefExpr->getExprLoc();
3835 ERange = RefExpr->getSourceRange();
3836 RefExpr = RefExpr->IgnoreParenImpCasts();
3837 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3838 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
3839 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
3840 (S.getCurrentThisType().isNull() || !ME ||
3841 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
3842 !isa<FieldDecl>(ME->getMemberDecl()))) {
3843 if (IsArrayExpr != NoArrayExpr) {
3844 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
3845 << ERange;
3846 } else {
3847 S.Diag(ELoc,
3848 AllowArraySection
3849 ? diag::err_omp_expected_var_name_member_expr_or_array_item
3850 : diag::err_omp_expected_var_name_member_expr)
3851 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
3852 }
3853 return std::make_pair(nullptr, false);
3854 }
3855 return std::make_pair(
3856 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
3857}
3858
3859static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00003860 ArrayRef<OMPClause *> Clauses) {
3861 assert(!S.CurContext->isDependentContext() &&
3862 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00003863 auto AllocateRange =
3864 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00003865 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
3866 DeclToCopy;
3867 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
3868 return isOpenMPPrivate(C->getClauseKind());
3869 });
3870 for (OMPClause *Cl : PrivateRange) {
3871 MutableArrayRef<Expr *>::iterator I, It, Et;
3872 if (Cl->getClauseKind() == OMPC_private) {
3873 auto *PC = cast<OMPPrivateClause>(Cl);
3874 I = PC->private_copies().begin();
3875 It = PC->varlist_begin();
3876 Et = PC->varlist_end();
3877 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
3878 auto *PC = cast<OMPFirstprivateClause>(Cl);
3879 I = PC->private_copies().begin();
3880 It = PC->varlist_begin();
3881 Et = PC->varlist_end();
3882 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
3883 auto *PC = cast<OMPLastprivateClause>(Cl);
3884 I = PC->private_copies().begin();
3885 It = PC->varlist_begin();
3886 Et = PC->varlist_end();
3887 } else if (Cl->getClauseKind() == OMPC_linear) {
3888 auto *PC = cast<OMPLinearClause>(Cl);
3889 I = PC->privates().begin();
3890 It = PC->varlist_begin();
3891 Et = PC->varlist_end();
3892 } else if (Cl->getClauseKind() == OMPC_reduction) {
3893 auto *PC = cast<OMPReductionClause>(Cl);
3894 I = PC->privates().begin();
3895 It = PC->varlist_begin();
3896 Et = PC->varlist_end();
3897 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
3898 auto *PC = cast<OMPTaskReductionClause>(Cl);
3899 I = PC->privates().begin();
3900 It = PC->varlist_begin();
3901 Et = PC->varlist_end();
3902 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
3903 auto *PC = cast<OMPInReductionClause>(Cl);
3904 I = PC->privates().begin();
3905 It = PC->varlist_begin();
3906 Et = PC->varlist_end();
3907 } else {
3908 llvm_unreachable("Expected private clause.");
3909 }
3910 for (Expr *E : llvm::make_range(It, Et)) {
3911 if (!*I) {
3912 ++I;
3913 continue;
3914 }
3915 SourceLocation ELoc;
3916 SourceRange ERange;
3917 Expr *SimpleRefExpr = E;
3918 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3919 /*AllowArraySection=*/true);
3920 DeclToCopy.try_emplace(Res.first,
3921 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
3922 ++I;
3923 }
3924 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003925 for (OMPClause *C : AllocateRange) {
3926 auto *AC = cast<OMPAllocateClause>(C);
3927 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3928 getAllocatorKind(S, Stack, AC->getAllocator());
3929 // OpenMP, 2.11.4 allocate Clause, Restrictions.
3930 // For task, taskloop or target directives, allocation requests to memory
3931 // allocators with the trait access set to thread result in unspecified
3932 // behavior.
3933 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
3934 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
3935 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
3936 S.Diag(AC->getAllocator()->getExprLoc(),
3937 diag::warn_omp_allocate_thread_on_task_target_directive)
3938 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00003939 }
3940 for (Expr *E : AC->varlists()) {
3941 SourceLocation ELoc;
3942 SourceRange ERange;
3943 Expr *SimpleRefExpr = E;
3944 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
3945 ValueDecl *VD = Res.first;
3946 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
3947 if (!isOpenMPPrivate(Data.CKind)) {
3948 S.Diag(E->getExprLoc(),
3949 diag::err_omp_expected_private_copy_for_allocate);
3950 continue;
3951 }
3952 VarDecl *PrivateVD = DeclToCopy[VD];
3953 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
3954 AllocatorKind, AC->getAllocator()))
3955 continue;
3956 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
3957 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00003958 }
3959 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003960}
3961
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003962StmtResult Sema::ActOnOpenMPExecutableDirective(
3963 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3964 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3965 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003966 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003967 // First check CancelRegion which is then used in checkNestingOfRegions.
3968 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3969 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003970 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003971 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003972
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003973 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003974 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003975 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003976 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003977 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3979
3980 // Check default data sharing attributes for referenced variables.
3981 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003982 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3983 Stmt *S = AStmt;
3984 while (--ThisCaptureLevel >= 0)
3985 S = cast<CapturedStmt>(S)->getCapturedStmt();
3986 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003987 if (DSAChecker.isErrorFound())
3988 return StmtError();
3989 // Generate list of implicitly defined firstprivate variables.
3990 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003991
Alexey Bataev88202be2017-07-27 13:20:36 +00003992 SmallVector<Expr *, 4> ImplicitFirstprivates(
3993 DSAChecker.getImplicitFirstprivate().begin(),
3994 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003995 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3996 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003997 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003998 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003999 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004000 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004001 if (E)
4002 ImplicitFirstprivates.emplace_back(E);
4003 }
4004 }
4005 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004006 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004007 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4008 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004009 ClausesWithImplicit.push_back(Implicit);
4010 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004011 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004012 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004013 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004014 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004015 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004016 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004017 CXXScopeSpec MapperIdScopeSpec;
4018 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004019 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004020 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4021 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4022 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004023 ClausesWithImplicit.emplace_back(Implicit);
4024 ErrorFound |=
4025 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004026 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004027 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004028 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004029 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004030 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004031
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004032 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004033 switch (Kind) {
4034 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004035 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4036 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004037 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004038 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004039 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004040 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4041 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004042 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004043 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004044 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4045 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004046 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004047 case OMPD_for_simd:
4048 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4049 EndLoc, VarsWithInheritedDSA);
4050 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004051 case OMPD_sections:
4052 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4053 EndLoc);
4054 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004055 case OMPD_section:
4056 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004057 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004058 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4059 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004060 case OMPD_single:
4061 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4062 EndLoc);
4063 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004064 case OMPD_master:
4065 assert(ClausesWithImplicit.empty() &&
4066 "No clauses are allowed for 'omp master' directive");
4067 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4068 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004069 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004070 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4071 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004072 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004073 case OMPD_parallel_for:
4074 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4075 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004076 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004077 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004078 case OMPD_parallel_for_simd:
4079 Res = ActOnOpenMPParallelForSimdDirective(
4080 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004081 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004082 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004083 case OMPD_parallel_sections:
4084 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4085 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004086 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004087 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004088 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004089 Res =
4090 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004091 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004092 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004093 case OMPD_taskyield:
4094 assert(ClausesWithImplicit.empty() &&
4095 "No clauses are allowed for 'omp taskyield' directive");
4096 assert(AStmt == nullptr &&
4097 "No associated statement allowed for 'omp taskyield' directive");
4098 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4099 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004100 case OMPD_barrier:
4101 assert(ClausesWithImplicit.empty() &&
4102 "No clauses are allowed for 'omp barrier' directive");
4103 assert(AStmt == nullptr &&
4104 "No associated statement allowed for 'omp barrier' directive");
4105 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4106 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004107 case OMPD_taskwait:
4108 assert(ClausesWithImplicit.empty() &&
4109 "No clauses are allowed for 'omp taskwait' directive");
4110 assert(AStmt == nullptr &&
4111 "No associated statement allowed for 'omp taskwait' directive");
4112 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4113 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004114 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004115 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4116 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004117 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004118 case OMPD_flush:
4119 assert(AStmt == nullptr &&
4120 "No associated statement allowed for 'omp flush' directive");
4121 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4122 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004123 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004124 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4125 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004126 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004127 case OMPD_atomic:
4128 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4129 EndLoc);
4130 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004131 case OMPD_teams:
4132 Res =
4133 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4134 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004135 case OMPD_target:
4136 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4137 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004138 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004139 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004140 case OMPD_target_parallel:
4141 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4142 StartLoc, EndLoc);
4143 AllowedNameModifiers.push_back(OMPD_target);
4144 AllowedNameModifiers.push_back(OMPD_parallel);
4145 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004146 case OMPD_target_parallel_for:
4147 Res = ActOnOpenMPTargetParallelForDirective(
4148 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4149 AllowedNameModifiers.push_back(OMPD_target);
4150 AllowedNameModifiers.push_back(OMPD_parallel);
4151 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004152 case OMPD_cancellation_point:
4153 assert(ClausesWithImplicit.empty() &&
4154 "No clauses are allowed for 'omp cancellation point' directive");
4155 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4156 "cancellation point' directive");
4157 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4158 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004159 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004160 assert(AStmt == nullptr &&
4161 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004162 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4163 CancelRegion);
4164 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004165 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004166 case OMPD_target_data:
4167 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4168 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004169 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004170 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004171 case OMPD_target_enter_data:
4172 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004173 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004174 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4175 break;
Samuel Antao72590762016-01-19 20:04:50 +00004176 case OMPD_target_exit_data:
4177 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004178 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004179 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4180 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004181 case OMPD_taskloop:
4182 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4183 EndLoc, VarsWithInheritedDSA);
4184 AllowedNameModifiers.push_back(OMPD_taskloop);
4185 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004186 case OMPD_taskloop_simd:
4187 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4188 EndLoc, VarsWithInheritedDSA);
4189 AllowedNameModifiers.push_back(OMPD_taskloop);
4190 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004191 case OMPD_distribute:
4192 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4193 EndLoc, VarsWithInheritedDSA);
4194 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004195 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004196 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4197 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004198 AllowedNameModifiers.push_back(OMPD_target_update);
4199 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004200 case OMPD_distribute_parallel_for:
4201 Res = ActOnOpenMPDistributeParallelForDirective(
4202 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4203 AllowedNameModifiers.push_back(OMPD_parallel);
4204 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004205 case OMPD_distribute_parallel_for_simd:
4206 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4207 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4208 AllowedNameModifiers.push_back(OMPD_parallel);
4209 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004210 case OMPD_distribute_simd:
4211 Res = ActOnOpenMPDistributeSimdDirective(
4212 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4213 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004214 case OMPD_target_parallel_for_simd:
4215 Res = ActOnOpenMPTargetParallelForSimdDirective(
4216 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4217 AllowedNameModifiers.push_back(OMPD_target);
4218 AllowedNameModifiers.push_back(OMPD_parallel);
4219 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004220 case OMPD_target_simd:
4221 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4222 EndLoc, VarsWithInheritedDSA);
4223 AllowedNameModifiers.push_back(OMPD_target);
4224 break;
Kelvin Li02532872016-08-05 14:37:37 +00004225 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004226 Res = ActOnOpenMPTeamsDistributeDirective(
4227 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004228 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004229 case OMPD_teams_distribute_simd:
4230 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4231 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4232 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004233 case OMPD_teams_distribute_parallel_for_simd:
4234 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4235 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4236 AllowedNameModifiers.push_back(OMPD_parallel);
4237 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004238 case OMPD_teams_distribute_parallel_for:
4239 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4240 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4241 AllowedNameModifiers.push_back(OMPD_parallel);
4242 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004243 case OMPD_target_teams:
4244 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4245 EndLoc);
4246 AllowedNameModifiers.push_back(OMPD_target);
4247 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004248 case OMPD_target_teams_distribute:
4249 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4250 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4251 AllowedNameModifiers.push_back(OMPD_target);
4252 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004253 case OMPD_target_teams_distribute_parallel_for:
4254 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4255 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4256 AllowedNameModifiers.push_back(OMPD_target);
4257 AllowedNameModifiers.push_back(OMPD_parallel);
4258 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004259 case OMPD_target_teams_distribute_parallel_for_simd:
4260 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4261 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4262 AllowedNameModifiers.push_back(OMPD_target);
4263 AllowedNameModifiers.push_back(OMPD_parallel);
4264 break;
Kelvin Lida681182017-01-10 18:08:18 +00004265 case OMPD_target_teams_distribute_simd:
4266 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4267 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4268 AllowedNameModifiers.push_back(OMPD_target);
4269 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004270 case OMPD_declare_target:
4271 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004272 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004273 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004274 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004275 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004276 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004277 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004278 llvm_unreachable("OpenMP Directive is not allowed");
4279 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004280 llvm_unreachable("Unknown OpenMP directive");
4281 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004282
Roman Lebedevb5700602019-03-20 16:32:36 +00004283 ErrorFound = Res.isInvalid() || ErrorFound;
4284
Alexey Bataev412254a2019-05-09 18:44:53 +00004285 // Check variables in the clauses if default(none) was specified.
4286 if (DSAStack->getDefaultDSA() == DSA_none) {
4287 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4288 for (OMPClause *C : Clauses) {
4289 switch (C->getClauseKind()) {
4290 case OMPC_num_threads:
4291 case OMPC_dist_schedule:
4292 // Do not analyse if no parent teams directive.
4293 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4294 break;
4295 continue;
4296 case OMPC_if:
4297 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4298 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4299 break;
4300 continue;
4301 case OMPC_schedule:
4302 break;
4303 case OMPC_ordered:
4304 case OMPC_device:
4305 case OMPC_num_teams:
4306 case OMPC_thread_limit:
4307 case OMPC_priority:
4308 case OMPC_grainsize:
4309 case OMPC_num_tasks:
4310 case OMPC_hint:
4311 case OMPC_collapse:
4312 case OMPC_safelen:
4313 case OMPC_simdlen:
4314 case OMPC_final:
4315 case OMPC_default:
4316 case OMPC_proc_bind:
4317 case OMPC_private:
4318 case OMPC_firstprivate:
4319 case OMPC_lastprivate:
4320 case OMPC_shared:
4321 case OMPC_reduction:
4322 case OMPC_task_reduction:
4323 case OMPC_in_reduction:
4324 case OMPC_linear:
4325 case OMPC_aligned:
4326 case OMPC_copyin:
4327 case OMPC_copyprivate:
4328 case OMPC_nowait:
4329 case OMPC_untied:
4330 case OMPC_mergeable:
4331 case OMPC_allocate:
4332 case OMPC_read:
4333 case OMPC_write:
4334 case OMPC_update:
4335 case OMPC_capture:
4336 case OMPC_seq_cst:
4337 case OMPC_depend:
4338 case OMPC_threads:
4339 case OMPC_simd:
4340 case OMPC_map:
4341 case OMPC_nogroup:
4342 case OMPC_defaultmap:
4343 case OMPC_to:
4344 case OMPC_from:
4345 case OMPC_use_device_ptr:
4346 case OMPC_is_device_ptr:
4347 continue;
4348 case OMPC_allocator:
4349 case OMPC_flush:
4350 case OMPC_threadprivate:
4351 case OMPC_uniform:
4352 case OMPC_unknown:
4353 case OMPC_unified_address:
4354 case OMPC_unified_shared_memory:
4355 case OMPC_reverse_offload:
4356 case OMPC_dynamic_allocators:
4357 case OMPC_atomic_default_mem_order:
4358 llvm_unreachable("Unexpected clause");
4359 }
4360 for (Stmt *CC : C->children()) {
4361 if (CC)
4362 DSAChecker.Visit(CC);
4363 }
4364 }
4365 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4366 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4367 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004368 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00004369 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4370 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004371 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004372 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004373 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
4374
4375 if (!AllowedNameModifiers.empty())
4376 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4377 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004378
Alexey Bataeved09d242014-05-28 05:53:51 +00004379 if (ErrorFound)
4380 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004381
4382 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4383 Res.getAs<OMPExecutableDirective>()
4384 ->getStructuredBlock()
4385 ->setIsOMPStructuredBlock(true);
4386 }
4387
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004388 if (!CurContext->isDependentContext() &&
4389 isOpenMPTargetExecutionDirective(Kind) &&
4390 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4391 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4392 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4393 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4394 // Register target to DSA Stack.
4395 DSAStack->addTargetDirLocation(StartLoc);
4396 }
4397
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004398 return Res;
4399}
4400
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004401Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4402 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004403 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004404 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4405 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004406 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004407 assert(Linears.size() == LinModifiers.size());
4408 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004409 if (!DG || DG.get().isNull())
4410 return DeclGroupPtrTy();
4411
4412 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00004413 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004414 return DG;
4415 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004416 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004417 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4418 ADecl = FTD->getTemplatedDecl();
4419
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004420 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4421 if (!FD) {
4422 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004423 return DeclGroupPtrTy();
4424 }
4425
Alexey Bataev2af33e32016-04-07 12:45:37 +00004426 // OpenMP [2.8.2, declare simd construct, Description]
4427 // The parameter of the simdlen clause must be a constant positive integer
4428 // expression.
4429 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004430 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004431 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004432 // OpenMP [2.8.2, declare simd construct, Description]
4433 // The special this pointer can be used as if was one of the arguments to the
4434 // function in any of the linear, aligned, or uniform clauses.
4435 // The uniform clause declares one or more arguments to have an invariant
4436 // value for all concurrent invocations of the function in the execution of a
4437 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004438 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4439 const Expr *UniformedLinearThis = nullptr;
4440 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004441 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004442 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4443 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004444 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4445 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004446 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004447 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004448 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004449 }
4450 if (isa<CXXThisExpr>(E)) {
4451 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004452 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004453 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004454 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4455 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004456 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004457 // OpenMP [2.8.2, declare simd construct, Description]
4458 // The aligned clause declares that the object to which each list item points
4459 // is aligned to the number of bytes expressed in the optional parameter of
4460 // the aligned clause.
4461 // The special this pointer can be used as if was one of the arguments to the
4462 // function in any of the linear, aligned, or uniform clauses.
4463 // The type of list items appearing in the aligned clause must be array,
4464 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004465 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4466 const Expr *AlignedThis = nullptr;
4467 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004468 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004469 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4470 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4471 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004472 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4473 FD->getParamDecl(PVD->getFunctionScopeIndex())
4474 ->getCanonicalDecl() == CanonPVD) {
4475 // OpenMP [2.8.1, simd construct, Restrictions]
4476 // A list-item cannot appear in more than one aligned clause.
4477 if (AlignedArgs.count(CanonPVD) > 0) {
4478 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4479 << 1 << E->getSourceRange();
4480 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4481 diag::note_omp_explicit_dsa)
4482 << getOpenMPClauseName(OMPC_aligned);
4483 continue;
4484 }
4485 AlignedArgs[CanonPVD] = E;
4486 QualType QTy = PVD->getType()
4487 .getNonReferenceType()
4488 .getUnqualifiedType()
4489 .getCanonicalType();
4490 const Type *Ty = QTy.getTypePtrOrNull();
4491 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4492 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4493 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4494 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4495 }
4496 continue;
4497 }
4498 }
4499 if (isa<CXXThisExpr>(E)) {
4500 if (AlignedThis) {
4501 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4502 << 2 << E->getSourceRange();
4503 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4504 << getOpenMPClauseName(OMPC_aligned);
4505 }
4506 AlignedThis = E;
4507 continue;
4508 }
4509 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4510 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4511 }
4512 // The optional parameter of the aligned clause, alignment, must be a constant
4513 // positive integer expression. If no optional parameter is specified,
4514 // implementation-defined default alignments for SIMD instructions on the
4515 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004516 SmallVector<const Expr *, 4> NewAligns;
4517 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004518 ExprResult Align;
4519 if (E)
4520 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4521 NewAligns.push_back(Align.get());
4522 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004523 // OpenMP [2.8.2, declare simd construct, Description]
4524 // The linear clause declares one or more list items to be private to a SIMD
4525 // lane and to have a linear relationship with respect to the iteration space
4526 // of a loop.
4527 // The special this pointer can be used as if was one of the arguments to the
4528 // function in any of the linear, aligned, or uniform clauses.
4529 // When a linear-step expression is specified in a linear clause it must be
4530 // either a constant integer expression or an integer-typed parameter that is
4531 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004532 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004533 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4534 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004535 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004536 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4537 ++MI;
4538 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004539 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4540 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4541 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004542 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4543 FD->getParamDecl(PVD->getFunctionScopeIndex())
4544 ->getCanonicalDecl() == CanonPVD) {
4545 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4546 // A list-item cannot appear in more than one linear clause.
4547 if (LinearArgs.count(CanonPVD) > 0) {
4548 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4549 << getOpenMPClauseName(OMPC_linear)
4550 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4551 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4552 diag::note_omp_explicit_dsa)
4553 << getOpenMPClauseName(OMPC_linear);
4554 continue;
4555 }
4556 // Each argument can appear in at most one uniform or linear clause.
4557 if (UniformedArgs.count(CanonPVD) > 0) {
4558 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4559 << getOpenMPClauseName(OMPC_linear)
4560 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4561 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4562 diag::note_omp_explicit_dsa)
4563 << getOpenMPClauseName(OMPC_uniform);
4564 continue;
4565 }
4566 LinearArgs[CanonPVD] = E;
4567 if (E->isValueDependent() || E->isTypeDependent() ||
4568 E->isInstantiationDependent() ||
4569 E->containsUnexpandedParameterPack())
4570 continue;
4571 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4572 PVD->getOriginalType());
4573 continue;
4574 }
4575 }
4576 if (isa<CXXThisExpr>(E)) {
4577 if (UniformedLinearThis) {
4578 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4579 << getOpenMPClauseName(OMPC_linear)
4580 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4581 << E->getSourceRange();
4582 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4583 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4584 : OMPC_linear);
4585 continue;
4586 }
4587 UniformedLinearThis = E;
4588 if (E->isValueDependent() || E->isTypeDependent() ||
4589 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4590 continue;
4591 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4592 E->getType());
4593 continue;
4594 }
4595 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4596 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4597 }
4598 Expr *Step = nullptr;
4599 Expr *NewStep = nullptr;
4600 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004601 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004602 // Skip the same step expression, it was checked already.
4603 if (Step == E || !E) {
4604 NewSteps.push_back(E ? NewStep : nullptr);
4605 continue;
4606 }
4607 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004608 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4609 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4610 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004611 if (UniformedArgs.count(CanonPVD) == 0) {
4612 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4613 << Step->getSourceRange();
4614 } else if (E->isValueDependent() || E->isTypeDependent() ||
4615 E->isInstantiationDependent() ||
4616 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004617 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004618 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004619 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004620 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4621 << Step->getSourceRange();
4622 }
4623 continue;
4624 }
4625 NewStep = Step;
4626 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4627 !Step->isInstantiationDependent() &&
4628 !Step->containsUnexpandedParameterPack()) {
4629 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4630 .get();
4631 if (NewStep)
4632 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4633 }
4634 NewSteps.push_back(NewStep);
4635 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004636 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4637 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004638 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004639 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4640 const_cast<Expr **>(Linears.data()), Linears.size(),
4641 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4642 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004643 ADecl->addAttr(NewAttr);
4644 return ConvertDeclToDeclGroup(ADecl);
4645}
4646
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004647StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4648 Stmt *AStmt,
4649 SourceLocation StartLoc,
4650 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004651 if (!AStmt)
4652 return StmtError();
4653
Alexey Bataeve3727102018-04-18 15:57:46 +00004654 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004655 // 1.2.2 OpenMP Language Terminology
4656 // Structured block - An executable statement with a single entry at the
4657 // top and a single exit at the bottom.
4658 // The point of exit cannot be a branch out of the structured block.
4659 // longjmp() and throw() must not violate the entry/exit criteria.
4660 CS->getCapturedDecl()->setNothrow();
4661
Reid Kleckner87a31802018-03-12 21:43:02 +00004662 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004663
Alexey Bataev25e5b442015-09-15 12:52:43 +00004664 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4665 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004666}
4667
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004668namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004669/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004670/// extracting iteration space of each loop in the loop nest, that will be used
4671/// for IR generation.
4672class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004673 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004674 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004675 /// Data-sharing stack.
4676 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004677 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004678 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004679 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004680 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004681 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004682 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004683 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004684 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004685 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004686 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004687 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004688 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004689 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004690 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004691 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004692 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004693 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004694 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004695 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004696 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004697 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004698 /// Var < UB
4699 /// Var <= UB
4700 /// UB > Var
4701 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004702 /// This will have no value when the condition is !=
4703 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004704 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004705 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004706 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004707 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004708 /// The outer loop counter this loop depends on (if any).
4709 const ValueDecl *DepDecl = nullptr;
4710 /// Contains number of loop (starts from 1) on which loop counter init
4711 /// expression of this loop depends on.
4712 Optional<unsigned> InitDependOnLC;
4713 /// Contains number of loop (starts from 1) on which loop counter condition
4714 /// expression of this loop depends on.
4715 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004716 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004717 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004718
4719public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00004720 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
4721 SourceLocation DefaultLoc)
4722 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
4723 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004724 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004725 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004726 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004727 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004728 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004729 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004730 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004731 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004732 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004733 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004734 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004735 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004736 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004737 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004738 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004739 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004740 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004741 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004742 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004743 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004744 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004745 /// True, if the compare operator is strict (<, > or !=).
4746 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004747 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004748 Expr *buildNumIterations(
4749 Scope *S, const bool LimitedType,
4750 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004751 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004752 Expr *
4753 buildPreCond(Scope *S, Expr *Cond,
4754 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004755 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004756 DeclRefExpr *
4757 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4758 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004759 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004760 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004761 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004762 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004763 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004764 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004765 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004766 /// Build loop data with counter value for depend clauses in ordered
4767 /// directives.
4768 Expr *
4769 buildOrderedLoopData(Scope *S, Expr *Counter,
4770 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4771 SourceLocation Loc, Expr *Inc = nullptr,
4772 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004773 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004774 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004775
4776private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004777 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004778 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004779 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004780 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00004781 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
4782 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004783 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004784 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4785 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004786 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004787 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004788};
4789
Alexey Bataeve3727102018-04-18 15:57:46 +00004790bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004791 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004792 assert(!LB && !UB && !Step);
4793 return false;
4794 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004795 return LCDecl->getType()->isDependentType() ||
4796 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4797 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004798}
4799
Alexey Bataeve3727102018-04-18 15:57:46 +00004800bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004801 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00004802 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004803 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004804 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004805 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004806 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004807 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004808 LCDecl = getCanonicalDecl(NewLCDecl);
4809 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004810 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4811 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004812 if ((Ctor->isCopyOrMoveConstructor() ||
4813 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4814 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004815 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004816 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004817 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004818 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004819 return false;
4820}
4821
Alexey Bataev316ccf62019-01-29 18:51:58 +00004822bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4823 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004824 bool StrictOp, SourceRange SR,
4825 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004826 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004827 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4828 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004829 if (!NewUB)
4830 return true;
4831 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004832 if (LessOp)
4833 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004834 TestIsStrictOp = StrictOp;
4835 ConditionSrcRange = SR;
4836 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004837 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004838 return false;
4839}
4840
Alexey Bataeve3727102018-04-18 15:57:46 +00004841bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004842 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004843 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004844 if (!NewStep)
4845 return true;
4846 if (!NewStep->isValueDependent()) {
4847 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004848 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004849 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4850 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004851 if (Val.isInvalid())
4852 return true;
4853 NewStep = Val.get();
4854
4855 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4856 // If test-expr is of form var relational-op b and relational-op is < or
4857 // <= then incr-expr must cause var to increase on each iteration of the
4858 // loop. If test-expr is of form var relational-op b and relational-op is
4859 // > or >= then incr-expr must cause var to decrease on each iteration of
4860 // the loop.
4861 // If test-expr is of form b relational-op var and relational-op is < or
4862 // <= then incr-expr must cause var to decrease on each iteration of the
4863 // loop. If test-expr is of form b relational-op var and relational-op is
4864 // > or >= then incr-expr must cause var to increase on each iteration of
4865 // the loop.
4866 llvm::APSInt Result;
4867 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4868 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4869 bool IsConstNeg =
4870 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004871 bool IsConstPos =
4872 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004873 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004874
4875 // != with increment is treated as <; != with decrement is treated as >
4876 if (!TestIsLessOp.hasValue())
4877 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004878 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004879 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004880 (IsConstNeg || (IsUnsigned && Subtract)) :
4881 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004882 SemaRef.Diag(NewStep->getExprLoc(),
4883 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004884 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004885 SemaRef.Diag(ConditionLoc,
4886 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004887 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004888 return true;
4889 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004890 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004891 NewStep =
4892 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4893 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004894 Subtract = !Subtract;
4895 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004896 }
4897
4898 Step = NewStep;
4899 SubtractStep = Subtract;
4900 return false;
4901}
4902
Alexey Bataev622af1d2019-04-24 19:58:30 +00004903namespace {
4904/// Checker for the non-rectangular loops. Checks if the initializer or
4905/// condition expression references loop counter variable.
4906class LoopCounterRefChecker final
4907 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
4908 Sema &SemaRef;
4909 DSAStackTy &Stack;
4910 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004911 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004912 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004913 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004914 unsigned BaseLoopId = 0;
4915 bool checkDecl(const Expr *E, const ValueDecl *VD) {
4916 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
4917 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
4918 << (IsInitializer ? 0 : 1);
4919 return false;
4920 }
4921 const auto &&Data = Stack.isLoopControlVariable(VD);
4922 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
4923 // The type of the loop iterator on which we depend may not have a random
4924 // access iterator type.
4925 if (Data.first && VD->getType()->isRecordType()) {
4926 SmallString<128> Name;
4927 llvm::raw_svector_ostream OS(Name);
4928 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4929 /*Qualified=*/true);
4930 SemaRef.Diag(E->getExprLoc(),
4931 diag::err_omp_wrong_dependency_iterator_type)
4932 << OS.str();
4933 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
4934 return false;
4935 }
4936 if (Data.first &&
4937 (DepDecl || (PrevDepDecl &&
4938 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
4939 if (!DepDecl && PrevDepDecl)
4940 DepDecl = PrevDepDecl;
4941 SmallString<128> Name;
4942 llvm::raw_svector_ostream OS(Name);
4943 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4944 /*Qualified=*/true);
4945 SemaRef.Diag(E->getExprLoc(),
4946 diag::err_omp_invariant_or_linear_dependency)
4947 << OS.str();
4948 return false;
4949 }
4950 if (Data.first) {
4951 DepDecl = VD;
4952 BaseLoopId = Data.first;
4953 }
4954 return Data.first;
4955 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004956
4957public:
4958 bool VisitDeclRefExpr(const DeclRefExpr *E) {
4959 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004960 if (isa<VarDecl>(VD))
4961 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00004962 return false;
4963 }
4964 bool VisitMemberExpr(const MemberExpr *E) {
4965 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
4966 const ValueDecl *VD = E->getMemberDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004967 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00004968 }
4969 return false;
4970 }
4971 bool VisitStmt(const Stmt *S) {
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004972 bool Res = true;
4973 for (const Stmt *Child : S->children())
4974 Res = Child && Visit(Child) && Res;
4975 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004976 }
4977 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004978 const ValueDecl *CurLCDecl, bool IsInitializer,
4979 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00004980 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004981 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
4982 unsigned getBaseLoopId() const {
4983 assert(CurLCDecl && "Expected loop dependency.");
4984 return BaseLoopId;
4985 }
4986 const ValueDecl *getDepDecl() const {
4987 assert(CurLCDecl && "Expected loop dependency.");
4988 return DepDecl;
4989 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004990};
4991} // namespace
4992
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004993Optional<unsigned>
4994OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
4995 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00004996 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004997 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
4998 DepDecl);
4999 if (LoopStmtChecker.Visit(S)) {
5000 DepDecl = LoopStmtChecker.getDepDecl();
5001 return LoopStmtChecker.getBaseLoopId();
5002 }
5003 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005004}
5005
Alexey Bataeve3727102018-04-18 15:57:46 +00005006bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005007 // Check init-expr for canonical loop form and save loop counter
5008 // variable - #Var and its initialization value - #LB.
5009 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5010 // var = lb
5011 // integer-type var = lb
5012 // random-access-iterator-type var = lb
5013 // pointer-type var = lb
5014 //
5015 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005016 if (EmitDiags) {
5017 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5018 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005019 return true;
5020 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005021 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5022 if (!ExprTemp->cleanupsHaveSideEffects())
5023 S = ExprTemp->getSubExpr();
5024
Alexander Musmana5f070a2014-10-01 06:03:56 +00005025 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005026 if (Expr *E = dyn_cast<Expr>(S))
5027 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005028 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005029 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005030 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005031 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5032 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5033 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005034 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5035 EmitDiags);
5036 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005037 }
5038 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5039 if (ME->isArrow() &&
5040 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005041 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5042 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005043 }
5044 }
David Majnemer9d168222016-08-05 17:44:54 +00005045 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005046 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005047 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005048 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005049 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005050 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005051 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005052 diag::ext_omp_loop_not_canonical_init)
5053 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005054 return setLCDeclAndLB(
5055 Var,
5056 buildDeclRefExpr(SemaRef, Var,
5057 Var->getType().getNonReferenceType(),
5058 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005059 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005060 }
5061 }
5062 }
David Majnemer9d168222016-08-05 17:44:54 +00005063 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005064 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005065 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005066 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005067 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5068 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005069 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5070 EmitDiags);
5071 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005072 }
5073 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5074 if (ME->isArrow() &&
5075 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005076 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5077 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005078 }
5079 }
5080 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005081
Alexey Bataeve3727102018-04-18 15:57:46 +00005082 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005083 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005084 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005085 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005086 << S->getSourceRange();
5087 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005088 return true;
5089}
5090
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005091/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005092/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005093static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005094 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005095 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005096 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005097 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005098 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005099 if ((Ctor->isCopyOrMoveConstructor() ||
5100 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5101 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005102 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005103 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5104 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005105 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005106 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005107 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005108 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5109 return getCanonicalDecl(ME->getMemberDecl());
5110 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005111}
5112
Alexey Bataeve3727102018-04-18 15:57:46 +00005113bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005114 // Check test-expr for canonical form, save upper-bound UB, flags for
5115 // less/greater and for strict/non-strict comparison.
5116 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5117 // var relational-op b
5118 // b relational-op var
5119 //
5120 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005121 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005122 return true;
5123 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005124 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005125 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005126 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005127 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005128 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5129 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005130 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5131 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5132 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005133 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5134 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005135 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5136 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5137 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005138 } else if (BO->getOpcode() == BO_NE)
5139 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
5140 BO->getRHS() : BO->getLHS(),
5141 /*LessOp=*/llvm::None,
5142 /*StrictOp=*/true,
5143 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005144 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005145 if (CE->getNumArgs() == 2) {
5146 auto Op = CE->getOperator();
5147 switch (Op) {
5148 case OO_Greater:
5149 case OO_GreaterEqual:
5150 case OO_Less:
5151 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005152 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5153 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005154 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5155 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005156 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5157 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005158 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5159 CE->getOperatorLoc());
5160 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005161 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00005162 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
5163 CE->getArg(1) : CE->getArg(0),
5164 /*LessOp=*/llvm::None,
5165 /*StrictOp=*/true,
5166 CE->getSourceRange(),
5167 CE->getOperatorLoc());
5168 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005169 default:
5170 break;
5171 }
5172 }
5173 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005174 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005175 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005176 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005177 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005178 return true;
5179}
5180
Alexey Bataeve3727102018-04-18 15:57:46 +00005181bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005182 // RHS of canonical loop form increment can be:
5183 // var + incr
5184 // incr + var
5185 // var - incr
5186 //
5187 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005188 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005189 if (BO->isAdditiveOp()) {
5190 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005191 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5192 return setStep(BO->getRHS(), !IsAdd);
5193 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5194 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005195 }
David Majnemer9d168222016-08-05 17:44:54 +00005196 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005197 bool IsAdd = CE->getOperator() == OO_Plus;
5198 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005199 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5200 return setStep(CE->getArg(1), !IsAdd);
5201 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5202 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005203 }
5204 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005205 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005206 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005207 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005208 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005209 return true;
5210}
5211
Alexey Bataeve3727102018-04-18 15:57:46 +00005212bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005213 // Check incr-expr for canonical loop form and return true if it
5214 // does not conform.
5215 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5216 // ++var
5217 // var++
5218 // --var
5219 // var--
5220 // var += incr
5221 // var -= incr
5222 // var = var + incr
5223 // var = incr + var
5224 // var = var - incr
5225 //
5226 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005227 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005228 return true;
5229 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005230 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5231 if (!ExprTemp->cleanupsHaveSideEffects())
5232 S = ExprTemp->getSubExpr();
5233
Alexander Musmana5f070a2014-10-01 06:03:56 +00005234 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005235 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005236 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005237 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005238 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5239 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005240 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005241 (UO->isDecrementOp() ? -1 : 1))
5242 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005243 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005244 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005245 switch (BO->getOpcode()) {
5246 case BO_AddAssign:
5247 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005248 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5249 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005250 break;
5251 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005252 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5253 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005254 break;
5255 default:
5256 break;
5257 }
David Majnemer9d168222016-08-05 17:44:54 +00005258 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005259 switch (CE->getOperator()) {
5260 case OO_PlusPlus:
5261 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005262 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5263 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005264 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005265 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005266 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5267 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005268 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005269 break;
5270 case OO_PlusEqual:
5271 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005272 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5273 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005274 break;
5275 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005276 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5277 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005278 break;
5279 default:
5280 break;
5281 }
5282 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005283 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005284 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005285 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005286 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005287 return true;
5288}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005289
Alexey Bataev5a3af132016-03-29 08:58:54 +00005290static ExprResult
5291tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005292 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005293 if (SemaRef.CurContext->isDependentContext())
5294 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005295 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5296 return SemaRef.PerformImplicitConversion(
5297 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5298 /*AllowExplicit=*/true);
5299 auto I = Captures.find(Capture);
5300 if (I != Captures.end())
5301 return buildCapture(SemaRef, Capture, I->second);
5302 DeclRefExpr *Ref = nullptr;
5303 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5304 Captures[Capture] = Ref;
5305 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005306}
5307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005308/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005309Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005310 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005311 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005312 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005313 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005314 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005315 SemaRef.getLangOpts().CPlusPlus) {
5316 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00005317 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
5318 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00005319 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
5320 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005321 if (!Upper || !Lower)
5322 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005323
5324 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5325
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005326 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005327 // BuildBinOp already emitted error, this one is to point user to upper
5328 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005329 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005330 << Upper->getSourceRange() << Lower->getSourceRange();
5331 return nullptr;
5332 }
5333 }
5334
5335 if (!Diff.isUsable())
5336 return nullptr;
5337
5338 // Upper - Lower [- 1]
5339 if (TestIsStrictOp)
5340 Diff = SemaRef.BuildBinOp(
5341 S, DefaultLoc, BO_Sub, Diff.get(),
5342 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5343 if (!Diff.isUsable())
5344 return nullptr;
5345
5346 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005347 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005348 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005349 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005350 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005351 if (!Diff.isUsable())
5352 return nullptr;
5353
5354 // Parentheses (for dumping/debugging purposes only).
5355 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5356 if (!Diff.isUsable())
5357 return nullptr;
5358
5359 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005360 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005361 if (!Diff.isUsable())
5362 return nullptr;
5363
Alexander Musman174b3ca2014-10-06 11:16:29 +00005364 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005365 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00005366 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005367 bool UseVarType = VarType->hasIntegerRepresentation() &&
5368 C.getTypeSize(Type) > C.getTypeSize(VarType);
5369 if (!Type->isIntegerType() || UseVarType) {
5370 unsigned NewSize =
5371 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
5372 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
5373 : Type->hasSignedIntegerRepresentation();
5374 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00005375 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
5376 Diff = SemaRef.PerformImplicitConversion(
5377 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
5378 if (!Diff.isUsable())
5379 return nullptr;
5380 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005381 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005382 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00005383 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
5384 if (NewSize != C.getTypeSize(Type)) {
5385 if (NewSize < C.getTypeSize(Type)) {
5386 assert(NewSize == 64 && "incorrect loop var size");
5387 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
5388 << InitSrcRange << ConditionSrcRange;
5389 }
5390 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005391 NewSize, Type->hasSignedIntegerRepresentation() ||
5392 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00005393 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
5394 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
5395 Sema::AA_Converting, true);
5396 if (!Diff.isUsable())
5397 return nullptr;
5398 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005399 }
5400 }
5401
Alexander Musmana5f070a2014-10-01 06:03:56 +00005402 return Diff.get();
5403}
5404
Alexey Bataeve3727102018-04-18 15:57:46 +00005405Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005406 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00005407 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005408 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
5409 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5410 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005411
Alexey Bataeve3727102018-04-18 15:57:46 +00005412 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
5413 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005414 if (!NewLB.isUsable() || !NewUB.isUsable())
5415 return nullptr;
5416
Alexey Bataeve3727102018-04-18 15:57:46 +00005417 ExprResult CondExpr =
5418 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005419 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005420 (TestIsStrictOp ? BO_LT : BO_LE) :
5421 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00005422 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005423 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005424 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
5425 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00005426 CondExpr = SemaRef.PerformImplicitConversion(
5427 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
5428 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005429 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00005430 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00005431 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005432 return CondExpr.isUsable() ? CondExpr.get() : Cond;
5433}
5434
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005435/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005436DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00005437 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5438 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005439 auto *VD = dyn_cast<VarDecl>(LCDecl);
5440 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005441 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
5442 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005443 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005444 const DSAStackTy::DSAVarData Data =
5445 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005446 // If the loop control decl is explicitly marked as private, do not mark it
5447 // as captured again.
5448 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
5449 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005450 return Ref;
5451 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00005452 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00005453}
5454
Alexey Bataeve3727102018-04-18 15:57:46 +00005455Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005456 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005457 QualType Type = LCDecl->getType().getNonReferenceType();
5458 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00005459 SemaRef, DefaultLoc, Type, LCDecl->getName(),
5460 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
5461 isa<VarDecl>(LCDecl)
5462 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
5463 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00005464 if (PrivateVar->isInvalidDecl())
5465 return nullptr;
5466 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
5467 }
5468 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005469}
5470
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005471/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005472Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005473
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005474/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005475Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005476
Alexey Bataevf138fda2018-08-13 19:04:24 +00005477Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
5478 Scope *S, Expr *Counter,
5479 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
5480 Expr *Inc, OverloadedOperatorKind OOK) {
5481 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
5482 if (!Cnt)
5483 return nullptr;
5484 if (Inc) {
5485 assert((OOK == OO_Plus || OOK == OO_Minus) &&
5486 "Expected only + or - operations for depend clauses.");
5487 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
5488 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
5489 if (!Cnt)
5490 return nullptr;
5491 }
5492 ExprResult Diff;
5493 QualType VarType = LCDecl->getType().getNonReferenceType();
5494 if (VarType->isIntegerType() || VarType->isPointerType() ||
5495 SemaRef.getLangOpts().CPlusPlus) {
5496 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00005497 Expr *Upper = TestIsLessOp.getValue()
5498 ? Cnt
5499 : tryBuildCapture(SemaRef, UB, Captures).get();
5500 Expr *Lower = TestIsLessOp.getValue()
5501 ? tryBuildCapture(SemaRef, LB, Captures).get()
5502 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005503 if (!Upper || !Lower)
5504 return nullptr;
5505
5506 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5507
5508 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5509 // BuildBinOp already emitted error, this one is to point user to upper
5510 // and lower bound, and to tell what is passed to 'operator-'.
5511 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5512 << Upper->getSourceRange() << Lower->getSourceRange();
5513 return nullptr;
5514 }
5515 }
5516
5517 if (!Diff.isUsable())
5518 return nullptr;
5519
5520 // Parentheses (for dumping/debugging purposes only).
5521 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5522 if (!Diff.isUsable())
5523 return nullptr;
5524
5525 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5526 if (!NewStep.isUsable())
5527 return nullptr;
5528 // (Upper - Lower) / Step
5529 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5530 if (!Diff.isUsable())
5531 return nullptr;
5532
5533 return Diff.get();
5534}
5535
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005536/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005537struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005538 /// True if the condition operator is the strict compare operator (<, > or
5539 /// !=).
5540 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005541 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005542 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005543 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005544 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005545 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005546 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005547 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005548 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005549 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005550 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00005551 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005552 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005553 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005554 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005555 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005556 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005557 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005558 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005559 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005560 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005561 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005562 SourceRange IncSrcRange;
5563};
5564
Alexey Bataev23b69422014-06-18 07:08:49 +00005565} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005566
Alexey Bataev9c821032015-04-30 04:23:23 +00005567void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5568 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5569 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005570 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5571 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005572 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005573 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00005574 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005575 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5576 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005577 auto *VD = dyn_cast<VarDecl>(D);
5578 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005579 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005580 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005581 } else {
5582 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5583 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005584 VD = cast<VarDecl>(Ref->getDecl());
5585 }
5586 }
5587 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005588 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5589 if (LD != D->getCanonicalDecl()) {
5590 DSAStack->resetPossibleLoopCounter();
5591 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5592 MarkDeclarationsReferencedInExpr(
5593 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5594 Var->getType().getNonLValueExprType(Context),
5595 ForLoc, /*RefersToCapture=*/true));
5596 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005597 }
5598 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005599 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005600 }
5601}
5602
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005603/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005604/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005605static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005606 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5607 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005608 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5609 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005610 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005611 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005612 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005613 // OpenMP [2.6, Canonical Loop Form]
5614 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005615 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005616 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005617 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005618 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005619 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005620 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005621 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005622 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5623 SemaRef.Diag(DSA.getConstructLoc(),
5624 diag::note_omp_collapse_ordered_expr)
5625 << 2 << CollapseLoopCountExpr->getSourceRange()
5626 << OrderedLoopCountExpr->getSourceRange();
5627 else if (CollapseLoopCountExpr)
5628 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5629 diag::note_omp_collapse_ordered_expr)
5630 << 0 << CollapseLoopCountExpr->getSourceRange();
5631 else
5632 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5633 diag::note_omp_collapse_ordered_expr)
5634 << 1 << OrderedLoopCountExpr->getSourceRange();
5635 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005636 return true;
5637 }
5638 assert(For->getBody());
5639
Alexey Bataev622af1d2019-04-24 19:58:30 +00005640 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005641
5642 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005643 Stmt *Init = For->getInit();
5644 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005645 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005646
5647 bool HasErrors = false;
5648
5649 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005650 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5651 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005652
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005653 // OpenMP [2.6, Canonical Loop Form]
5654 // Var is one of the following:
5655 // A variable of signed or unsigned integer type.
5656 // For C++, a variable of a random access iterator type.
5657 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005658 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005659 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5660 !VarType->isPointerType() &&
5661 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005662 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005663 << SemaRef.getLangOpts().CPlusPlus;
5664 HasErrors = true;
5665 }
5666
5667 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5668 // a Construct
5669 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5670 // parallel for construct is (are) private.
5671 // The loop iteration variable in the associated for-loop of a simd
5672 // construct with just one associated for-loop is linear with a
5673 // constant-linear-step that is the increment of the associated for-loop.
5674 // Exclude loop var from the list of variables with implicitly defined data
5675 // sharing attributes.
5676 VarsWithImplicitDSA.erase(LCDecl);
5677
5678 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5679 // in a Construct, C/C++].
5680 // The loop iteration variable in the associated for-loop of a simd
5681 // construct with just one associated for-loop may be listed in a linear
5682 // clause with a constant-linear-step that is the increment of the
5683 // associated for-loop.
5684 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5685 // parallel for construct may be listed in a private or lastprivate clause.
5686 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5687 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5688 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005689 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005690 isOpenMPSimdDirective(DKind)
5691 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5692 : OMPC_private;
5693 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5694 DVar.CKind != PredeterminedCKind) ||
5695 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5696 isOpenMPDistributeDirective(DKind)) &&
5697 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5698 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5699 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005700 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005701 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5702 << getOpenMPClauseName(PredeterminedCKind);
5703 if (DVar.RefExpr == nullptr)
5704 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005705 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005706 HasErrors = true;
5707 } else if (LoopDeclRefExpr != nullptr) {
5708 // Make the loop iteration variable private (for worksharing constructs),
5709 // linear (for simd directives with the only one associated loop) or
5710 // lastprivate (for simd directives with several collapsed or ordered
5711 // loops).
5712 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005713 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005714 }
5715
5716 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5717
5718 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005719 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005720
5721 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005722 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005723 }
5724
Alexey Bataeve3727102018-04-18 15:57:46 +00005725 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005726 return HasErrors;
5727
Alexander Musmana5f070a2014-10-01 06:03:56 +00005728 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005729 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005730 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5731 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005732 DSA.getCurScope(),
5733 (isOpenMPWorksharingDirective(DKind) ||
5734 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5735 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005736 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5737 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5738 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5739 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5740 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5741 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5742 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5743 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005744 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005745
Alexey Bataev62dbb972015-04-22 11:59:37 +00005746 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5747 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005748 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005749 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005750 ResultIterSpace.CounterInit == nullptr ||
5751 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005752 if (!HasErrors && DSA.isOrderedRegion()) {
5753 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5754 if (CurrentNestedLoopCount <
5755 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5756 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5757 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5758 DSA.getOrderedRegionParam().second->setLoopCounter(
5759 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5760 }
5761 }
5762 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5763 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5764 // Erroneous case - clause has some problems.
5765 continue;
5766 }
5767 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5768 Pair.second.size() <= CurrentNestedLoopCount) {
5769 // Erroneous case - clause has some problems.
5770 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5771 continue;
5772 }
5773 Expr *CntValue;
5774 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5775 CntValue = ISC.buildOrderedLoopData(
5776 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5777 Pair.first->getDependencyLoc());
5778 else
5779 CntValue = ISC.buildOrderedLoopData(
5780 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5781 Pair.first->getDependencyLoc(),
5782 Pair.second[CurrentNestedLoopCount].first,
5783 Pair.second[CurrentNestedLoopCount].second);
5784 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5785 }
5786 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005787
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005788 return HasErrors;
5789}
5790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005791/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005792static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005793buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005794 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005795 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005796 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005797 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005798 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005799 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005800 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005801 VarRef.get()->getType())) {
5802 NewStart = SemaRef.PerformImplicitConversion(
5803 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5804 /*AllowExplicit=*/true);
5805 if (!NewStart.isUsable())
5806 return ExprError();
5807 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005808
Alexey Bataeve3727102018-04-18 15:57:46 +00005809 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005810 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5811 return Init;
5812}
5813
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005814/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005815static ExprResult buildCounterUpdate(
5816 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5817 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5818 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005819 // Add parentheses (for debugging purposes only).
5820 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5821 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5822 !Step.isUsable())
5823 return ExprError();
5824
Alexey Bataev5a3af132016-03-29 08:58:54 +00005825 ExprResult NewStep = Step;
5826 if (Captures)
5827 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005828 if (NewStep.isInvalid())
5829 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005830 ExprResult Update =
5831 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005832 if (!Update.isUsable())
5833 return ExprError();
5834
Alexey Bataevc0214e02016-02-16 12:13:49 +00005835 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5836 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005837 ExprResult NewStart = Start;
5838 if (Captures)
5839 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005840 if (NewStart.isInvalid())
5841 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005842
Alexey Bataevc0214e02016-02-16 12:13:49 +00005843 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5844 ExprResult SavedUpdate = Update;
5845 ExprResult UpdateVal;
5846 if (VarRef.get()->getType()->isOverloadableType() ||
5847 NewStart.get()->getType()->isOverloadableType() ||
5848 Update.get()->getType()->isOverloadableType()) {
5849 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5850 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5851 Update =
5852 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5853 if (Update.isUsable()) {
5854 UpdateVal =
5855 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5856 VarRef.get(), SavedUpdate.get());
5857 if (UpdateVal.isUsable()) {
5858 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5859 UpdateVal.get());
5860 }
5861 }
5862 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5863 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005864
Alexey Bataevc0214e02016-02-16 12:13:49 +00005865 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5866 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5867 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5868 NewStart.get(), SavedUpdate.get());
5869 if (!Update.isUsable())
5870 return ExprError();
5871
Alexey Bataev11481f52016-02-17 10:29:05 +00005872 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5873 VarRef.get()->getType())) {
5874 Update = SemaRef.PerformImplicitConversion(
5875 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5876 if (!Update.isUsable())
5877 return ExprError();
5878 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005879
5880 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5881 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005882 return Update;
5883}
5884
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005885/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005886/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005887static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005888 if (E == nullptr)
5889 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005890 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005891 QualType OldType = E->getType();
5892 unsigned HasBits = C.getTypeSize(OldType);
5893 if (HasBits >= Bits)
5894 return ExprResult(E);
5895 // OK to convert to signed, because new type has more bits than old.
5896 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5897 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5898 true);
5899}
5900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005901/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005902/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005903static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005904 if (E == nullptr)
5905 return false;
5906 llvm::APSInt Result;
5907 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5908 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5909 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005910}
5911
Alexey Bataev5a3af132016-03-29 08:58:54 +00005912/// Build preinits statement for the given declarations.
5913static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005914 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005915 if (!PreInits.empty()) {
5916 return new (Context) DeclStmt(
5917 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5918 SourceLocation(), SourceLocation());
5919 }
5920 return nullptr;
5921}
5922
5923/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005924static Stmt *
5925buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005926 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005927 if (!Captures.empty()) {
5928 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005929 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005930 PreInits.push_back(Pair.second->getDecl());
5931 return buildPreInits(Context, PreInits);
5932 }
5933 return nullptr;
5934}
5935
5936/// Build postupdate expression for the given list of postupdates expressions.
5937static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5938 Expr *PostUpdate = nullptr;
5939 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005940 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005941 Expr *ConvE = S.BuildCStyleCastExpr(
5942 E->getExprLoc(),
5943 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5944 E->getExprLoc(), E)
5945 .get();
5946 PostUpdate = PostUpdate
5947 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5948 PostUpdate, ConvE)
5949 .get()
5950 : ConvE;
5951 }
5952 }
5953 return PostUpdate;
5954}
5955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005956/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005957/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5958/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005959static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005960checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005961 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5962 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005963 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005964 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005965 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005966 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005967 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005968 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005969 if (!CollapseLoopCountExpr->isValueDependent() &&
5970 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00005971 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005972 } else {
5973 Built.clear(/*size=*/1);
5974 return 1;
5975 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00005976 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005977 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005978 if (OrderedLoopCountExpr) {
5979 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005980 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005981 if (!OrderedLoopCountExpr->isValueDependent() &&
5982 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
5983 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00005984 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005985 if (Result.getLimitedValue() < NestedLoopCount) {
5986 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5987 diag::err_omp_wrong_ordered_loop_count)
5988 << OrderedLoopCountExpr->getSourceRange();
5989 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5990 diag::note_collapse_loop_count)
5991 << CollapseLoopCountExpr->getSourceRange();
5992 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005993 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00005994 } else {
5995 Built.clear(/*size=*/1);
5996 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005997 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005998 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005999 // This is helper routine for loop directives (e.g., 'for', 'simd',
6000 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006001 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006002 SmallVector<LoopIterationSpace, 4> IterSpaces(
6003 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006004 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006005 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006006 if (checkOpenMPIterationSpace(
6007 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6008 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6009 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
6010 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006011 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006012 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006013 // OpenMP [2.8.1, simd construct, Restrictions]
6014 // All loops associated with the construct must be perfectly nested; that
6015 // is, there must be no intervening code nor any OpenMP directive between
6016 // any two loops.
6017 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006018 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006019 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6020 if (checkOpenMPIterationSpace(
6021 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6022 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6023 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
6024 Captures))
6025 return 0;
6026 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6027 // Handle initialization of captured loop iterator variables.
6028 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6029 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6030 Captures[DRE] = DRE;
6031 }
6032 }
6033 // Move on to the next nested for loop, or to the loop body.
6034 // OpenMP [2.8.1, simd construct, Restrictions]
6035 // All loops associated with the construct must be perfectly nested; that
6036 // is, there must be no intervening code nor any OpenMP directive between
6037 // any two loops.
6038 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
6039 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006040
Alexander Musmana5f070a2014-10-01 06:03:56 +00006041 Built.clear(/* size */ NestedLoopCount);
6042
6043 if (SemaRef.CurContext->isDependentContext())
6044 return NestedLoopCount;
6045
6046 // An example of what is generated for the following code:
6047 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006048 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006049 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006050 // for (k = 0; k < NK; ++k)
6051 // for (j = J0; j < NJ; j+=2) {
6052 // <loop body>
6053 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006054 //
6055 // We generate the code below.
6056 // Note: the loop body may be outlined in CodeGen.
6057 // Note: some counters may be C++ classes, operator- is used to find number of
6058 // iterations and operator+= to calculate counter value.
6059 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
6060 // or i64 is currently supported).
6061 //
6062 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
6063 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
6064 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
6065 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
6066 // // similar updates for vars in clauses (e.g. 'linear')
6067 // <loop body (using local i and j)>
6068 // }
6069 // i = NI; // assign final values of counters
6070 // j = NJ;
6071 //
6072
6073 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
6074 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006075 // Precondition tests if there is at least one iteration (all conditions are
6076 // true).
6077 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00006078 Expr *N0 = IterSpaces[0].NumIterations;
6079 ExprResult LastIteration32 =
6080 widenIterationCount(/*Bits=*/32,
6081 SemaRef
6082 .PerformImplicitConversion(
6083 N0->IgnoreImpCasts(), N0->getType(),
6084 Sema::AA_Converting, /*AllowExplicit=*/true)
6085 .get(),
6086 SemaRef);
6087 ExprResult LastIteration64 = widenIterationCount(
6088 /*Bits=*/64,
6089 SemaRef
6090 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
6091 Sema::AA_Converting,
6092 /*AllowExplicit=*/true)
6093 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006094 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006095
6096 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
6097 return NestedLoopCount;
6098
Alexey Bataeve3727102018-04-18 15:57:46 +00006099 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006100 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
6101
6102 Scope *CurScope = DSA.getCurScope();
6103 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006104 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00006105 PreCond =
6106 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
6107 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00006108 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006109 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00006110 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006111 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
6112 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006113 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006114 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006115 SemaRef
6116 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6117 Sema::AA_Converting,
6118 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006119 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006120 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006121 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006122 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006123 SemaRef
6124 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6125 Sema::AA_Converting,
6126 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006127 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006128 }
6129
6130 // Choose either the 32-bit or 64-bit version.
6131 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006132 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
6133 (LastIteration32.isUsable() &&
6134 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
6135 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
6136 fitsInto(
6137 /*Bits=*/32,
6138 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
6139 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00006140 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00006141 QualType VType = LastIteration.get()->getType();
6142 QualType RealVType = VType;
6143 QualType StrideVType = VType;
6144 if (isOpenMPTaskLoopDirective(DKind)) {
6145 VType =
6146 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
6147 StrideVType =
6148 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6149 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006150
6151 if (!LastIteration.isUsable())
6152 return 0;
6153
6154 // Save the number of iterations.
6155 ExprResult NumIterations = LastIteration;
6156 {
6157 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006158 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
6159 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006160 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6161 if (!LastIteration.isUsable())
6162 return 0;
6163 }
6164
6165 // Calculate the last iteration number beforehand instead of doing this on
6166 // each iteration. Do not do this if the number of iterations may be kfold-ed.
6167 llvm::APSInt Result;
6168 bool IsConstant =
6169 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
6170 ExprResult CalcLastIteration;
6171 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006172 ExprResult SaveRef =
6173 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006174 LastIteration = SaveRef;
6175
6176 // Prepare SaveRef + 1.
6177 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006178 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006179 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6180 if (!NumIterations.isUsable())
6181 return 0;
6182 }
6183
6184 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
6185
David Majnemer9d168222016-08-05 17:44:54 +00006186 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006187 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006188 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6189 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006190 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006191 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
6192 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006193 SemaRef.AddInitializerToDecl(LBDecl,
6194 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6195 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006196
6197 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006198 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
6199 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00006200 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00006201 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006202
6203 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
6204 // This will be used to implement clause 'lastprivate'.
6205 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006206 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
6207 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006208 SemaRef.AddInitializerToDecl(ILDecl,
6209 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6210 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006211
6212 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00006213 VarDecl *STDecl =
6214 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
6215 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006216 SemaRef.AddInitializerToDecl(STDecl,
6217 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
6218 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006219
6220 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00006221 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00006222 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
6223 UB.get(), LastIteration.get());
6224 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00006225 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
6226 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00006227 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
6228 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006229 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006230
6231 // If we have a combined directive that combines 'distribute', 'for' or
6232 // 'simd' we need to be able to access the bounds of the schedule of the
6233 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
6234 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
6235 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00006236 // Lower bound variable, initialized with zero.
6237 VarDecl *CombLBDecl =
6238 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
6239 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
6240 SemaRef.AddInitializerToDecl(
6241 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6242 /*DirectInit*/ false);
6243
6244 // Upper bound variable, initialized with last iteration number.
6245 VarDecl *CombUBDecl =
6246 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
6247 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
6248 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
6249 /*DirectInit*/ false);
6250
6251 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
6252 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
6253 ExprResult CombCondOp =
6254 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
6255 LastIteration.get(), CombUB.get());
6256 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
6257 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006258 CombEUB =
6259 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006260
Alexey Bataeve3727102018-04-18 15:57:46 +00006261 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006262 // We expect to have at least 2 more parameters than the 'parallel'
6263 // directive does - the lower and upper bounds of the previous schedule.
6264 assert(CD->getNumParams() >= 4 &&
6265 "Unexpected number of parameters in loop combined directive");
6266
6267 // Set the proper type for the bounds given what we learned from the
6268 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00006269 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
6270 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006271
6272 // Previous lower and upper bounds are obtained from the region
6273 // parameters.
6274 PrevLB =
6275 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
6276 PrevUB =
6277 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
6278 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006279 }
6280
6281 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006282 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006283 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006284 {
Alexey Bataev7292c292016-04-25 12:22:29 +00006285 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
6286 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00006287 Expr *RHS =
6288 (isOpenMPWorksharingDirective(DKind) ||
6289 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
6290 ? LB.get()
6291 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006292 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006293 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006294
6295 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6296 Expr *CombRHS =
6297 (isOpenMPWorksharingDirective(DKind) ||
6298 isOpenMPTaskLoopDirective(DKind) ||
6299 isOpenMPDistributeDirective(DKind))
6300 ? CombLB.get()
6301 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
6302 CombInit =
6303 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006304 CombInit =
6305 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006306 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006307 }
6308
Alexey Bataev316ccf62019-01-29 18:51:58 +00006309 bool UseStrictCompare =
6310 RealVType->hasUnsignedIntegerRepresentation() &&
6311 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
6312 return LIS.IsStrictCompare;
6313 });
6314 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
6315 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006316 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00006317 Expr *BoundUB = UB.get();
6318 if (UseStrictCompare) {
6319 BoundUB =
6320 SemaRef
6321 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
6322 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6323 .get();
6324 BoundUB =
6325 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
6326 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006327 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006328 (isOpenMPWorksharingDirective(DKind) ||
6329 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00006330 ? SemaRef.BuildBinOp(CurScope, CondLoc,
6331 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
6332 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00006333 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6334 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006335 ExprResult CombDistCond;
6336 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006337 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6338 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006339 }
6340
Carlo Bertolliffafe102017-04-20 00:39:39 +00006341 ExprResult CombCond;
6342 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006343 Expr *BoundCombUB = CombUB.get();
6344 if (UseStrictCompare) {
6345 BoundCombUB =
6346 SemaRef
6347 .BuildBinOp(
6348 CurScope, CondLoc, BO_Add, BoundCombUB,
6349 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6350 .get();
6351 BoundCombUB =
6352 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
6353 .get();
6354 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00006355 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006356 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6357 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006358 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006359 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006360 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006361 ExprResult Inc =
6362 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
6363 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
6364 if (!Inc.isUsable())
6365 return 0;
6366 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006367 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006368 if (!Inc.isUsable())
6369 return 0;
6370
6371 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
6372 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006373 // In combined construct, add combined version that use CombLB and CombUB
6374 // base variables for the update
6375 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006376 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6377 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006378 // LB + ST
6379 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
6380 if (!NextLB.isUsable())
6381 return 0;
6382 // LB = LB + ST
6383 NextLB =
6384 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006385 NextLB =
6386 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006387 if (!NextLB.isUsable())
6388 return 0;
6389 // UB + ST
6390 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
6391 if (!NextUB.isUsable())
6392 return 0;
6393 // UB = UB + ST
6394 NextUB =
6395 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006396 NextUB =
6397 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006398 if (!NextUB.isUsable())
6399 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006400 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6401 CombNextLB =
6402 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
6403 if (!NextLB.isUsable())
6404 return 0;
6405 // LB = LB + ST
6406 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
6407 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006408 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
6409 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006410 if (!CombNextLB.isUsable())
6411 return 0;
6412 // UB + ST
6413 CombNextUB =
6414 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
6415 if (!CombNextUB.isUsable())
6416 return 0;
6417 // UB = UB + ST
6418 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
6419 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006420 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
6421 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006422 if (!CombNextUB.isUsable())
6423 return 0;
6424 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006425 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006426
Carlo Bertolliffafe102017-04-20 00:39:39 +00006427 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00006428 // directive with for as IV = IV + ST; ensure upper bound expression based
6429 // on PrevUB instead of NumIterations - used to implement 'for' when found
6430 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006431 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006432 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00006433 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006434 DistCond = SemaRef.BuildBinOp(
6435 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006436 assert(DistCond.isUsable() && "distribute cond expr was not built");
6437
6438 DistInc =
6439 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
6440 assert(DistInc.isUsable() && "distribute inc expr was not built");
6441 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
6442 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006443 DistInc =
6444 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006445 assert(DistInc.isUsable() && "distribute inc expr was not built");
6446
6447 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
6448 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006449 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006450 ExprResult IsUBGreater =
6451 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
6452 ExprResult CondOp = SemaRef.ActOnConditionalOp(
6453 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
6454 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
6455 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006456 PrevEUB =
6457 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006458
Alexey Bataev316ccf62019-01-29 18:51:58 +00006459 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
6460 // parallel for is in combination with a distribute directive with
6461 // schedule(static, 1)
6462 Expr *BoundPrevUB = PrevUB.get();
6463 if (UseStrictCompare) {
6464 BoundPrevUB =
6465 SemaRef
6466 .BuildBinOp(
6467 CurScope, CondLoc, BO_Add, BoundPrevUB,
6468 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6469 .get();
6470 BoundPrevUB =
6471 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
6472 .get();
6473 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006474 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006475 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6476 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006477 }
6478
Alexander Musmana5f070a2014-10-01 06:03:56 +00006479 // Build updates and final values of the loop counters.
6480 bool HasErrors = false;
6481 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006482 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006483 Built.Updates.resize(NestedLoopCount);
6484 Built.Finals.resize(NestedLoopCount);
6485 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006486 // We implement the following algorithm for obtaining the
6487 // original loop iteration variable values based on the
6488 // value of the collapsed loop iteration variable IV.
6489 //
6490 // Let n+1 be the number of collapsed loops in the nest.
6491 // Iteration variables (I0, I1, .... In)
6492 // Iteration counts (N0, N1, ... Nn)
6493 //
6494 // Acc = IV;
6495 //
6496 // To compute Ik for loop k, 0 <= k <= n, generate:
6497 // Prod = N(k+1) * N(k+2) * ... * Nn;
6498 // Ik = Acc / Prod;
6499 // Acc -= Ik * Prod;
6500 //
6501 ExprResult Acc = IV;
6502 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006503 LoopIterationSpace &IS = IterSpaces[Cnt];
6504 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006505 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006506
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006507 // Compute prod
6508 ExprResult Prod =
6509 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6510 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
6511 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
6512 IterSpaces[K].NumIterations);
6513
6514 // Iter = Acc / Prod
6515 // If there is at least one more inner loop to avoid
6516 // multiplication by 1.
6517 if (Cnt + 1 < NestedLoopCount)
6518 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
6519 Acc.get(), Prod.get());
6520 else
6521 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006522 if (!Iter.isUsable()) {
6523 HasErrors = true;
6524 break;
6525 }
6526
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006527 // Update Acc:
6528 // Acc -= Iter * Prod
6529 // Check if there is at least one more inner loop to avoid
6530 // multiplication by 1.
6531 if (Cnt + 1 < NestedLoopCount)
6532 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
6533 Iter.get(), Prod.get());
6534 else
6535 Prod = Iter;
6536 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
6537 Acc.get(), Prod.get());
6538
Alexey Bataev39f915b82015-05-08 10:41:21 +00006539 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006540 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00006541 DeclRefExpr *CounterVar = buildDeclRefExpr(
6542 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
6543 /*RefersToCapture=*/true);
6544 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006545 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006546 if (!Init.isUsable()) {
6547 HasErrors = true;
6548 break;
6549 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006550 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006551 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6552 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006553 if (!Update.isUsable()) {
6554 HasErrors = true;
6555 break;
6556 }
6557
6558 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006559 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00006560 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006561 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006562 if (!Final.isUsable()) {
6563 HasErrors = true;
6564 break;
6565 }
6566
Alexander Musmana5f070a2014-10-01 06:03:56 +00006567 if (!Update.isUsable() || !Final.isUsable()) {
6568 HasErrors = true;
6569 break;
6570 }
6571 // Save results
6572 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006573 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006574 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006575 Built.Updates[Cnt] = Update.get();
6576 Built.Finals[Cnt] = Final.get();
6577 }
6578 }
6579
6580 if (HasErrors)
6581 return 0;
6582
6583 // Save results
6584 Built.IterationVarRef = IV.get();
6585 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006586 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006587 Built.CalcLastIteration = SemaRef
6588 .ActOnFinishFullExpr(CalcLastIteration.get(),
6589 /*DiscardedValue*/ false)
6590 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006591 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006592 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006593 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006594 Built.Init = Init.get();
6595 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006596 Built.LB = LB.get();
6597 Built.UB = UB.get();
6598 Built.IL = IL.get();
6599 Built.ST = ST.get();
6600 Built.EUB = EUB.get();
6601 Built.NLB = NextLB.get();
6602 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006603 Built.PrevLB = PrevLB.get();
6604 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006605 Built.DistInc = DistInc.get();
6606 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006607 Built.DistCombinedFields.LB = CombLB.get();
6608 Built.DistCombinedFields.UB = CombUB.get();
6609 Built.DistCombinedFields.EUB = CombEUB.get();
6610 Built.DistCombinedFields.Init = CombInit.get();
6611 Built.DistCombinedFields.Cond = CombCond.get();
6612 Built.DistCombinedFields.NLB = CombNextLB.get();
6613 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006614 Built.DistCombinedFields.DistCond = CombDistCond.get();
6615 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006616
Alexey Bataevabfc0692014-06-25 06:52:00 +00006617 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006618}
6619
Alexey Bataev10e775f2015-07-30 11:36:16 +00006620static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006621 auto CollapseClauses =
6622 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6623 if (CollapseClauses.begin() != CollapseClauses.end())
6624 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006625 return nullptr;
6626}
6627
Alexey Bataev10e775f2015-07-30 11:36:16 +00006628static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006629 auto OrderedClauses =
6630 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6631 if (OrderedClauses.begin() != OrderedClauses.end())
6632 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006633 return nullptr;
6634}
6635
Kelvin Lic5609492016-07-15 04:39:07 +00006636static bool checkSimdlenSafelenSpecified(Sema &S,
6637 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006638 const OMPSafelenClause *Safelen = nullptr;
6639 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006640
Alexey Bataeve3727102018-04-18 15:57:46 +00006641 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006642 if (Clause->getClauseKind() == OMPC_safelen)
6643 Safelen = cast<OMPSafelenClause>(Clause);
6644 else if (Clause->getClauseKind() == OMPC_simdlen)
6645 Simdlen = cast<OMPSimdlenClause>(Clause);
6646 if (Safelen && Simdlen)
6647 break;
6648 }
6649
6650 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006651 const Expr *SimdlenLength = Simdlen->getSimdlen();
6652 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006653 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6654 SimdlenLength->isInstantiationDependent() ||
6655 SimdlenLength->containsUnexpandedParameterPack())
6656 return false;
6657 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6658 SafelenLength->isInstantiationDependent() ||
6659 SafelenLength->containsUnexpandedParameterPack())
6660 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006661 Expr::EvalResult SimdlenResult, SafelenResult;
6662 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6663 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6664 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6665 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006666 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6667 // If both simdlen and safelen clauses are specified, the value of the
6668 // simdlen parameter must be less than or equal to the value of the safelen
6669 // parameter.
6670 if (SimdlenRes > SafelenRes) {
6671 S.Diag(SimdlenLength->getExprLoc(),
6672 diag::err_omp_wrong_simdlen_safelen_values)
6673 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6674 return true;
6675 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006676 }
6677 return false;
6678}
6679
Alexey Bataeve3727102018-04-18 15:57:46 +00006680StmtResult
6681Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6682 SourceLocation StartLoc, SourceLocation EndLoc,
6683 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006684 if (!AStmt)
6685 return StmtError();
6686
6687 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006688 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006689 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6690 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006691 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006692 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6693 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006694 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006695 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006696
Alexander Musmana5f070a2014-10-01 06:03:56 +00006697 assert((CurContext->isDependentContext() || B.builtAll()) &&
6698 "omp simd loop exprs were not built");
6699
Alexander Musman3276a272015-03-21 10:12:56 +00006700 if (!CurContext->isDependentContext()) {
6701 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006702 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006703 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006704 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006705 B.NumIterations, *this, CurScope,
6706 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006707 return StmtError();
6708 }
6709 }
6710
Kelvin Lic5609492016-07-15 04:39:07 +00006711 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006712 return StmtError();
6713
Reid Kleckner87a31802018-03-12 21:43:02 +00006714 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006715 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6716 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006717}
6718
Alexey Bataeve3727102018-04-18 15:57:46 +00006719StmtResult
6720Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6721 SourceLocation StartLoc, SourceLocation EndLoc,
6722 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006723 if (!AStmt)
6724 return StmtError();
6725
6726 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006727 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006728 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6729 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006730 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006731 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6732 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006733 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006734 return StmtError();
6735
Alexander Musmana5f070a2014-10-01 06:03:56 +00006736 assert((CurContext->isDependentContext() || B.builtAll()) &&
6737 "omp for loop exprs were not built");
6738
Alexey Bataev54acd402015-08-04 11:18:19 +00006739 if (!CurContext->isDependentContext()) {
6740 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006741 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006742 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006743 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006744 B.NumIterations, *this, CurScope,
6745 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006746 return StmtError();
6747 }
6748 }
6749
Reid Kleckner87a31802018-03-12 21:43:02 +00006750 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006751 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006752 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006753}
6754
Alexander Musmanf82886e2014-09-18 05:12:34 +00006755StmtResult Sema::ActOnOpenMPForSimdDirective(
6756 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006757 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006758 if (!AStmt)
6759 return StmtError();
6760
6761 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006762 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006763 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6764 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006765 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006766 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006767 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6768 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006769 if (NestedLoopCount == 0)
6770 return StmtError();
6771
Alexander Musmanc6388682014-12-15 07:07:06 +00006772 assert((CurContext->isDependentContext() || B.builtAll()) &&
6773 "omp for simd loop exprs were not built");
6774
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006775 if (!CurContext->isDependentContext()) {
6776 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006777 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006778 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006779 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006780 B.NumIterations, *this, CurScope,
6781 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006782 return StmtError();
6783 }
6784 }
6785
Kelvin Lic5609492016-07-15 04:39:07 +00006786 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006787 return StmtError();
6788
Reid Kleckner87a31802018-03-12 21:43:02 +00006789 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006790 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6791 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006792}
6793
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006794StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6795 Stmt *AStmt,
6796 SourceLocation StartLoc,
6797 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006798 if (!AStmt)
6799 return StmtError();
6800
6801 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006802 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006803 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006804 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006805 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006806 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006807 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006808 return StmtError();
6809 // All associated statements must be '#pragma omp section' except for
6810 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006811 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006812 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6813 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006814 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006815 diag::err_omp_sections_substmt_not_section);
6816 return StmtError();
6817 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006818 cast<OMPSectionDirective>(SectionStmt)
6819 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006820 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006821 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006822 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006823 return StmtError();
6824 }
6825
Reid Kleckner87a31802018-03-12 21:43:02 +00006826 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006827
Alexey Bataev25e5b442015-09-15 12:52:43 +00006828 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6829 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006830}
6831
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006832StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6833 SourceLocation StartLoc,
6834 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006835 if (!AStmt)
6836 return StmtError();
6837
6838 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006839
Reid Kleckner87a31802018-03-12 21:43:02 +00006840 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006841 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006842
Alexey Bataev25e5b442015-09-15 12:52:43 +00006843 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6844 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006845}
6846
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006847StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6848 Stmt *AStmt,
6849 SourceLocation StartLoc,
6850 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006851 if (!AStmt)
6852 return StmtError();
6853
6854 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006855
Reid Kleckner87a31802018-03-12 21:43:02 +00006856 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006857
Alexey Bataev3255bf32015-01-19 05:20:46 +00006858 // OpenMP [2.7.3, single Construct, Restrictions]
6859 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006860 const OMPClause *Nowait = nullptr;
6861 const OMPClause *Copyprivate = nullptr;
6862 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006863 if (Clause->getClauseKind() == OMPC_nowait)
6864 Nowait = Clause;
6865 else if (Clause->getClauseKind() == OMPC_copyprivate)
6866 Copyprivate = Clause;
6867 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006868 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006869 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006870 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006871 return StmtError();
6872 }
6873 }
6874
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006875 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6876}
6877
Alexander Musman80c22892014-07-17 08:54:58 +00006878StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6879 SourceLocation StartLoc,
6880 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006881 if (!AStmt)
6882 return StmtError();
6883
6884 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006885
Reid Kleckner87a31802018-03-12 21:43:02 +00006886 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006887
6888 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6889}
6890
Alexey Bataev28c75412015-12-15 08:19:24 +00006891StmtResult Sema::ActOnOpenMPCriticalDirective(
6892 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6893 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006894 if (!AStmt)
6895 return StmtError();
6896
6897 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006898
Alexey Bataev28c75412015-12-15 08:19:24 +00006899 bool ErrorFound = false;
6900 llvm::APSInt Hint;
6901 SourceLocation HintLoc;
6902 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006903 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006904 if (C->getClauseKind() == OMPC_hint) {
6905 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006906 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006907 ErrorFound = true;
6908 }
6909 Expr *E = cast<OMPHintClause>(C)->getHint();
6910 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006911 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006912 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006913 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006914 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006915 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006916 }
6917 }
6918 }
6919 if (ErrorFound)
6920 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006921 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006922 if (Pair.first && DirName.getName() && !DependentHint) {
6923 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6924 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006925 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006926 Diag(HintLoc, diag::note_omp_critical_hint_here)
6927 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006928 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006929 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006930 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006931 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006932 << 1
6933 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6934 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006935 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006936 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006937 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006938 }
6939 }
6940
Reid Kleckner87a31802018-03-12 21:43:02 +00006941 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006942
Alexey Bataev28c75412015-12-15 08:19:24 +00006943 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6944 Clauses, AStmt);
6945 if (!Pair.first && DirName.getName() && !DependentHint)
6946 DSAStack->addCriticalWithHint(Dir, Hint);
6947 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006948}
6949
Alexey Bataev4acb8592014-07-07 13:01:15 +00006950StmtResult Sema::ActOnOpenMPParallelForDirective(
6951 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006952 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006953 if (!AStmt)
6954 return StmtError();
6955
Alexey Bataeve3727102018-04-18 15:57:46 +00006956 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006957 // 1.2.2 OpenMP Language Terminology
6958 // Structured block - An executable statement with a single entry at the
6959 // top and a single exit at the bottom.
6960 // The point of exit cannot be a branch out of the structured block.
6961 // longjmp() and throw() must not violate the entry/exit criteria.
6962 CS->getCapturedDecl()->setNothrow();
6963
Alexander Musmanc6388682014-12-15 07:07:06 +00006964 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006965 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6966 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006967 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006968 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006969 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6970 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006971 if (NestedLoopCount == 0)
6972 return StmtError();
6973
Alexander Musmana5f070a2014-10-01 06:03:56 +00006974 assert((CurContext->isDependentContext() || B.builtAll()) &&
6975 "omp parallel for loop exprs were not built");
6976
Alexey Bataev54acd402015-08-04 11:18:19 +00006977 if (!CurContext->isDependentContext()) {
6978 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006979 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006980 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006981 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006982 B.NumIterations, *this, CurScope,
6983 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006984 return StmtError();
6985 }
6986 }
6987
Reid Kleckner87a31802018-03-12 21:43:02 +00006988 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006989 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006990 NestedLoopCount, Clauses, AStmt, B,
6991 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006992}
6993
Alexander Musmane4e893b2014-09-23 09:33:00 +00006994StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6995 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006996 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006997 if (!AStmt)
6998 return StmtError();
6999
Alexey Bataeve3727102018-04-18 15:57:46 +00007000 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007001 // 1.2.2 OpenMP Language Terminology
7002 // Structured block - An executable statement with a single entry at the
7003 // top and a single exit at the bottom.
7004 // The point of exit cannot be a branch out of the structured block.
7005 // longjmp() and throw() must not violate the entry/exit criteria.
7006 CS->getCapturedDecl()->setNothrow();
7007
Alexander Musmanc6388682014-12-15 07:07:06 +00007008 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007009 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7010 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007011 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007012 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007013 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7014 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007015 if (NestedLoopCount == 0)
7016 return StmtError();
7017
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007018 if (!CurContext->isDependentContext()) {
7019 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007020 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007021 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007022 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007023 B.NumIterations, *this, CurScope,
7024 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007025 return StmtError();
7026 }
7027 }
7028
Kelvin Lic5609492016-07-15 04:39:07 +00007029 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007030 return StmtError();
7031
Reid Kleckner87a31802018-03-12 21:43:02 +00007032 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007033 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007034 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007035}
7036
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007037StmtResult
7038Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7039 Stmt *AStmt, SourceLocation StartLoc,
7040 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007041 if (!AStmt)
7042 return StmtError();
7043
7044 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007045 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007046 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007047 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007048 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007049 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007050 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007051 return StmtError();
7052 // All associated statements must be '#pragma omp section' except for
7053 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007054 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007055 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7056 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007057 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007058 diag::err_omp_parallel_sections_substmt_not_section);
7059 return StmtError();
7060 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007061 cast<OMPSectionDirective>(SectionStmt)
7062 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007063 }
7064 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007065 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007066 diag::err_omp_parallel_sections_not_compound_stmt);
7067 return StmtError();
7068 }
7069
Reid Kleckner87a31802018-03-12 21:43:02 +00007070 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007071
Alexey Bataev25e5b442015-09-15 12:52:43 +00007072 return OMPParallelSectionsDirective::Create(
7073 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007074}
7075
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007076StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7077 Stmt *AStmt, SourceLocation StartLoc,
7078 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007079 if (!AStmt)
7080 return StmtError();
7081
David Majnemer9d168222016-08-05 17:44:54 +00007082 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007083 // 1.2.2 OpenMP Language Terminology
7084 // Structured block - An executable statement with a single entry at the
7085 // top and a single exit at the bottom.
7086 // The point of exit cannot be a branch out of the structured block.
7087 // longjmp() and throw() must not violate the entry/exit criteria.
7088 CS->getCapturedDecl()->setNothrow();
7089
Reid Kleckner87a31802018-03-12 21:43:02 +00007090 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007091
Alexey Bataev25e5b442015-09-15 12:52:43 +00007092 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7093 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007094}
7095
Alexey Bataev68446b72014-07-18 07:47:19 +00007096StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7097 SourceLocation EndLoc) {
7098 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
7099}
7100
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00007101StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7102 SourceLocation EndLoc) {
7103 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
7104}
7105
Alexey Bataev2df347a2014-07-18 10:17:07 +00007106StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7107 SourceLocation EndLoc) {
7108 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
7109}
7110
Alexey Bataev169d96a2017-07-18 20:17:46 +00007111StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
7112 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007113 SourceLocation StartLoc,
7114 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007115 if (!AStmt)
7116 return StmtError();
7117
7118 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007119
Reid Kleckner87a31802018-03-12 21:43:02 +00007120 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007121
Alexey Bataev169d96a2017-07-18 20:17:46 +00007122 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00007123 AStmt,
7124 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007125}
7126
Alexey Bataev6125da92014-07-21 11:26:11 +00007127StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7128 SourceLocation StartLoc,
7129 SourceLocation EndLoc) {
7130 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
7131 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
7132}
7133
Alexey Bataev346265e2015-09-25 10:37:12 +00007134StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7135 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007136 SourceLocation StartLoc,
7137 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007138 const OMPClause *DependFound = nullptr;
7139 const OMPClause *DependSourceClause = nullptr;
7140 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00007141 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007142 const OMPThreadsClause *TC = nullptr;
7143 const OMPSIMDClause *SC = nullptr;
7144 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00007145 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
7146 DependFound = C;
7147 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
7148 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007149 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00007150 << getOpenMPDirectiveName(OMPD_ordered)
7151 << getOpenMPClauseName(OMPC_depend) << 2;
7152 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007153 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00007154 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00007155 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007156 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007157 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007158 << 0;
7159 ErrorFound = true;
7160 }
7161 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
7162 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007163 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007164 << 1;
7165 ErrorFound = true;
7166 }
7167 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00007168 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007169 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00007170 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007171 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007172 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007173 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007174 }
Alexey Bataeveb482352015-12-18 05:05:56 +00007175 if (!ErrorFound && !SC &&
7176 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007177 // OpenMP [2.8.1,simd Construct, Restrictions]
7178 // An ordered construct with the simd clause is the only OpenMP construct
7179 // that can appear in the simd region.
7180 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00007181 ErrorFound = true;
7182 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007183 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00007184 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
7185 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007186 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007187 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00007188 diag::err_omp_ordered_directive_without_param);
7189 ErrorFound = true;
7190 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007191 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007192 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00007193 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
7194 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007195 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00007196 ErrorFound = true;
7197 }
7198 }
7199 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007200 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00007201
7202 if (AStmt) {
7203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7204
Reid Kleckner87a31802018-03-12 21:43:02 +00007205 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007206 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007207
7208 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007209}
7210
Alexey Bataev1d160b12015-03-13 12:27:31 +00007211namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007212/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007213/// construct.
7214class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007215 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007216 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007217 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007218 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007219 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007220 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007221 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007222 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007223 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007224 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007225 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007226 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007227 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007228 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007229 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00007230 /// expression.
7231 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007232 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00007233 /// part.
7234 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007235 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007236 NoError
7237 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007238 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007239 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007240 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00007241 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007242 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007243 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007244 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007245 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007246 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00007247 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7248 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7249 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007250 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00007251 /// important for non-associative operations.
7252 bool IsXLHSInRHSPart;
7253 BinaryOperatorKind Op;
7254 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007255 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007256 /// if it is a prefix unary operation.
7257 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007258
7259public:
7260 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00007261 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00007262 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007263 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007264 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00007265 /// expression. If DiagId and NoteId == 0, then only check is performed
7266 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007267 /// \param DiagId Diagnostic which should be emitted if error is found.
7268 /// \param NoteId Diagnostic note for the main error message.
7269 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00007270 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007271 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007272 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007273 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007274 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007275 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00007276 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7277 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7278 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007279 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00007280 /// false otherwise.
7281 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
7282
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007283 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007284 /// if it is a prefix unary operation.
7285 bool isPostfixUpdate() const { return IsPostfixUpdate; }
7286
Alexey Bataev1d160b12015-03-13 12:27:31 +00007287private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00007288 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
7289 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00007290};
7291} // namespace
7292
7293bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
7294 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
7295 ExprAnalysisErrorCode ErrorFound = NoError;
7296 SourceLocation ErrorLoc, NoteLoc;
7297 SourceRange ErrorRange, NoteRange;
7298 // Allowed constructs are:
7299 // x = x binop expr;
7300 // x = expr binop x;
7301 if (AtomicBinOp->getOpcode() == BO_Assign) {
7302 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00007303 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007304 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
7305 if (AtomicInnerBinOp->isMultiplicativeOp() ||
7306 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
7307 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007308 Op = AtomicInnerBinOp->getOpcode();
7309 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00007310 Expr *LHS = AtomicInnerBinOp->getLHS();
7311 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007312 llvm::FoldingSetNodeID XId, LHSId, RHSId;
7313 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
7314 /*Canonical=*/true);
7315 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
7316 /*Canonical=*/true);
7317 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
7318 /*Canonical=*/true);
7319 if (XId == LHSId) {
7320 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007321 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007322 } else if (XId == RHSId) {
7323 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007324 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007325 } else {
7326 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7327 ErrorRange = AtomicInnerBinOp->getSourceRange();
7328 NoteLoc = X->getExprLoc();
7329 NoteRange = X->getSourceRange();
7330 ErrorFound = NotAnUpdateExpression;
7331 }
7332 } else {
7333 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7334 ErrorRange = AtomicInnerBinOp->getSourceRange();
7335 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
7336 NoteRange = SourceRange(NoteLoc, NoteLoc);
7337 ErrorFound = NotABinaryOperator;
7338 }
7339 } else {
7340 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
7341 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
7342 ErrorFound = NotABinaryExpression;
7343 }
7344 } else {
7345 ErrorLoc = AtomicBinOp->getExprLoc();
7346 ErrorRange = AtomicBinOp->getSourceRange();
7347 NoteLoc = AtomicBinOp->getOperatorLoc();
7348 NoteRange = SourceRange(NoteLoc, NoteLoc);
7349 ErrorFound = NotAnAssignmentOp;
7350 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007351 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007352 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7353 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7354 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007355 }
7356 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007357 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007358 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007359}
7360
7361bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
7362 unsigned NoteId) {
7363 ExprAnalysisErrorCode ErrorFound = NoError;
7364 SourceLocation ErrorLoc, NoteLoc;
7365 SourceRange ErrorRange, NoteRange;
7366 // Allowed constructs are:
7367 // x++;
7368 // x--;
7369 // ++x;
7370 // --x;
7371 // x binop= expr;
7372 // x = x binop expr;
7373 // x = expr binop x;
7374 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
7375 AtomicBody = AtomicBody->IgnoreParenImpCasts();
7376 if (AtomicBody->getType()->isScalarType() ||
7377 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007378 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007379 AtomicBody->IgnoreParenImpCasts())) {
7380 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00007381 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007382 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00007383 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007384 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007385 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007386 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007387 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
7388 AtomicBody->IgnoreParenImpCasts())) {
7389 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00007390 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00007391 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007392 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00007393 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007394 // Check for Unary Operation
7395 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007396 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007397 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
7398 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007399 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007400 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
7401 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007402 } else {
7403 ErrorFound = NotAnUnaryIncDecExpression;
7404 ErrorLoc = AtomicUnaryOp->getExprLoc();
7405 ErrorRange = AtomicUnaryOp->getSourceRange();
7406 NoteLoc = AtomicUnaryOp->getOperatorLoc();
7407 NoteRange = SourceRange(NoteLoc, NoteLoc);
7408 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007409 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007410 ErrorFound = NotABinaryOrUnaryExpression;
7411 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
7412 NoteRange = ErrorRange = AtomicBody->getSourceRange();
7413 }
7414 } else {
7415 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007416 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007417 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7418 }
7419 } else {
7420 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007421 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007422 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7423 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007424 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007425 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7426 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7427 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007428 }
7429 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007430 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007431 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007432 // Build an update expression of form 'OpaqueValueExpr(x) binop
7433 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
7434 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
7435 auto *OVEX = new (SemaRef.getASTContext())
7436 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
7437 auto *OVEExpr = new (SemaRef.getASTContext())
7438 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00007439 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00007440 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
7441 IsXLHSInRHSPart ? OVEExpr : OVEX);
7442 if (Update.isInvalid())
7443 return true;
7444 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
7445 Sema::AA_Casting);
7446 if (Update.isInvalid())
7447 return true;
7448 UpdateExpr = Update.get();
7449 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00007450 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007451}
7452
Alexey Bataev0162e452014-07-22 10:10:35 +00007453StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7454 Stmt *AStmt,
7455 SourceLocation StartLoc,
7456 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007457 if (!AStmt)
7458 return StmtError();
7459
David Majnemer9d168222016-08-05 17:44:54 +00007460 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00007461 // 1.2.2 OpenMP Language Terminology
7462 // Structured block - An executable statement with a single entry at the
7463 // top and a single exit at the bottom.
7464 // The point of exit cannot be a branch out of the structured block.
7465 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00007466 OpenMPClauseKind AtomicKind = OMPC_unknown;
7467 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00007468 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00007469 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00007470 C->getClauseKind() == OMPC_update ||
7471 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00007472 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007473 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007474 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00007475 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
7476 << getOpenMPClauseName(AtomicKind);
7477 } else {
7478 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007479 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007480 }
7481 }
7482 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007483
Alexey Bataeve3727102018-04-18 15:57:46 +00007484 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00007485 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
7486 Body = EWC->getSubExpr();
7487
Alexey Bataev62cec442014-11-18 10:14:22 +00007488 Expr *X = nullptr;
7489 Expr *V = nullptr;
7490 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007491 Expr *UE = nullptr;
7492 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007493 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00007494 // OpenMP [2.12.6, atomic Construct]
7495 // In the next expressions:
7496 // * x and v (as applicable) are both l-value expressions with scalar type.
7497 // * During the execution of an atomic region, multiple syntactic
7498 // occurrences of x must designate the same storage location.
7499 // * Neither of v and expr (as applicable) may access the storage location
7500 // designated by x.
7501 // * Neither of x and expr (as applicable) may access the storage location
7502 // designated by v.
7503 // * expr is an expression with scalar type.
7504 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
7505 // * binop, binop=, ++, and -- are not overloaded operators.
7506 // * The expression x binop expr must be numerically equivalent to x binop
7507 // (expr). This requirement is satisfied if the operators in expr have
7508 // precedence greater than binop, or by using parentheses around expr or
7509 // subexpressions of expr.
7510 // * The expression expr binop x must be numerically equivalent to (expr)
7511 // binop x. This requirement is satisfied if the operators in expr have
7512 // precedence equal to or greater than binop, or by using parentheses around
7513 // expr or subexpressions of expr.
7514 // * For forms that allow multiple occurrences of x, the number of times
7515 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00007516 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007517 enum {
7518 NotAnExpression,
7519 NotAnAssignmentOp,
7520 NotAScalarType,
7521 NotAnLValue,
7522 NoError
7523 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00007524 SourceLocation ErrorLoc, NoteLoc;
7525 SourceRange ErrorRange, NoteRange;
7526 // If clause is read:
7527 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007528 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7529 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00007530 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7531 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7532 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7533 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
7534 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7535 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
7536 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007537 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00007538 ErrorFound = NotAnLValue;
7539 ErrorLoc = AtomicBinOp->getExprLoc();
7540 ErrorRange = AtomicBinOp->getSourceRange();
7541 NoteLoc = NotLValueExpr->getExprLoc();
7542 NoteRange = NotLValueExpr->getSourceRange();
7543 }
7544 } else if (!X->isInstantiationDependent() ||
7545 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007546 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00007547 (X->isInstantiationDependent() || X->getType()->isScalarType())
7548 ? V
7549 : X;
7550 ErrorFound = NotAScalarType;
7551 ErrorLoc = AtomicBinOp->getExprLoc();
7552 ErrorRange = AtomicBinOp->getSourceRange();
7553 NoteLoc = NotScalarExpr->getExprLoc();
7554 NoteRange = NotScalarExpr->getSourceRange();
7555 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007556 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00007557 ErrorFound = NotAnAssignmentOp;
7558 ErrorLoc = AtomicBody->getExprLoc();
7559 ErrorRange = AtomicBody->getSourceRange();
7560 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7561 : AtomicBody->getExprLoc();
7562 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7563 : AtomicBody->getSourceRange();
7564 }
7565 } else {
7566 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007567 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007568 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007569 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007570 if (ErrorFound != NoError) {
7571 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7572 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007573 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7574 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007575 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007576 }
7577 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007578 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007579 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007580 enum {
7581 NotAnExpression,
7582 NotAnAssignmentOp,
7583 NotAScalarType,
7584 NotAnLValue,
7585 NoError
7586 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007587 SourceLocation ErrorLoc, NoteLoc;
7588 SourceRange ErrorRange, NoteRange;
7589 // If clause is write:
7590 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007591 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7592 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007593 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7594 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007595 X = AtomicBinOp->getLHS();
7596 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007597 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7598 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7599 if (!X->isLValue()) {
7600 ErrorFound = NotAnLValue;
7601 ErrorLoc = AtomicBinOp->getExprLoc();
7602 ErrorRange = AtomicBinOp->getSourceRange();
7603 NoteLoc = X->getExprLoc();
7604 NoteRange = X->getSourceRange();
7605 }
7606 } else if (!X->isInstantiationDependent() ||
7607 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007608 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007609 (X->isInstantiationDependent() || X->getType()->isScalarType())
7610 ? E
7611 : X;
7612 ErrorFound = NotAScalarType;
7613 ErrorLoc = AtomicBinOp->getExprLoc();
7614 ErrorRange = AtomicBinOp->getSourceRange();
7615 NoteLoc = NotScalarExpr->getExprLoc();
7616 NoteRange = NotScalarExpr->getSourceRange();
7617 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007618 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007619 ErrorFound = NotAnAssignmentOp;
7620 ErrorLoc = AtomicBody->getExprLoc();
7621 ErrorRange = AtomicBody->getSourceRange();
7622 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7623 : AtomicBody->getExprLoc();
7624 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7625 : AtomicBody->getSourceRange();
7626 }
7627 } else {
7628 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007629 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007630 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007631 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007632 if (ErrorFound != NoError) {
7633 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7634 << ErrorRange;
7635 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7636 << NoteRange;
7637 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007638 }
7639 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007640 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007641 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007642 // If clause is update:
7643 // x++;
7644 // x--;
7645 // ++x;
7646 // --x;
7647 // x binop= expr;
7648 // x = x binop expr;
7649 // x = expr binop x;
7650 OpenMPAtomicUpdateChecker Checker(*this);
7651 if (Checker.checkStatement(
7652 Body, (AtomicKind == OMPC_update)
7653 ? diag::err_omp_atomic_update_not_expression_statement
7654 : diag::err_omp_atomic_not_expression_statement,
7655 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007656 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007657 if (!CurContext->isDependentContext()) {
7658 E = Checker.getExpr();
7659 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007660 UE = Checker.getUpdateExpr();
7661 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007662 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007663 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007664 enum {
7665 NotAnAssignmentOp,
7666 NotACompoundStatement,
7667 NotTwoSubstatements,
7668 NotASpecificExpression,
7669 NoError
7670 } ErrorFound = NoError;
7671 SourceLocation ErrorLoc, NoteLoc;
7672 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007673 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007674 // If clause is a capture:
7675 // v = x++;
7676 // v = x--;
7677 // v = ++x;
7678 // v = --x;
7679 // v = x binop= expr;
7680 // v = x = x binop expr;
7681 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007682 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007683 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7684 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7685 V = AtomicBinOp->getLHS();
7686 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7687 OpenMPAtomicUpdateChecker Checker(*this);
7688 if (Checker.checkStatement(
7689 Body, diag::err_omp_atomic_capture_not_expression_statement,
7690 diag::note_omp_atomic_update))
7691 return StmtError();
7692 E = Checker.getExpr();
7693 X = Checker.getX();
7694 UE = Checker.getUpdateExpr();
7695 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7696 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007697 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007698 ErrorLoc = AtomicBody->getExprLoc();
7699 ErrorRange = AtomicBody->getSourceRange();
7700 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7701 : AtomicBody->getExprLoc();
7702 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7703 : AtomicBody->getSourceRange();
7704 ErrorFound = NotAnAssignmentOp;
7705 }
7706 if (ErrorFound != NoError) {
7707 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7708 << ErrorRange;
7709 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7710 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007711 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007712 if (CurContext->isDependentContext())
7713 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007714 } else {
7715 // If clause is a capture:
7716 // { v = x; x = expr; }
7717 // { v = x; x++; }
7718 // { v = x; x--; }
7719 // { v = x; ++x; }
7720 // { v = x; --x; }
7721 // { v = x; x binop= expr; }
7722 // { v = x; x = x binop expr; }
7723 // { v = x; x = expr binop x; }
7724 // { x++; v = x; }
7725 // { x--; v = x; }
7726 // { ++x; v = x; }
7727 // { --x; v = x; }
7728 // { x binop= expr; v = x; }
7729 // { x = x binop expr; v = x; }
7730 // { x = expr binop x; v = x; }
7731 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7732 // Check that this is { expr1; expr2; }
7733 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007734 Stmt *First = CS->body_front();
7735 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007736 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7737 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7738 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7739 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7740 // Need to find what subexpression is 'v' and what is 'x'.
7741 OpenMPAtomicUpdateChecker Checker(*this);
7742 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7743 BinaryOperator *BinOp = nullptr;
7744 if (IsUpdateExprFound) {
7745 BinOp = dyn_cast<BinaryOperator>(First);
7746 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7747 }
7748 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7749 // { v = x; x++; }
7750 // { v = x; x--; }
7751 // { v = x; ++x; }
7752 // { v = x; --x; }
7753 // { v = x; x binop= expr; }
7754 // { v = x; x = x binop expr; }
7755 // { v = x; x = expr binop x; }
7756 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007757 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007758 llvm::FoldingSetNodeID XId, PossibleXId;
7759 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7760 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7761 IsUpdateExprFound = XId == PossibleXId;
7762 if (IsUpdateExprFound) {
7763 V = BinOp->getLHS();
7764 X = Checker.getX();
7765 E = Checker.getExpr();
7766 UE = Checker.getUpdateExpr();
7767 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007768 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007769 }
7770 }
7771 if (!IsUpdateExprFound) {
7772 IsUpdateExprFound = !Checker.checkStatement(First);
7773 BinOp = nullptr;
7774 if (IsUpdateExprFound) {
7775 BinOp = dyn_cast<BinaryOperator>(Second);
7776 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7777 }
7778 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7779 // { x++; v = x; }
7780 // { x--; v = x; }
7781 // { ++x; v = x; }
7782 // { --x; v = x; }
7783 // { x binop= expr; v = x; }
7784 // { x = x binop expr; v = x; }
7785 // { x = expr binop x; v = x; }
7786 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007787 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007788 llvm::FoldingSetNodeID XId, PossibleXId;
7789 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7790 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7791 IsUpdateExprFound = XId == PossibleXId;
7792 if (IsUpdateExprFound) {
7793 V = BinOp->getLHS();
7794 X = Checker.getX();
7795 E = Checker.getExpr();
7796 UE = Checker.getUpdateExpr();
7797 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007798 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007799 }
7800 }
7801 }
7802 if (!IsUpdateExprFound) {
7803 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007804 auto *FirstExpr = dyn_cast<Expr>(First);
7805 auto *SecondExpr = dyn_cast<Expr>(Second);
7806 if (!FirstExpr || !SecondExpr ||
7807 !(FirstExpr->isInstantiationDependent() ||
7808 SecondExpr->isInstantiationDependent())) {
7809 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7810 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007811 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007812 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007813 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007814 NoteRange = ErrorRange = FirstBinOp
7815 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007816 : SourceRange(ErrorLoc, ErrorLoc);
7817 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007818 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7819 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7820 ErrorFound = NotAnAssignmentOp;
7821 NoteLoc = ErrorLoc = SecondBinOp
7822 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007823 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007824 NoteRange = ErrorRange =
7825 SecondBinOp ? SecondBinOp->getSourceRange()
7826 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007827 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007828 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007829 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007830 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007831 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7832 llvm::FoldingSetNodeID X1Id, X2Id;
7833 PossibleXRHSInFirst->Profile(X1Id, Context,
7834 /*Canonical=*/true);
7835 PossibleXLHSInSecond->Profile(X2Id, Context,
7836 /*Canonical=*/true);
7837 IsUpdateExprFound = X1Id == X2Id;
7838 if (IsUpdateExprFound) {
7839 V = FirstBinOp->getLHS();
7840 X = SecondBinOp->getLHS();
7841 E = SecondBinOp->getRHS();
7842 UE = nullptr;
7843 IsXLHSInRHSPart = false;
7844 IsPostfixUpdate = true;
7845 } else {
7846 ErrorFound = NotASpecificExpression;
7847 ErrorLoc = FirstBinOp->getExprLoc();
7848 ErrorRange = FirstBinOp->getSourceRange();
7849 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7850 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7851 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007852 }
7853 }
7854 }
7855 }
7856 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007857 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007858 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007859 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007860 ErrorFound = NotTwoSubstatements;
7861 }
7862 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007863 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007864 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007865 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007866 ErrorFound = NotACompoundStatement;
7867 }
7868 if (ErrorFound != NoError) {
7869 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7870 << ErrorRange;
7871 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7872 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007873 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007874 if (CurContext->isDependentContext())
7875 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007876 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007877 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007878
Reid Kleckner87a31802018-03-12 21:43:02 +00007879 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007880
Alexey Bataev62cec442014-11-18 10:14:22 +00007881 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007882 X, V, E, UE, IsXLHSInRHSPart,
7883 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007884}
7885
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007886StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7887 Stmt *AStmt,
7888 SourceLocation StartLoc,
7889 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007890 if (!AStmt)
7891 return StmtError();
7892
Alexey Bataeve3727102018-04-18 15:57:46 +00007893 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007894 // 1.2.2 OpenMP Language Terminology
7895 // Structured block - An executable statement with a single entry at the
7896 // top and a single exit at the bottom.
7897 // The point of exit cannot be a branch out of the structured block.
7898 // longjmp() and throw() must not violate the entry/exit criteria.
7899 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007900 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7901 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7902 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7903 // 1.2.2 OpenMP Language Terminology
7904 // Structured block - An executable statement with a single entry at the
7905 // top and a single exit at the bottom.
7906 // The point of exit cannot be a branch out of the structured block.
7907 // longjmp() and throw() must not violate the entry/exit criteria.
7908 CS->getCapturedDecl()->setNothrow();
7909 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007910
Alexey Bataev13314bf2014-10-09 04:18:56 +00007911 // OpenMP [2.16, Nesting of Regions]
7912 // If specified, a teams construct must be contained within a target
7913 // construct. That target construct must contain no statements or directives
7914 // outside of the teams construct.
7915 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007916 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007917 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007918 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007919 auto I = CS->body_begin();
7920 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007921 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007922 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7923 OMPTeamsFound) {
7924
Alexey Bataev13314bf2014-10-09 04:18:56 +00007925 OMPTeamsFound = false;
7926 break;
7927 }
7928 ++I;
7929 }
7930 assert(I != CS->body_end() && "Not found statement");
7931 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007932 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007933 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007934 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007935 }
7936 if (!OMPTeamsFound) {
7937 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7938 Diag(DSAStack->getInnerTeamsRegionLoc(),
7939 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007940 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007941 << isa<OMPExecutableDirective>(S);
7942 return StmtError();
7943 }
7944 }
7945
Reid Kleckner87a31802018-03-12 21:43:02 +00007946 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007947
7948 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7949}
7950
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007951StmtResult
7952Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7953 Stmt *AStmt, SourceLocation StartLoc,
7954 SourceLocation EndLoc) {
7955 if (!AStmt)
7956 return StmtError();
7957
Alexey Bataeve3727102018-04-18 15:57:46 +00007958 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007959 // 1.2.2 OpenMP Language Terminology
7960 // Structured block - An executable statement with a single entry at the
7961 // top and a single exit at the bottom.
7962 // The point of exit cannot be a branch out of the structured block.
7963 // longjmp() and throw() must not violate the entry/exit criteria.
7964 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007965 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7966 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7967 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7968 // 1.2.2 OpenMP Language Terminology
7969 // Structured block - An executable statement with a single entry at the
7970 // top and a single exit at the bottom.
7971 // The point of exit cannot be a branch out of the structured block.
7972 // longjmp() and throw() must not violate the entry/exit criteria.
7973 CS->getCapturedDecl()->setNothrow();
7974 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007975
Reid Kleckner87a31802018-03-12 21:43:02 +00007976 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007977
7978 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7979 AStmt);
7980}
7981
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007982StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7983 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007984 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007985 if (!AStmt)
7986 return StmtError();
7987
Alexey Bataeve3727102018-04-18 15:57:46 +00007988 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007989 // 1.2.2 OpenMP Language Terminology
7990 // Structured block - An executable statement with a single entry at the
7991 // top and a single exit at the bottom.
7992 // The point of exit cannot be a branch out of the structured block.
7993 // longjmp() and throw() must not violate the entry/exit criteria.
7994 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007995 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7996 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7997 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7998 // 1.2.2 OpenMP Language Terminology
7999 // Structured block - An executable statement with a single entry at the
8000 // top and a single exit at the bottom.
8001 // The point of exit cannot be a branch out of the structured block.
8002 // longjmp() and throw() must not violate the entry/exit criteria.
8003 CS->getCapturedDecl()->setNothrow();
8004 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008005
8006 OMPLoopDirective::HelperExprs B;
8007 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8008 // define the nested loops number.
8009 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008010 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008011 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008012 VarsWithImplicitDSA, B);
8013 if (NestedLoopCount == 0)
8014 return StmtError();
8015
8016 assert((CurContext->isDependentContext() || B.builtAll()) &&
8017 "omp target parallel for loop exprs were not built");
8018
8019 if (!CurContext->isDependentContext()) {
8020 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008021 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008022 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008023 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008024 B.NumIterations, *this, CurScope,
8025 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008026 return StmtError();
8027 }
8028 }
8029
Reid Kleckner87a31802018-03-12 21:43:02 +00008030 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008031 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8032 NestedLoopCount, Clauses, AStmt,
8033 B, DSAStack->isCancelRegion());
8034}
8035
Alexey Bataev95b64a92017-05-30 16:00:04 +00008036/// Check for existence of a map clause in the list of clauses.
8037static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8038 const OpenMPClauseKind K) {
8039 return llvm::any_of(
8040 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8041}
Samuel Antaodf67fc42016-01-19 19:15:56 +00008042
Alexey Bataev95b64a92017-05-30 16:00:04 +00008043template <typename... Params>
8044static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
8045 const Params... ClauseTypes) {
8046 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008047}
8048
Michael Wong65f367f2015-07-21 13:44:28 +00008049StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8050 Stmt *AStmt,
8051 SourceLocation StartLoc,
8052 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008053 if (!AStmt)
8054 return StmtError();
8055
8056 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8057
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008058 // OpenMP [2.10.1, Restrictions, p. 97]
8059 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008060 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
8061 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8062 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00008063 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008064 return StmtError();
8065 }
8066
Reid Kleckner87a31802018-03-12 21:43:02 +00008067 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00008068
8069 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8070 AStmt);
8071}
8072
Samuel Antaodf67fc42016-01-19 19:15:56 +00008073StmtResult
8074Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8075 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008076 SourceLocation EndLoc, Stmt *AStmt) {
8077 if (!AStmt)
8078 return StmtError();
8079
Alexey Bataeve3727102018-04-18 15:57:46 +00008080 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008081 // 1.2.2 OpenMP Language Terminology
8082 // Structured block - An executable statement with a single entry at the
8083 // top and a single exit at the bottom.
8084 // The point of exit cannot be a branch out of the structured block.
8085 // longjmp() and throw() must not violate the entry/exit criteria.
8086 CS->getCapturedDecl()->setNothrow();
8087 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
8088 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8089 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8090 // 1.2.2 OpenMP Language Terminology
8091 // Structured block - An executable statement with a single entry at the
8092 // top and a single exit at the bottom.
8093 // The point of exit cannot be a branch out of the structured block.
8094 // longjmp() and throw() must not violate the entry/exit criteria.
8095 CS->getCapturedDecl()->setNothrow();
8096 }
8097
Samuel Antaodf67fc42016-01-19 19:15:56 +00008098 // OpenMP [2.10.2, Restrictions, p. 99]
8099 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008100 if (!hasClauses(Clauses, OMPC_map)) {
8101 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8102 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008103 return StmtError();
8104 }
8105
Alexey Bataev7828b252017-11-21 17:08:48 +00008106 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8107 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008108}
8109
Samuel Antao72590762016-01-19 20:04:50 +00008110StmtResult
8111Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8112 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008113 SourceLocation EndLoc, Stmt *AStmt) {
8114 if (!AStmt)
8115 return StmtError();
8116
Alexey Bataeve3727102018-04-18 15:57:46 +00008117 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008118 // 1.2.2 OpenMP Language Terminology
8119 // Structured block - An executable statement with a single entry at the
8120 // top and a single exit at the bottom.
8121 // The point of exit cannot be a branch out of the structured block.
8122 // longjmp() and throw() must not violate the entry/exit criteria.
8123 CS->getCapturedDecl()->setNothrow();
8124 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
8125 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8126 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8127 // 1.2.2 OpenMP Language Terminology
8128 // Structured block - An executable statement with a single entry at the
8129 // top and a single exit at the bottom.
8130 // The point of exit cannot be a branch out of the structured block.
8131 // longjmp() and throw() must not violate the entry/exit criteria.
8132 CS->getCapturedDecl()->setNothrow();
8133 }
8134
Samuel Antao72590762016-01-19 20:04:50 +00008135 // OpenMP [2.10.3, Restrictions, p. 102]
8136 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008137 if (!hasClauses(Clauses, OMPC_map)) {
8138 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8139 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00008140 return StmtError();
8141 }
8142
Alexey Bataev7828b252017-11-21 17:08:48 +00008143 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8144 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00008145}
8146
Samuel Antao686c70c2016-05-26 17:30:50 +00008147StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8148 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008149 SourceLocation EndLoc,
8150 Stmt *AStmt) {
8151 if (!AStmt)
8152 return StmtError();
8153
Alexey Bataeve3727102018-04-18 15:57:46 +00008154 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008155 // 1.2.2 OpenMP Language Terminology
8156 // Structured block - An executable statement with a single entry at the
8157 // top and a single exit at the bottom.
8158 // The point of exit cannot be a branch out of the structured block.
8159 // longjmp() and throw() must not violate the entry/exit criteria.
8160 CS->getCapturedDecl()->setNothrow();
8161 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
8162 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8163 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8164 // 1.2.2 OpenMP Language Terminology
8165 // Structured block - An executable statement with a single entry at the
8166 // top and a single exit at the bottom.
8167 // The point of exit cannot be a branch out of the structured block.
8168 // longjmp() and throw() must not violate the entry/exit criteria.
8169 CS->getCapturedDecl()->setNothrow();
8170 }
8171
Alexey Bataev95b64a92017-05-30 16:00:04 +00008172 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00008173 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
8174 return StmtError();
8175 }
Alexey Bataev7828b252017-11-21 17:08:48 +00008176 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
8177 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00008178}
8179
Alexey Bataev13314bf2014-10-09 04:18:56 +00008180StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8181 Stmt *AStmt, SourceLocation StartLoc,
8182 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008183 if (!AStmt)
8184 return StmtError();
8185
Alexey Bataeve3727102018-04-18 15:57:46 +00008186 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008187 // 1.2.2 OpenMP Language Terminology
8188 // Structured block - An executable statement with a single entry at the
8189 // top and a single exit at the bottom.
8190 // The point of exit cannot be a branch out of the structured block.
8191 // longjmp() and throw() must not violate the entry/exit criteria.
8192 CS->getCapturedDecl()->setNothrow();
8193
Reid Kleckner87a31802018-03-12 21:43:02 +00008194 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00008195
Alexey Bataevceabd412017-11-30 18:01:54 +00008196 DSAStack->setParentTeamsRegionLoc(StartLoc);
8197
Alexey Bataev13314bf2014-10-09 04:18:56 +00008198 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8199}
8200
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008201StmtResult
8202Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8203 SourceLocation EndLoc,
8204 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008205 if (DSAStack->isParentNowaitRegion()) {
8206 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
8207 return StmtError();
8208 }
8209 if (DSAStack->isParentOrderedRegion()) {
8210 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
8211 return StmtError();
8212 }
8213 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
8214 CancelRegion);
8215}
8216
Alexey Bataev87933c72015-09-18 08:07:34 +00008217StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8218 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00008219 SourceLocation EndLoc,
8220 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00008221 if (DSAStack->isParentNowaitRegion()) {
8222 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
8223 return StmtError();
8224 }
8225 if (DSAStack->isParentOrderedRegion()) {
8226 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
8227 return StmtError();
8228 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008229 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00008230 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8231 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00008232}
8233
Alexey Bataev382967a2015-12-08 12:06:20 +00008234static bool checkGrainsizeNumTasksClauses(Sema &S,
8235 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008236 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00008237 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008238 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00008239 if (C->getClauseKind() == OMPC_grainsize ||
8240 C->getClauseKind() == OMPC_num_tasks) {
8241 if (!PrevClause)
8242 PrevClause = C;
8243 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008244 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008245 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
8246 << getOpenMPClauseName(C->getClauseKind())
8247 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008248 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008249 diag::note_omp_previous_grainsize_num_tasks)
8250 << getOpenMPClauseName(PrevClause->getClauseKind());
8251 ErrorFound = true;
8252 }
8253 }
8254 }
8255 return ErrorFound;
8256}
8257
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008258static bool checkReductionClauseWithNogroup(Sema &S,
8259 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008260 const OMPClause *ReductionClause = nullptr;
8261 const OMPClause *NogroupClause = nullptr;
8262 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008263 if (C->getClauseKind() == OMPC_reduction) {
8264 ReductionClause = C;
8265 if (NogroupClause)
8266 break;
8267 continue;
8268 }
8269 if (C->getClauseKind() == OMPC_nogroup) {
8270 NogroupClause = C;
8271 if (ReductionClause)
8272 break;
8273 continue;
8274 }
8275 }
8276 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008277 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
8278 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008279 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008280 return true;
8281 }
8282 return false;
8283}
8284
Alexey Bataev49f6e782015-12-01 04:18:41 +00008285StmtResult Sema::ActOnOpenMPTaskLoopDirective(
8286 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008287 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00008288 if (!AStmt)
8289 return StmtError();
8290
8291 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8292 OMPLoopDirective::HelperExprs B;
8293 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8294 // define the nested loops number.
8295 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008296 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008297 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00008298 VarsWithImplicitDSA, B);
8299 if (NestedLoopCount == 0)
8300 return StmtError();
8301
8302 assert((CurContext->isDependentContext() || B.builtAll()) &&
8303 "omp for loop exprs were not built");
8304
Alexey Bataev382967a2015-12-08 12:06:20 +00008305 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8306 // The grainsize clause and num_tasks clause are mutually exclusive and may
8307 // not appear on the same taskloop directive.
8308 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8309 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008310 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8311 // If a reduction clause is present on the taskloop directive, the nogroup
8312 // clause must not be specified.
8313 if (checkReductionClauseWithNogroup(*this, Clauses))
8314 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008315
Reid Kleckner87a31802018-03-12 21:43:02 +00008316 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00008317 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
8318 NestedLoopCount, Clauses, AStmt, B);
8319}
8320
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008321StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
8322 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008323 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008324 if (!AStmt)
8325 return StmtError();
8326
8327 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8328 OMPLoopDirective::HelperExprs B;
8329 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8330 // define the nested loops number.
8331 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008332 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008333 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
8334 VarsWithImplicitDSA, B);
8335 if (NestedLoopCount == 0)
8336 return StmtError();
8337
8338 assert((CurContext->isDependentContext() || B.builtAll()) &&
8339 "omp for loop exprs were not built");
8340
Alexey Bataev5a3af132016-03-29 08:58:54 +00008341 if (!CurContext->isDependentContext()) {
8342 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008343 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008344 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008345 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008346 B.NumIterations, *this, CurScope,
8347 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008348 return StmtError();
8349 }
8350 }
8351
Alexey Bataev382967a2015-12-08 12:06:20 +00008352 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8353 // The grainsize clause and num_tasks clause are mutually exclusive and may
8354 // not appear on the same taskloop directive.
8355 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8356 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008357 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8358 // If a reduction clause is present on the taskloop directive, the nogroup
8359 // clause must not be specified.
8360 if (checkReductionClauseWithNogroup(*this, Clauses))
8361 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00008362 if (checkSimdlenSafelenSpecified(*this, Clauses))
8363 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008364
Reid Kleckner87a31802018-03-12 21:43:02 +00008365 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008366 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
8367 NestedLoopCount, Clauses, AStmt, B);
8368}
8369
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008370StmtResult Sema::ActOnOpenMPDistributeDirective(
8371 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008372 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008373 if (!AStmt)
8374 return StmtError();
8375
8376 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8377 OMPLoopDirective::HelperExprs B;
8378 // In presence of clause 'collapse' with number of loops, it will
8379 // define the nested loops number.
8380 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008381 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008382 nullptr /*ordered not a clause on distribute*/, AStmt,
8383 *this, *DSAStack, VarsWithImplicitDSA, B);
8384 if (NestedLoopCount == 0)
8385 return StmtError();
8386
8387 assert((CurContext->isDependentContext() || B.builtAll()) &&
8388 "omp for loop exprs were not built");
8389
Reid Kleckner87a31802018-03-12 21:43:02 +00008390 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008391 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
8392 NestedLoopCount, Clauses, AStmt, B);
8393}
8394
Carlo Bertolli9925f152016-06-27 14:55:37 +00008395StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
8396 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008397 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00008398 if (!AStmt)
8399 return StmtError();
8400
Alexey Bataeve3727102018-04-18 15:57:46 +00008401 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00008402 // 1.2.2 OpenMP Language Terminology
8403 // Structured block - An executable statement with a single entry at the
8404 // top and a single exit at the bottom.
8405 // The point of exit cannot be a branch out of the structured block.
8406 // longjmp() and throw() must not violate the entry/exit criteria.
8407 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00008408 for (int ThisCaptureLevel =
8409 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
8410 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8411 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8412 // 1.2.2 OpenMP Language Terminology
8413 // Structured block - An executable statement with a single entry at the
8414 // top and a single exit at the bottom.
8415 // The point of exit cannot be a branch out of the structured block.
8416 // longjmp() and throw() must not violate the entry/exit criteria.
8417 CS->getCapturedDecl()->setNothrow();
8418 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00008419
8420 OMPLoopDirective::HelperExprs B;
8421 // In presence of clause 'collapse' with number of loops, it will
8422 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008423 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00008424 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00008425 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00008426 VarsWithImplicitDSA, B);
8427 if (NestedLoopCount == 0)
8428 return StmtError();
8429
8430 assert((CurContext->isDependentContext() || B.builtAll()) &&
8431 "omp for loop exprs were not built");
8432
Reid Kleckner87a31802018-03-12 21:43:02 +00008433 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008434 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008435 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8436 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00008437}
8438
Kelvin Li4a39add2016-07-05 05:00:15 +00008439StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
8440 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008441 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00008442 if (!AStmt)
8443 return StmtError();
8444
Alexey Bataeve3727102018-04-18 15:57:46 +00008445 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00008446 // 1.2.2 OpenMP Language Terminology
8447 // Structured block - An executable statement with a single entry at the
8448 // top and a single exit at the bottom.
8449 // The point of exit cannot be a branch out of the structured block.
8450 // longjmp() and throw() must not violate the entry/exit criteria.
8451 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00008452 for (int ThisCaptureLevel =
8453 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
8454 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8455 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8456 // 1.2.2 OpenMP Language Terminology
8457 // Structured block - An executable statement with a single entry at the
8458 // top and a single exit at the bottom.
8459 // The point of exit cannot be a branch out of the structured block.
8460 // longjmp() and throw() must not violate the entry/exit criteria.
8461 CS->getCapturedDecl()->setNothrow();
8462 }
Kelvin Li4a39add2016-07-05 05:00:15 +00008463
8464 OMPLoopDirective::HelperExprs B;
8465 // In presence of clause 'collapse' with number of loops, it will
8466 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008467 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00008468 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00008469 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00008470 VarsWithImplicitDSA, B);
8471 if (NestedLoopCount == 0)
8472 return StmtError();
8473
8474 assert((CurContext->isDependentContext() || B.builtAll()) &&
8475 "omp for loop exprs were not built");
8476
Alexey Bataev438388c2017-11-22 18:34:02 +00008477 if (!CurContext->isDependentContext()) {
8478 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008479 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008480 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8481 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8482 B.NumIterations, *this, CurScope,
8483 DSAStack))
8484 return StmtError();
8485 }
8486 }
8487
Kelvin Lic5609492016-07-15 04:39:07 +00008488 if (checkSimdlenSafelenSpecified(*this, Clauses))
8489 return StmtError();
8490
Reid Kleckner87a31802018-03-12 21:43:02 +00008491 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00008492 return OMPDistributeParallelForSimdDirective::Create(
8493 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8494}
8495
Kelvin Li787f3fc2016-07-06 04:45:38 +00008496StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
8497 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008498 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00008499 if (!AStmt)
8500 return StmtError();
8501
Alexey Bataeve3727102018-04-18 15:57:46 +00008502 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008503 // 1.2.2 OpenMP Language Terminology
8504 // Structured block - An executable statement with a single entry at the
8505 // top and a single exit at the bottom.
8506 // The point of exit cannot be a branch out of the structured block.
8507 // longjmp() and throw() must not violate the entry/exit criteria.
8508 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00008509 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
8510 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8511 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8512 // 1.2.2 OpenMP Language Terminology
8513 // Structured block - An executable statement with a single entry at the
8514 // top and a single exit at the bottom.
8515 // The point of exit cannot be a branch out of the structured block.
8516 // longjmp() and throw() must not violate the entry/exit criteria.
8517 CS->getCapturedDecl()->setNothrow();
8518 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00008519
8520 OMPLoopDirective::HelperExprs B;
8521 // In presence of clause 'collapse' with number of loops, it will
8522 // define the nested loops number.
8523 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008524 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00008525 nullptr /*ordered not a clause on distribute*/, CS, *this,
8526 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008527 if (NestedLoopCount == 0)
8528 return StmtError();
8529
8530 assert((CurContext->isDependentContext() || B.builtAll()) &&
8531 "omp for loop exprs were not built");
8532
Alexey Bataev438388c2017-11-22 18:34:02 +00008533 if (!CurContext->isDependentContext()) {
8534 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008535 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008536 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8537 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8538 B.NumIterations, *this, CurScope,
8539 DSAStack))
8540 return StmtError();
8541 }
8542 }
8543
Kelvin Lic5609492016-07-15 04:39:07 +00008544 if (checkSimdlenSafelenSpecified(*this, Clauses))
8545 return StmtError();
8546
Reid Kleckner87a31802018-03-12 21:43:02 +00008547 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00008548 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8549 NestedLoopCount, Clauses, AStmt, B);
8550}
8551
Kelvin Lia579b912016-07-14 02:54:56 +00008552StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8553 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008554 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00008555 if (!AStmt)
8556 return StmtError();
8557
Alexey Bataeve3727102018-04-18 15:57:46 +00008558 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00008559 // 1.2.2 OpenMP Language Terminology
8560 // Structured block - An executable statement with a single entry at the
8561 // top and a single exit at the bottom.
8562 // The point of exit cannot be a branch out of the structured block.
8563 // longjmp() and throw() must not violate the entry/exit criteria.
8564 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008565 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8566 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8567 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8568 // 1.2.2 OpenMP Language Terminology
8569 // Structured block - An executable statement with a single entry at the
8570 // top and a single exit at the bottom.
8571 // The point of exit cannot be a branch out of the structured block.
8572 // longjmp() and throw() must not violate the entry/exit criteria.
8573 CS->getCapturedDecl()->setNothrow();
8574 }
Kelvin Lia579b912016-07-14 02:54:56 +00008575
8576 OMPLoopDirective::HelperExprs B;
8577 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8578 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008579 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008580 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008581 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008582 VarsWithImplicitDSA, B);
8583 if (NestedLoopCount == 0)
8584 return StmtError();
8585
8586 assert((CurContext->isDependentContext() || B.builtAll()) &&
8587 "omp target parallel for simd loop exprs were not built");
8588
8589 if (!CurContext->isDependentContext()) {
8590 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008591 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008592 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008593 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8594 B.NumIterations, *this, CurScope,
8595 DSAStack))
8596 return StmtError();
8597 }
8598 }
Kelvin Lic5609492016-07-15 04:39:07 +00008599 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008600 return StmtError();
8601
Reid Kleckner87a31802018-03-12 21:43:02 +00008602 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008603 return OMPTargetParallelForSimdDirective::Create(
8604 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8605}
8606
Kelvin Li986330c2016-07-20 22:57:10 +00008607StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8608 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008609 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008610 if (!AStmt)
8611 return StmtError();
8612
Alexey Bataeve3727102018-04-18 15:57:46 +00008613 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008614 // 1.2.2 OpenMP Language Terminology
8615 // Structured block - An executable statement with a single entry at the
8616 // top and a single exit at the bottom.
8617 // The point of exit cannot be a branch out of the structured block.
8618 // longjmp() and throw() must not violate the entry/exit criteria.
8619 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008620 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8621 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8622 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8623 // 1.2.2 OpenMP Language Terminology
8624 // Structured block - An executable statement with a single entry at the
8625 // top and a single exit at the bottom.
8626 // The point of exit cannot be a branch out of the structured block.
8627 // longjmp() and throw() must not violate the entry/exit criteria.
8628 CS->getCapturedDecl()->setNothrow();
8629 }
8630
Kelvin Li986330c2016-07-20 22:57:10 +00008631 OMPLoopDirective::HelperExprs B;
8632 // In presence of clause 'collapse' with number of loops, it will define the
8633 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008634 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008635 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008636 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008637 VarsWithImplicitDSA, B);
8638 if (NestedLoopCount == 0)
8639 return StmtError();
8640
8641 assert((CurContext->isDependentContext() || B.builtAll()) &&
8642 "omp target simd loop exprs were not built");
8643
8644 if (!CurContext->isDependentContext()) {
8645 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008646 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008647 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008648 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8649 B.NumIterations, *this, CurScope,
8650 DSAStack))
8651 return StmtError();
8652 }
8653 }
8654
8655 if (checkSimdlenSafelenSpecified(*this, Clauses))
8656 return StmtError();
8657
Reid Kleckner87a31802018-03-12 21:43:02 +00008658 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008659 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8660 NestedLoopCount, Clauses, AStmt, B);
8661}
8662
Kelvin Li02532872016-08-05 14:37:37 +00008663StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8664 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008665 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008666 if (!AStmt)
8667 return StmtError();
8668
Alexey Bataeve3727102018-04-18 15:57:46 +00008669 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008670 // 1.2.2 OpenMP Language Terminology
8671 // Structured block - An executable statement with a single entry at the
8672 // top and a single exit at the bottom.
8673 // The point of exit cannot be a branch out of the structured block.
8674 // longjmp() and throw() must not violate the entry/exit criteria.
8675 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008676 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8677 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8678 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8679 // 1.2.2 OpenMP Language Terminology
8680 // Structured block - An executable statement with a single entry at the
8681 // top and a single exit at the bottom.
8682 // The point of exit cannot be a branch out of the structured block.
8683 // longjmp() and throw() must not violate the entry/exit criteria.
8684 CS->getCapturedDecl()->setNothrow();
8685 }
Kelvin Li02532872016-08-05 14:37:37 +00008686
8687 OMPLoopDirective::HelperExprs B;
8688 // In presence of clause 'collapse' with number of loops, it will
8689 // define the nested loops number.
8690 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008691 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008692 nullptr /*ordered not a clause on distribute*/, CS, *this,
8693 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008694 if (NestedLoopCount == 0)
8695 return StmtError();
8696
8697 assert((CurContext->isDependentContext() || B.builtAll()) &&
8698 "omp teams distribute loop exprs were not built");
8699
Reid Kleckner87a31802018-03-12 21:43:02 +00008700 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008701
8702 DSAStack->setParentTeamsRegionLoc(StartLoc);
8703
David Majnemer9d168222016-08-05 17:44:54 +00008704 return OMPTeamsDistributeDirective::Create(
8705 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008706}
8707
Kelvin Li4e325f72016-10-25 12:50:55 +00008708StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8709 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008710 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008711 if (!AStmt)
8712 return StmtError();
8713
Alexey Bataeve3727102018-04-18 15:57:46 +00008714 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008715 // 1.2.2 OpenMP Language Terminology
8716 // Structured block - An executable statement with a single entry at the
8717 // top and a single exit at the bottom.
8718 // The point of exit cannot be a branch out of the structured block.
8719 // longjmp() and throw() must not violate the entry/exit criteria.
8720 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008721 for (int ThisCaptureLevel =
8722 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8723 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8724 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8725 // 1.2.2 OpenMP Language Terminology
8726 // Structured block - An executable statement with a single entry at the
8727 // top and a single exit at the bottom.
8728 // The point of exit cannot be a branch out of the structured block.
8729 // longjmp() and throw() must not violate the entry/exit criteria.
8730 CS->getCapturedDecl()->setNothrow();
8731 }
8732
Kelvin Li4e325f72016-10-25 12:50:55 +00008733
8734 OMPLoopDirective::HelperExprs B;
8735 // In presence of clause 'collapse' with number of loops, it will
8736 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008737 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008738 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008739 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008740 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008741
8742 if (NestedLoopCount == 0)
8743 return StmtError();
8744
8745 assert((CurContext->isDependentContext() || B.builtAll()) &&
8746 "omp teams distribute simd loop exprs were not built");
8747
8748 if (!CurContext->isDependentContext()) {
8749 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008750 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008751 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8752 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8753 B.NumIterations, *this, CurScope,
8754 DSAStack))
8755 return StmtError();
8756 }
8757 }
8758
8759 if (checkSimdlenSafelenSpecified(*this, Clauses))
8760 return StmtError();
8761
Reid Kleckner87a31802018-03-12 21:43:02 +00008762 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008763
8764 DSAStack->setParentTeamsRegionLoc(StartLoc);
8765
Kelvin Li4e325f72016-10-25 12:50:55 +00008766 return OMPTeamsDistributeSimdDirective::Create(
8767 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8768}
8769
Kelvin Li579e41c2016-11-30 23:51:03 +00008770StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8771 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008772 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008773 if (!AStmt)
8774 return StmtError();
8775
Alexey Bataeve3727102018-04-18 15:57:46 +00008776 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008777 // 1.2.2 OpenMP Language Terminology
8778 // Structured block - An executable statement with a single entry at the
8779 // top and a single exit at the bottom.
8780 // The point of exit cannot be a branch out of the structured block.
8781 // longjmp() and throw() must not violate the entry/exit criteria.
8782 CS->getCapturedDecl()->setNothrow();
8783
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008784 for (int ThisCaptureLevel =
8785 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8786 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8787 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8788 // 1.2.2 OpenMP Language Terminology
8789 // Structured block - An executable statement with a single entry at the
8790 // top and a single exit at the bottom.
8791 // The point of exit cannot be a branch out of the structured block.
8792 // longjmp() and throw() must not violate the entry/exit criteria.
8793 CS->getCapturedDecl()->setNothrow();
8794 }
8795
Kelvin Li579e41c2016-11-30 23:51:03 +00008796 OMPLoopDirective::HelperExprs B;
8797 // In presence of clause 'collapse' with number of loops, it will
8798 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008799 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008800 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008801 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008802 VarsWithImplicitDSA, B);
8803
8804 if (NestedLoopCount == 0)
8805 return StmtError();
8806
8807 assert((CurContext->isDependentContext() || B.builtAll()) &&
8808 "omp for loop exprs were not built");
8809
8810 if (!CurContext->isDependentContext()) {
8811 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008812 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008813 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8814 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8815 B.NumIterations, *this, CurScope,
8816 DSAStack))
8817 return StmtError();
8818 }
8819 }
8820
8821 if (checkSimdlenSafelenSpecified(*this, Clauses))
8822 return StmtError();
8823
Reid Kleckner87a31802018-03-12 21:43:02 +00008824 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008825
8826 DSAStack->setParentTeamsRegionLoc(StartLoc);
8827
Kelvin Li579e41c2016-11-30 23:51:03 +00008828 return OMPTeamsDistributeParallelForSimdDirective::Create(
8829 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8830}
8831
Kelvin Li7ade93f2016-12-09 03:24:30 +00008832StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8833 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008834 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008835 if (!AStmt)
8836 return StmtError();
8837
Alexey Bataeve3727102018-04-18 15:57:46 +00008838 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008839 // 1.2.2 OpenMP Language Terminology
8840 // Structured block - An executable statement with a single entry at the
8841 // top and a single exit at the bottom.
8842 // The point of exit cannot be a branch out of the structured block.
8843 // longjmp() and throw() must not violate the entry/exit criteria.
8844 CS->getCapturedDecl()->setNothrow();
8845
Carlo Bertolli62fae152017-11-20 20:46:39 +00008846 for (int ThisCaptureLevel =
8847 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8848 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8849 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8850 // 1.2.2 OpenMP Language Terminology
8851 // Structured block - An executable statement with a single entry at the
8852 // top and a single exit at the bottom.
8853 // The point of exit cannot be a branch out of the structured block.
8854 // longjmp() and throw() must not violate the entry/exit criteria.
8855 CS->getCapturedDecl()->setNothrow();
8856 }
8857
Kelvin Li7ade93f2016-12-09 03:24:30 +00008858 OMPLoopDirective::HelperExprs B;
8859 // In presence of clause 'collapse' with number of loops, it will
8860 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008861 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008862 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008863 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008864 VarsWithImplicitDSA, B);
8865
8866 if (NestedLoopCount == 0)
8867 return StmtError();
8868
8869 assert((CurContext->isDependentContext() || B.builtAll()) &&
8870 "omp for loop exprs were not built");
8871
Reid Kleckner87a31802018-03-12 21:43:02 +00008872 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008873
8874 DSAStack->setParentTeamsRegionLoc(StartLoc);
8875
Kelvin Li7ade93f2016-12-09 03:24:30 +00008876 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008877 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8878 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008879}
8880
Kelvin Libf594a52016-12-17 05:48:59 +00008881StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8882 Stmt *AStmt,
8883 SourceLocation StartLoc,
8884 SourceLocation EndLoc) {
8885 if (!AStmt)
8886 return StmtError();
8887
Alexey Bataeve3727102018-04-18 15:57:46 +00008888 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008889 // 1.2.2 OpenMP Language Terminology
8890 // Structured block - An executable statement with a single entry at the
8891 // top and a single exit at the bottom.
8892 // The point of exit cannot be a branch out of the structured block.
8893 // longjmp() and throw() must not violate the entry/exit criteria.
8894 CS->getCapturedDecl()->setNothrow();
8895
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008896 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8897 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8898 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8899 // 1.2.2 OpenMP Language Terminology
8900 // Structured block - An executable statement with a single entry at the
8901 // top and a single exit at the bottom.
8902 // The point of exit cannot be a branch out of the structured block.
8903 // longjmp() and throw() must not violate the entry/exit criteria.
8904 CS->getCapturedDecl()->setNothrow();
8905 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008906 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008907
8908 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8909 AStmt);
8910}
8911
Kelvin Li83c451e2016-12-25 04:52:54 +00008912StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8913 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008914 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008915 if (!AStmt)
8916 return StmtError();
8917
Alexey Bataeve3727102018-04-18 15:57:46 +00008918 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008919 // 1.2.2 OpenMP Language Terminology
8920 // Structured block - An executable statement with a single entry at the
8921 // top and a single exit at the bottom.
8922 // The point of exit cannot be a branch out of the structured block.
8923 // longjmp() and throw() must not violate the entry/exit criteria.
8924 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008925 for (int ThisCaptureLevel =
8926 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8927 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8928 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8929 // 1.2.2 OpenMP Language Terminology
8930 // Structured block - An executable statement with a single entry at the
8931 // top and a single exit at the bottom.
8932 // The point of exit cannot be a branch out of the structured block.
8933 // longjmp() and throw() must not violate the entry/exit criteria.
8934 CS->getCapturedDecl()->setNothrow();
8935 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008936
8937 OMPLoopDirective::HelperExprs B;
8938 // In presence of clause 'collapse' with number of loops, it will
8939 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008940 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008941 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8942 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008943 VarsWithImplicitDSA, B);
8944 if (NestedLoopCount == 0)
8945 return StmtError();
8946
8947 assert((CurContext->isDependentContext() || B.builtAll()) &&
8948 "omp target teams distribute loop exprs were not built");
8949
Reid Kleckner87a31802018-03-12 21:43:02 +00008950 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008951 return OMPTargetTeamsDistributeDirective::Create(
8952 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8953}
8954
Kelvin Li80e8f562016-12-29 22:16:30 +00008955StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8956 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008957 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008958 if (!AStmt)
8959 return StmtError();
8960
Alexey Bataeve3727102018-04-18 15:57:46 +00008961 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008962 // 1.2.2 OpenMP Language Terminology
8963 // Structured block - An executable statement with a single entry at the
8964 // top and a single exit at the bottom.
8965 // The point of exit cannot be a branch out of the structured block.
8966 // longjmp() and throw() must not violate the entry/exit criteria.
8967 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008968 for (int ThisCaptureLevel =
8969 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8970 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8971 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8972 // 1.2.2 OpenMP Language Terminology
8973 // Structured block - An executable statement with a single entry at the
8974 // top and a single exit at the bottom.
8975 // The point of exit cannot be a branch out of the structured block.
8976 // longjmp() and throw() must not violate the entry/exit criteria.
8977 CS->getCapturedDecl()->setNothrow();
8978 }
8979
Kelvin Li80e8f562016-12-29 22:16:30 +00008980 OMPLoopDirective::HelperExprs B;
8981 // In presence of clause 'collapse' with number of loops, it will
8982 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008983 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008984 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8985 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008986 VarsWithImplicitDSA, B);
8987 if (NestedLoopCount == 0)
8988 return StmtError();
8989
8990 assert((CurContext->isDependentContext() || B.builtAll()) &&
8991 "omp target teams distribute parallel for loop exprs were not built");
8992
Alexey Bataev647dd842018-01-15 20:59:40 +00008993 if (!CurContext->isDependentContext()) {
8994 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008995 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008996 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8997 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8998 B.NumIterations, *this, CurScope,
8999 DSAStack))
9000 return StmtError();
9001 }
9002 }
9003
Reid Kleckner87a31802018-03-12 21:43:02 +00009004 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00009005 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00009006 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9007 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00009008}
9009
Kelvin Li1851df52017-01-03 05:23:48 +00009010StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009012 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00009013 if (!AStmt)
9014 return StmtError();
9015
Alexey Bataeve3727102018-04-18 15:57:46 +00009016 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00009017 // 1.2.2 OpenMP Language Terminology
9018 // Structured block - An executable statement with a single entry at the
9019 // top and a single exit at the bottom.
9020 // The point of exit cannot be a branch out of the structured block.
9021 // longjmp() and throw() must not violate the entry/exit criteria.
9022 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00009023 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
9024 OMPD_target_teams_distribute_parallel_for_simd);
9025 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9026 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9027 // 1.2.2 OpenMP Language Terminology
9028 // Structured block - An executable statement with a single entry at the
9029 // top and a single exit at the bottom.
9030 // The point of exit cannot be a branch out of the structured block.
9031 // longjmp() and throw() must not violate the entry/exit criteria.
9032 CS->getCapturedDecl()->setNothrow();
9033 }
Kelvin Li1851df52017-01-03 05:23:48 +00009034
9035 OMPLoopDirective::HelperExprs B;
9036 // In presence of clause 'collapse' with number of loops, it will
9037 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009038 unsigned NestedLoopCount =
9039 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00009040 getCollapseNumberExpr(Clauses),
9041 nullptr /*ordered not a clause on distribute*/, CS, *this,
9042 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00009043 if (NestedLoopCount == 0)
9044 return StmtError();
9045
9046 assert((CurContext->isDependentContext() || B.builtAll()) &&
9047 "omp target teams distribute parallel for simd loop exprs were not "
9048 "built");
9049
9050 if (!CurContext->isDependentContext()) {
9051 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009052 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00009053 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9054 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9055 B.NumIterations, *this, CurScope,
9056 DSAStack))
9057 return StmtError();
9058 }
9059 }
9060
Alexey Bataev438388c2017-11-22 18:34:02 +00009061 if (checkSimdlenSafelenSpecified(*this, Clauses))
9062 return StmtError();
9063
Reid Kleckner87a31802018-03-12 21:43:02 +00009064 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00009065 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
9066 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9067}
9068
Kelvin Lida681182017-01-10 18:08:18 +00009069StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
9070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009071 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00009072 if (!AStmt)
9073 return StmtError();
9074
9075 auto *CS = cast<CapturedStmt>(AStmt);
9076 // 1.2.2 OpenMP Language Terminology
9077 // Structured block - An executable statement with a single entry at the
9078 // top and a single exit at the bottom.
9079 // The point of exit cannot be a branch out of the structured block.
9080 // longjmp() and throw() must not violate the entry/exit criteria.
9081 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009082 for (int ThisCaptureLevel =
9083 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
9084 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9085 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9086 // 1.2.2 OpenMP Language Terminology
9087 // Structured block - An executable statement with a single entry at the
9088 // top and a single exit at the bottom.
9089 // The point of exit cannot be a branch out of the structured block.
9090 // longjmp() and throw() must not violate the entry/exit criteria.
9091 CS->getCapturedDecl()->setNothrow();
9092 }
Kelvin Lida681182017-01-10 18:08:18 +00009093
9094 OMPLoopDirective::HelperExprs B;
9095 // In presence of clause 'collapse' with number of loops, it will
9096 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009097 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00009098 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009099 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00009100 VarsWithImplicitDSA, B);
9101 if (NestedLoopCount == 0)
9102 return StmtError();
9103
9104 assert((CurContext->isDependentContext() || B.builtAll()) &&
9105 "omp target teams distribute simd loop exprs were not built");
9106
Alexey Bataev438388c2017-11-22 18:34:02 +00009107 if (!CurContext->isDependentContext()) {
9108 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009109 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009110 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9111 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9112 B.NumIterations, *this, CurScope,
9113 DSAStack))
9114 return StmtError();
9115 }
9116 }
9117
9118 if (checkSimdlenSafelenSpecified(*this, Clauses))
9119 return StmtError();
9120
Reid Kleckner87a31802018-03-12 21:43:02 +00009121 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00009122 return OMPTargetTeamsDistributeSimdDirective::Create(
9123 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9124}
9125
Alexey Bataeved09d242014-05-28 05:53:51 +00009126OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009127 SourceLocation StartLoc,
9128 SourceLocation LParenLoc,
9129 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009130 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009131 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00009132 case OMPC_final:
9133 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
9134 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00009135 case OMPC_num_threads:
9136 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
9137 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009138 case OMPC_safelen:
9139 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
9140 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00009141 case OMPC_simdlen:
9142 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
9143 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009144 case OMPC_allocator:
9145 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
9146 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00009147 case OMPC_collapse:
9148 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
9149 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009150 case OMPC_ordered:
9151 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
9152 break;
Michael Wonge710d542015-08-07 16:16:36 +00009153 case OMPC_device:
9154 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
9155 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00009156 case OMPC_num_teams:
9157 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
9158 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009159 case OMPC_thread_limit:
9160 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
9161 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00009162 case OMPC_priority:
9163 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
9164 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009165 case OMPC_grainsize:
9166 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
9167 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00009168 case OMPC_num_tasks:
9169 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
9170 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00009171 case OMPC_hint:
9172 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
9173 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009174 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009175 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009176 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009177 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009178 case OMPC_private:
9179 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009180 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009181 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009182 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009183 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009184 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009185 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009186 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009187 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009188 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00009189 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009190 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009191 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009192 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009193 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009194 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009195 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009196 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009197 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009198 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009199 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009200 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00009201 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009202 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009203 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00009204 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009205 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009206 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009207 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009208 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009209 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009210 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009211 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009212 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009213 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009214 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009215 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009216 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009217 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009218 llvm_unreachable("Clause is not allowed.");
9219 }
9220 return Res;
9221}
9222
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009223// An OpenMP directive such as 'target parallel' has two captured regions:
9224// for the 'target' and 'parallel' respectively. This function returns
9225// the region in which to capture expressions associated with a clause.
9226// A return value of OMPD_unknown signifies that the expression should not
9227// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009228static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
9229 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
9230 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009231 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009232 switch (CKind) {
9233 case OMPC_if:
9234 switch (DKind) {
9235 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009236 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009237 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009238 // If this clause applies to the nested 'parallel' region, capture within
9239 // the 'target' region, otherwise do not capture.
9240 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9241 CaptureRegion = OMPD_target;
9242 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00009243 case OMPD_target_teams_distribute_parallel_for:
9244 case OMPD_target_teams_distribute_parallel_for_simd:
9245 // If this clause applies to the nested 'parallel' region, capture within
9246 // the 'teams' region, otherwise do not capture.
9247 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9248 CaptureRegion = OMPD_teams;
9249 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009250 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009251 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009252 CaptureRegion = OMPD_teams;
9253 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009254 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009255 case OMPD_target_enter_data:
9256 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009257 CaptureRegion = OMPD_task;
9258 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009259 case OMPD_cancel:
9260 case OMPD_parallel:
9261 case OMPD_parallel_sections:
9262 case OMPD_parallel_for:
9263 case OMPD_parallel_for_simd:
9264 case OMPD_target:
9265 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009266 case OMPD_target_teams:
9267 case OMPD_target_teams_distribute:
9268 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009269 case OMPD_distribute_parallel_for:
9270 case OMPD_distribute_parallel_for_simd:
9271 case OMPD_task:
9272 case OMPD_taskloop:
9273 case OMPD_taskloop_simd:
9274 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009275 // Do not capture if-clause expressions.
9276 break;
9277 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009278 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009279 case OMPD_taskyield:
9280 case OMPD_barrier:
9281 case OMPD_taskwait:
9282 case OMPD_cancellation_point:
9283 case OMPD_flush:
9284 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009285 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009286 case OMPD_declare_simd:
9287 case OMPD_declare_target:
9288 case OMPD_end_declare_target:
9289 case OMPD_teams:
9290 case OMPD_simd:
9291 case OMPD_for:
9292 case OMPD_for_simd:
9293 case OMPD_sections:
9294 case OMPD_section:
9295 case OMPD_single:
9296 case OMPD_master:
9297 case OMPD_critical:
9298 case OMPD_taskgroup:
9299 case OMPD_distribute:
9300 case OMPD_ordered:
9301 case OMPD_atomic:
9302 case OMPD_distribute_simd:
9303 case OMPD_teams_distribute:
9304 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009305 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009306 llvm_unreachable("Unexpected OpenMP directive with if-clause");
9307 case OMPD_unknown:
9308 llvm_unreachable("Unknown OpenMP directive");
9309 }
9310 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009311 case OMPC_num_threads:
9312 switch (DKind) {
9313 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009314 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009315 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009316 CaptureRegion = OMPD_target;
9317 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009318 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009319 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009320 case OMPD_target_teams_distribute_parallel_for:
9321 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009322 CaptureRegion = OMPD_teams;
9323 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009324 case OMPD_parallel:
9325 case OMPD_parallel_sections:
9326 case OMPD_parallel_for:
9327 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009328 case OMPD_distribute_parallel_for:
9329 case OMPD_distribute_parallel_for_simd:
9330 // Do not capture num_threads-clause expressions.
9331 break;
9332 case OMPD_target_data:
9333 case OMPD_target_enter_data:
9334 case OMPD_target_exit_data:
9335 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009336 case OMPD_target:
9337 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009338 case OMPD_target_teams:
9339 case OMPD_target_teams_distribute:
9340 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009341 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009342 case OMPD_task:
9343 case OMPD_taskloop:
9344 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009345 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009346 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009347 case OMPD_taskyield:
9348 case OMPD_barrier:
9349 case OMPD_taskwait:
9350 case OMPD_cancellation_point:
9351 case OMPD_flush:
9352 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009353 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009354 case OMPD_declare_simd:
9355 case OMPD_declare_target:
9356 case OMPD_end_declare_target:
9357 case OMPD_teams:
9358 case OMPD_simd:
9359 case OMPD_for:
9360 case OMPD_for_simd:
9361 case OMPD_sections:
9362 case OMPD_section:
9363 case OMPD_single:
9364 case OMPD_master:
9365 case OMPD_critical:
9366 case OMPD_taskgroup:
9367 case OMPD_distribute:
9368 case OMPD_ordered:
9369 case OMPD_atomic:
9370 case OMPD_distribute_simd:
9371 case OMPD_teams_distribute:
9372 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009373 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009374 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
9375 case OMPD_unknown:
9376 llvm_unreachable("Unknown OpenMP directive");
9377 }
9378 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009379 case OMPC_num_teams:
9380 switch (DKind) {
9381 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009382 case OMPD_target_teams_distribute:
9383 case OMPD_target_teams_distribute_simd:
9384 case OMPD_target_teams_distribute_parallel_for:
9385 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009386 CaptureRegion = OMPD_target;
9387 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009388 case OMPD_teams_distribute_parallel_for:
9389 case OMPD_teams_distribute_parallel_for_simd:
9390 case OMPD_teams:
9391 case OMPD_teams_distribute:
9392 case OMPD_teams_distribute_simd:
9393 // Do not capture num_teams-clause expressions.
9394 break;
9395 case OMPD_distribute_parallel_for:
9396 case OMPD_distribute_parallel_for_simd:
9397 case OMPD_task:
9398 case OMPD_taskloop:
9399 case OMPD_taskloop_simd:
9400 case OMPD_target_data:
9401 case OMPD_target_enter_data:
9402 case OMPD_target_exit_data:
9403 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009404 case OMPD_cancel:
9405 case OMPD_parallel:
9406 case OMPD_parallel_sections:
9407 case OMPD_parallel_for:
9408 case OMPD_parallel_for_simd:
9409 case OMPD_target:
9410 case OMPD_target_simd:
9411 case OMPD_target_parallel:
9412 case OMPD_target_parallel_for:
9413 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009414 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009415 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009416 case OMPD_taskyield:
9417 case OMPD_barrier:
9418 case OMPD_taskwait:
9419 case OMPD_cancellation_point:
9420 case OMPD_flush:
9421 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009422 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009423 case OMPD_declare_simd:
9424 case OMPD_declare_target:
9425 case OMPD_end_declare_target:
9426 case OMPD_simd:
9427 case OMPD_for:
9428 case OMPD_for_simd:
9429 case OMPD_sections:
9430 case OMPD_section:
9431 case OMPD_single:
9432 case OMPD_master:
9433 case OMPD_critical:
9434 case OMPD_taskgroup:
9435 case OMPD_distribute:
9436 case OMPD_ordered:
9437 case OMPD_atomic:
9438 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009439 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009440 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9441 case OMPD_unknown:
9442 llvm_unreachable("Unknown OpenMP directive");
9443 }
9444 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009445 case OMPC_thread_limit:
9446 switch (DKind) {
9447 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009448 case OMPD_target_teams_distribute:
9449 case OMPD_target_teams_distribute_simd:
9450 case OMPD_target_teams_distribute_parallel_for:
9451 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009452 CaptureRegion = OMPD_target;
9453 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009454 case OMPD_teams_distribute_parallel_for:
9455 case OMPD_teams_distribute_parallel_for_simd:
9456 case OMPD_teams:
9457 case OMPD_teams_distribute:
9458 case OMPD_teams_distribute_simd:
9459 // Do not capture thread_limit-clause expressions.
9460 break;
9461 case OMPD_distribute_parallel_for:
9462 case OMPD_distribute_parallel_for_simd:
9463 case OMPD_task:
9464 case OMPD_taskloop:
9465 case OMPD_taskloop_simd:
9466 case OMPD_target_data:
9467 case OMPD_target_enter_data:
9468 case OMPD_target_exit_data:
9469 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009470 case OMPD_cancel:
9471 case OMPD_parallel:
9472 case OMPD_parallel_sections:
9473 case OMPD_parallel_for:
9474 case OMPD_parallel_for_simd:
9475 case OMPD_target:
9476 case OMPD_target_simd:
9477 case OMPD_target_parallel:
9478 case OMPD_target_parallel_for:
9479 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009480 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009481 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009482 case OMPD_taskyield:
9483 case OMPD_barrier:
9484 case OMPD_taskwait:
9485 case OMPD_cancellation_point:
9486 case OMPD_flush:
9487 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009488 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009489 case OMPD_declare_simd:
9490 case OMPD_declare_target:
9491 case OMPD_end_declare_target:
9492 case OMPD_simd:
9493 case OMPD_for:
9494 case OMPD_for_simd:
9495 case OMPD_sections:
9496 case OMPD_section:
9497 case OMPD_single:
9498 case OMPD_master:
9499 case OMPD_critical:
9500 case OMPD_taskgroup:
9501 case OMPD_distribute:
9502 case OMPD_ordered:
9503 case OMPD_atomic:
9504 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009505 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009506 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
9507 case OMPD_unknown:
9508 llvm_unreachable("Unknown OpenMP directive");
9509 }
9510 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009511 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009512 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00009513 case OMPD_parallel_for:
9514 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009515 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00009516 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009517 case OMPD_teams_distribute_parallel_for:
9518 case OMPD_teams_distribute_parallel_for_simd:
9519 case OMPD_target_parallel_for:
9520 case OMPD_target_parallel_for_simd:
9521 case OMPD_target_teams_distribute_parallel_for:
9522 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009523 CaptureRegion = OMPD_parallel;
9524 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009525 case OMPD_for:
9526 case OMPD_for_simd:
9527 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009528 break;
9529 case OMPD_task:
9530 case OMPD_taskloop:
9531 case OMPD_taskloop_simd:
9532 case OMPD_target_data:
9533 case OMPD_target_enter_data:
9534 case OMPD_target_exit_data:
9535 case OMPD_target_update:
9536 case OMPD_teams:
9537 case OMPD_teams_distribute:
9538 case OMPD_teams_distribute_simd:
9539 case OMPD_target_teams_distribute:
9540 case OMPD_target_teams_distribute_simd:
9541 case OMPD_target:
9542 case OMPD_target_simd:
9543 case OMPD_target_parallel:
9544 case OMPD_cancel:
9545 case OMPD_parallel:
9546 case OMPD_parallel_sections:
9547 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009548 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009549 case OMPD_taskyield:
9550 case OMPD_barrier:
9551 case OMPD_taskwait:
9552 case OMPD_cancellation_point:
9553 case OMPD_flush:
9554 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009555 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009556 case OMPD_declare_simd:
9557 case OMPD_declare_target:
9558 case OMPD_end_declare_target:
9559 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009560 case OMPD_sections:
9561 case OMPD_section:
9562 case OMPD_single:
9563 case OMPD_master:
9564 case OMPD_critical:
9565 case OMPD_taskgroup:
9566 case OMPD_distribute:
9567 case OMPD_ordered:
9568 case OMPD_atomic:
9569 case OMPD_distribute_simd:
9570 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009571 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009572 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9573 case OMPD_unknown:
9574 llvm_unreachable("Unknown OpenMP directive");
9575 }
9576 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009577 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009578 switch (DKind) {
9579 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009580 case OMPD_teams_distribute_parallel_for_simd:
9581 case OMPD_teams_distribute:
9582 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009583 case OMPD_target_teams_distribute_parallel_for:
9584 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009585 case OMPD_target_teams_distribute:
9586 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009587 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009588 break;
9589 case OMPD_distribute_parallel_for:
9590 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009591 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009592 case OMPD_distribute_simd:
9593 // Do not capture thread_limit-clause expressions.
9594 break;
9595 case OMPD_parallel_for:
9596 case OMPD_parallel_for_simd:
9597 case OMPD_target_parallel_for_simd:
9598 case OMPD_target_parallel_for:
9599 case OMPD_task:
9600 case OMPD_taskloop:
9601 case OMPD_taskloop_simd:
9602 case OMPD_target_data:
9603 case OMPD_target_enter_data:
9604 case OMPD_target_exit_data:
9605 case OMPD_target_update:
9606 case OMPD_teams:
9607 case OMPD_target:
9608 case OMPD_target_simd:
9609 case OMPD_target_parallel:
9610 case OMPD_cancel:
9611 case OMPD_parallel:
9612 case OMPD_parallel_sections:
9613 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009614 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009615 case OMPD_taskyield:
9616 case OMPD_barrier:
9617 case OMPD_taskwait:
9618 case OMPD_cancellation_point:
9619 case OMPD_flush:
9620 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009621 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009622 case OMPD_declare_simd:
9623 case OMPD_declare_target:
9624 case OMPD_end_declare_target:
9625 case OMPD_simd:
9626 case OMPD_for:
9627 case OMPD_for_simd:
9628 case OMPD_sections:
9629 case OMPD_section:
9630 case OMPD_single:
9631 case OMPD_master:
9632 case OMPD_critical:
9633 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009634 case OMPD_ordered:
9635 case OMPD_atomic:
9636 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009637 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009638 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9639 case OMPD_unknown:
9640 llvm_unreachable("Unknown OpenMP directive");
9641 }
9642 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009643 case OMPC_device:
9644 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009645 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009646 case OMPD_target_enter_data:
9647 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009648 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009649 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009650 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009651 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009652 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009653 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009654 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009655 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009656 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009657 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009658 CaptureRegion = OMPD_task;
9659 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009660 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009661 // Do not capture device-clause expressions.
9662 break;
9663 case OMPD_teams_distribute_parallel_for:
9664 case OMPD_teams_distribute_parallel_for_simd:
9665 case OMPD_teams:
9666 case OMPD_teams_distribute:
9667 case OMPD_teams_distribute_simd:
9668 case OMPD_distribute_parallel_for:
9669 case OMPD_distribute_parallel_for_simd:
9670 case OMPD_task:
9671 case OMPD_taskloop:
9672 case OMPD_taskloop_simd:
9673 case OMPD_cancel:
9674 case OMPD_parallel:
9675 case OMPD_parallel_sections:
9676 case OMPD_parallel_for:
9677 case OMPD_parallel_for_simd:
9678 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009679 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009680 case OMPD_taskyield:
9681 case OMPD_barrier:
9682 case OMPD_taskwait:
9683 case OMPD_cancellation_point:
9684 case OMPD_flush:
9685 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009686 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009687 case OMPD_declare_simd:
9688 case OMPD_declare_target:
9689 case OMPD_end_declare_target:
9690 case OMPD_simd:
9691 case OMPD_for:
9692 case OMPD_for_simd:
9693 case OMPD_sections:
9694 case OMPD_section:
9695 case OMPD_single:
9696 case OMPD_master:
9697 case OMPD_critical:
9698 case OMPD_taskgroup:
9699 case OMPD_distribute:
9700 case OMPD_ordered:
9701 case OMPD_atomic:
9702 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009703 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009704 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9705 case OMPD_unknown:
9706 llvm_unreachable("Unknown OpenMP directive");
9707 }
9708 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009709 case OMPC_firstprivate:
9710 case OMPC_lastprivate:
9711 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009712 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009713 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009714 case OMPC_linear:
9715 case OMPC_default:
9716 case OMPC_proc_bind:
9717 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009718 case OMPC_safelen:
9719 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009720 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009721 case OMPC_collapse:
9722 case OMPC_private:
9723 case OMPC_shared:
9724 case OMPC_aligned:
9725 case OMPC_copyin:
9726 case OMPC_copyprivate:
9727 case OMPC_ordered:
9728 case OMPC_nowait:
9729 case OMPC_untied:
9730 case OMPC_mergeable:
9731 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009732 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009733 case OMPC_flush:
9734 case OMPC_read:
9735 case OMPC_write:
9736 case OMPC_update:
9737 case OMPC_capture:
9738 case OMPC_seq_cst:
9739 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009740 case OMPC_threads:
9741 case OMPC_simd:
9742 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009743 case OMPC_priority:
9744 case OMPC_grainsize:
9745 case OMPC_nogroup:
9746 case OMPC_num_tasks:
9747 case OMPC_hint:
9748 case OMPC_defaultmap:
9749 case OMPC_unknown:
9750 case OMPC_uniform:
9751 case OMPC_to:
9752 case OMPC_from:
9753 case OMPC_use_device_ptr:
9754 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009755 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009756 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009757 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009758 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009759 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009760 llvm_unreachable("Unexpected OpenMP clause.");
9761 }
9762 return CaptureRegion;
9763}
9764
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009765OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9766 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009767 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009768 SourceLocation NameModifierLoc,
9769 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009770 SourceLocation EndLoc) {
9771 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009772 Stmt *HelperValStmt = nullptr;
9773 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009774 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9775 !Condition->isInstantiationDependent() &&
9776 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009777 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009778 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009779 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009780
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009781 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009782
9783 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9784 CaptureRegion =
9785 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009786 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009787 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009788 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009789 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9790 HelperValStmt = buildPreInits(Context, Captures);
9791 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009792 }
9793
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009794 return new (Context)
9795 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9796 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009797}
9798
Alexey Bataev3778b602014-07-17 07:32:53 +00009799OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9800 SourceLocation StartLoc,
9801 SourceLocation LParenLoc,
9802 SourceLocation EndLoc) {
9803 Expr *ValExpr = Condition;
9804 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9805 !Condition->isInstantiationDependent() &&
9806 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009807 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009808 if (Val.isInvalid())
9809 return nullptr;
9810
Richard Smith03a4aa32016-06-23 19:02:52 +00009811 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009812 }
9813
9814 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9815}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009816ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9817 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009818 if (!Op)
9819 return ExprError();
9820
9821 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9822 public:
9823 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009824 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009825 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9826 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009827 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9828 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009829 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9830 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009831 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9832 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009833 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9834 QualType T,
9835 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009836 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9837 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009838 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9839 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009840 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009841 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009842 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009843 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9844 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009845 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9846 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009847 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9848 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009849 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009850 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009851 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009852 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9853 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009854 llvm_unreachable("conversion functions are permitted");
9855 }
9856 } ConvertDiagnoser;
9857 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9858}
9859
Alexey Bataeve3727102018-04-18 15:57:46 +00009860static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009861 OpenMPClauseKind CKind,
9862 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009863 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9864 !ValExpr->isInstantiationDependent()) {
9865 SourceLocation Loc = ValExpr->getExprLoc();
9866 ExprResult Value =
9867 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9868 if (Value.isInvalid())
9869 return false;
9870
9871 ValExpr = Value.get();
9872 // The expression must evaluate to a non-negative integer value.
9873 llvm::APSInt Result;
9874 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009875 Result.isSigned() &&
9876 !((!StrictlyPositive && Result.isNonNegative()) ||
9877 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009878 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009879 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9880 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009881 return false;
9882 }
9883 }
9884 return true;
9885}
9886
Alexey Bataev568a8332014-03-06 06:15:19 +00009887OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9888 SourceLocation StartLoc,
9889 SourceLocation LParenLoc,
9890 SourceLocation EndLoc) {
9891 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009892 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009893
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009894 // OpenMP [2.5, Restrictions]
9895 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009896 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009897 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009898 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009899
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009900 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009901 OpenMPDirectiveKind CaptureRegion =
9902 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9903 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009904 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009905 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009906 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9907 HelperValStmt = buildPreInits(Context, Captures);
9908 }
9909
9910 return new (Context) OMPNumThreadsClause(
9911 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009912}
9913
Alexey Bataev62c87d22014-03-21 04:51:18 +00009914ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009915 OpenMPClauseKind CKind,
9916 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009917 if (!E)
9918 return ExprError();
9919 if (E->isValueDependent() || E->isTypeDependent() ||
9920 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009921 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009922 llvm::APSInt Result;
9923 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9924 if (ICE.isInvalid())
9925 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009926 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9927 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009928 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009929 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9930 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009931 return ExprError();
9932 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009933 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9934 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9935 << E->getSourceRange();
9936 return ExprError();
9937 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009938 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9939 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009940 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009941 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009942 return ICE;
9943}
9944
9945OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9946 SourceLocation LParenLoc,
9947 SourceLocation EndLoc) {
9948 // OpenMP [2.8.1, simd construct, Description]
9949 // The parameter of the safelen clause must be a constant
9950 // positive integer expression.
9951 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9952 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009953 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009954 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009955 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009956}
9957
Alexey Bataev66b15b52015-08-21 11:14:16 +00009958OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9959 SourceLocation LParenLoc,
9960 SourceLocation EndLoc) {
9961 // OpenMP [2.8.1, simd construct, Description]
9962 // The parameter of the simdlen clause must be a constant
9963 // positive integer expression.
9964 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9965 if (Simdlen.isInvalid())
9966 return nullptr;
9967 return new (Context)
9968 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9969}
9970
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009971/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009972static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9973 DSAStackTy *Stack) {
9974 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009975 if (!OMPAllocatorHandleT.isNull())
9976 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009977 // Build the predefined allocator expressions.
9978 bool ErrorFound = false;
9979 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9980 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9981 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9982 StringRef Allocator =
9983 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9984 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9985 auto *VD = dyn_cast_or_null<ValueDecl>(
9986 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9987 if (!VD) {
9988 ErrorFound = true;
9989 break;
9990 }
9991 QualType AllocatorType =
9992 VD->getType().getNonLValueExprType(S.getASTContext());
9993 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9994 if (!Res.isUsable()) {
9995 ErrorFound = true;
9996 break;
9997 }
9998 if (OMPAllocatorHandleT.isNull())
9999 OMPAllocatorHandleT = AllocatorType;
10000 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
10001 ErrorFound = true;
10002 break;
10003 }
10004 Stack->setAllocator(AllocatorKind, Res.get());
10005 }
10006 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010007 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
10008 return false;
10009 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000010010 OMPAllocatorHandleT.addConst();
10011 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010012 return true;
10013}
10014
10015OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
10016 SourceLocation LParenLoc,
10017 SourceLocation EndLoc) {
10018 // OpenMP [2.11.3, allocate Directive, Description]
10019 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010020 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010021 return nullptr;
10022
10023 ExprResult Allocator = DefaultLvalueConversion(A);
10024 if (Allocator.isInvalid())
10025 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010026 Allocator = PerformImplicitConversion(Allocator.get(),
10027 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010028 Sema::AA_Initializing,
10029 /*AllowExplicit=*/true);
10030 if (Allocator.isInvalid())
10031 return nullptr;
10032 return new (Context)
10033 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
10034}
10035
Alexander Musman64d33f12014-06-04 07:53:32 +000010036OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
10037 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000010038 SourceLocation LParenLoc,
10039 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000010040 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010041 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000010042 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010043 // The parameter of the collapse clause must be a constant
10044 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000010045 ExprResult NumForLoopsResult =
10046 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
10047 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000010048 return nullptr;
10049 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000010050 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000010051}
10052
Alexey Bataev10e775f2015-07-30 11:36:16 +000010053OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
10054 SourceLocation EndLoc,
10055 SourceLocation LParenLoc,
10056 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000010057 // OpenMP [2.7.1, loop construct, Description]
10058 // OpenMP [2.8.1, simd construct, Description]
10059 // OpenMP [2.9.6, distribute construct, Description]
10060 // The parameter of the ordered clause must be a constant
10061 // positive integer expression if any.
10062 if (NumForLoops && LParenLoc.isValid()) {
10063 ExprResult NumForLoopsResult =
10064 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
10065 if (NumForLoopsResult.isInvalid())
10066 return nullptr;
10067 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010068 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000010069 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010070 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000010071 auto *Clause = OMPOrderedClause::Create(
10072 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
10073 StartLoc, LParenLoc, EndLoc);
10074 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
10075 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010076}
10077
Alexey Bataeved09d242014-05-28 05:53:51 +000010078OMPClause *Sema::ActOnOpenMPSimpleClause(
10079 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
10080 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010081 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010082 switch (Kind) {
10083 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010084 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000010085 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
10086 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010087 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010088 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000010089 Res = ActOnOpenMPProcBindClause(
10090 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
10091 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010092 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010093 case OMPC_atomic_default_mem_order:
10094 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
10095 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
10096 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10097 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010098 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010099 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010100 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010101 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010102 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010103 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010104 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010105 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010106 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010107 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010108 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010109 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010110 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010111 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010112 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010113 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010114 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010115 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010116 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010117 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010118 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010119 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010120 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010121 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010122 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010123 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010124 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010125 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010126 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010127 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010128 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010129 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010130 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010131 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010132 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010133 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010134 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010135 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010136 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010137 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010138 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010139 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010140 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010141 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010142 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010143 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010144 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010145 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010146 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010147 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010148 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010149 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010150 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010151 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010152 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010153 llvm_unreachable("Clause is not allowed.");
10154 }
10155 return Res;
10156}
10157
Alexey Bataev6402bca2015-12-28 07:25:51 +000010158static std::string
10159getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
10160 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010161 SmallString<256> Buffer;
10162 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000010163 unsigned Bound = Last >= 2 ? Last - 2 : 0;
10164 unsigned Skipped = Exclude.size();
10165 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000010166 for (unsigned I = First; I < Last; ++I) {
10167 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010168 --Skipped;
10169 continue;
10170 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010171 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
10172 if (I == Bound - Skipped)
10173 Out << " or ";
10174 else if (I != Bound + 1 - Skipped)
10175 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000010176 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010177 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000010178}
10179
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010180OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10181 SourceLocation KindKwLoc,
10182 SourceLocation StartLoc,
10183 SourceLocation LParenLoc,
10184 SourceLocation EndLoc) {
10185 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000010186 static_assert(OMPC_DEFAULT_unknown > 0,
10187 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010188 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010189 << getListOfPossibleValues(OMPC_default, /*First=*/0,
10190 /*Last=*/OMPC_DEFAULT_unknown)
10191 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010192 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010193 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000010194 switch (Kind) {
10195 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010196 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010197 break;
10198 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010199 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010200 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010201 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010202 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000010203 break;
10204 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010205 return new (Context)
10206 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010207}
10208
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010209OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
10210 SourceLocation KindKwLoc,
10211 SourceLocation StartLoc,
10212 SourceLocation LParenLoc,
10213 SourceLocation EndLoc) {
10214 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010215 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010216 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
10217 /*Last=*/OMPC_PROC_BIND_unknown)
10218 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010219 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010220 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010221 return new (Context)
10222 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010223}
10224
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010225OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
10226 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
10227 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
10228 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
10229 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10230 << getListOfPossibleValues(
10231 OMPC_atomic_default_mem_order, /*First=*/0,
10232 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
10233 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
10234 return nullptr;
10235 }
10236 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
10237 LParenLoc, EndLoc);
10238}
10239
Alexey Bataev56dafe82014-06-20 07:16:17 +000010240OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010241 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010242 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010243 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010244 SourceLocation EndLoc) {
10245 OMPClause *Res = nullptr;
10246 switch (Kind) {
10247 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010248 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
10249 assert(Argument.size() == NumberOfElements &&
10250 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010251 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010252 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
10253 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
10254 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
10255 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
10256 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010257 break;
10258 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010259 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
10260 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
10261 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
10262 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010263 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010264 case OMPC_dist_schedule:
10265 Res = ActOnOpenMPDistScheduleClause(
10266 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
10267 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
10268 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010269 case OMPC_defaultmap:
10270 enum { Modifier, DefaultmapKind };
10271 Res = ActOnOpenMPDefaultmapClause(
10272 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
10273 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000010274 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
10275 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010276 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000010277 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010278 case OMPC_num_threads:
10279 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010280 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010281 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010282 case OMPC_collapse:
10283 case OMPC_default:
10284 case OMPC_proc_bind:
10285 case OMPC_private:
10286 case OMPC_firstprivate:
10287 case OMPC_lastprivate:
10288 case OMPC_shared:
10289 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010290 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010291 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010292 case OMPC_linear:
10293 case OMPC_aligned:
10294 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010295 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010296 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010297 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010298 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010299 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010300 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010301 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010302 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010303 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010304 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010305 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010306 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010307 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010308 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010309 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010310 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010311 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010312 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010313 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010314 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010315 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010316 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010317 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010318 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010319 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010320 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010321 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010322 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010323 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010324 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010325 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010326 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010327 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010328 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010329 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010330 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010331 llvm_unreachable("Clause is not allowed.");
10332 }
10333 return Res;
10334}
10335
Alexey Bataev6402bca2015-12-28 07:25:51 +000010336static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
10337 OpenMPScheduleClauseModifier M2,
10338 SourceLocation M1Loc, SourceLocation M2Loc) {
10339 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
10340 SmallVector<unsigned, 2> Excluded;
10341 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
10342 Excluded.push_back(M2);
10343 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
10344 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
10345 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
10346 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
10347 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
10348 << getListOfPossibleValues(OMPC_schedule,
10349 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
10350 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10351 Excluded)
10352 << getOpenMPClauseName(OMPC_schedule);
10353 return true;
10354 }
10355 return false;
10356}
10357
Alexey Bataev56dafe82014-06-20 07:16:17 +000010358OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010359 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010360 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010361 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10362 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
10363 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
10364 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
10365 return nullptr;
10366 // OpenMP, 2.7.1, Loop Construct, Restrictions
10367 // Either the monotonic modifier or the nonmonotonic modifier can be specified
10368 // but not both.
10369 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
10370 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
10371 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
10372 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
10373 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
10374 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
10375 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
10376 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
10377 return nullptr;
10378 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010379 if (Kind == OMPC_SCHEDULE_unknown) {
10380 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000010381 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
10382 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
10383 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10384 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10385 Exclude);
10386 } else {
10387 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10388 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010389 }
10390 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10391 << Values << getOpenMPClauseName(OMPC_schedule);
10392 return nullptr;
10393 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000010394 // OpenMP, 2.7.1, Loop Construct, Restrictions
10395 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
10396 // schedule(guided).
10397 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
10398 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
10399 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
10400 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
10401 diag::err_omp_schedule_nonmonotonic_static);
10402 return nullptr;
10403 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010404 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010405 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000010406 if (ChunkSize) {
10407 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10408 !ChunkSize->isInstantiationDependent() &&
10409 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010410 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000010411 ExprResult Val =
10412 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10413 if (Val.isInvalid())
10414 return nullptr;
10415
10416 ValExpr = Val.get();
10417
10418 // OpenMP [2.7.1, Restrictions]
10419 // chunk_size must be a loop invariant integer expression with a positive
10420 // value.
10421 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000010422 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10423 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10424 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000010425 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000010426 return nullptr;
10427 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000010428 } else if (getOpenMPCaptureRegionForClause(
10429 DSAStack->getCurrentDirective(), OMPC_schedule) !=
10430 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010431 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010432 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010433 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000010434 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10435 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010436 }
10437 }
10438 }
10439
Alexey Bataev6402bca2015-12-28 07:25:51 +000010440 return new (Context)
10441 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000010442 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010443}
10444
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010445OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
10446 SourceLocation StartLoc,
10447 SourceLocation EndLoc) {
10448 OMPClause *Res = nullptr;
10449 switch (Kind) {
10450 case OMPC_ordered:
10451 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
10452 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000010453 case OMPC_nowait:
10454 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
10455 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010456 case OMPC_untied:
10457 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
10458 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010459 case OMPC_mergeable:
10460 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
10461 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010462 case OMPC_read:
10463 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
10464 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000010465 case OMPC_write:
10466 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
10467 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000010468 case OMPC_update:
10469 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
10470 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000010471 case OMPC_capture:
10472 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
10473 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010474 case OMPC_seq_cst:
10475 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
10476 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000010477 case OMPC_threads:
10478 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
10479 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010480 case OMPC_simd:
10481 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
10482 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000010483 case OMPC_nogroup:
10484 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
10485 break;
Kelvin Li1408f912018-09-26 04:28:39 +000010486 case OMPC_unified_address:
10487 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
10488 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000010489 case OMPC_unified_shared_memory:
10490 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10491 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010492 case OMPC_reverse_offload:
10493 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
10494 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010495 case OMPC_dynamic_allocators:
10496 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
10497 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010498 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010499 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010500 case OMPC_num_threads:
10501 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010502 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010503 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010504 case OMPC_collapse:
10505 case OMPC_schedule:
10506 case OMPC_private:
10507 case OMPC_firstprivate:
10508 case OMPC_lastprivate:
10509 case OMPC_shared:
10510 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010511 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010512 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010513 case OMPC_linear:
10514 case OMPC_aligned:
10515 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010516 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010517 case OMPC_default:
10518 case OMPC_proc_bind:
10519 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010520 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010521 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010522 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010523 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010524 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010525 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010526 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010527 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010528 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000010529 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010530 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010531 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010532 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010533 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010534 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010535 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010536 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010537 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010538 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010539 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010540 llvm_unreachable("Clause is not allowed.");
10541 }
10542 return Res;
10543}
10544
Alexey Bataev236070f2014-06-20 11:19:47 +000010545OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10546 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000010547 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000010548 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10549}
10550
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010551OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10552 SourceLocation EndLoc) {
10553 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10554}
10555
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010556OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10557 SourceLocation EndLoc) {
10558 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10559}
10560
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010561OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10562 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010563 return new (Context) OMPReadClause(StartLoc, EndLoc);
10564}
10565
Alexey Bataevdea47612014-07-23 07:46:59 +000010566OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10567 SourceLocation EndLoc) {
10568 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10569}
10570
Alexey Bataev67a4f222014-07-23 10:25:33 +000010571OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10572 SourceLocation EndLoc) {
10573 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10574}
10575
Alexey Bataev459dec02014-07-24 06:46:57 +000010576OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10577 SourceLocation EndLoc) {
10578 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10579}
10580
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010581OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10582 SourceLocation EndLoc) {
10583 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10584}
10585
Alexey Bataev346265e2015-09-25 10:37:12 +000010586OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10587 SourceLocation EndLoc) {
10588 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10589}
10590
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010591OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10592 SourceLocation EndLoc) {
10593 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10594}
10595
Alexey Bataevb825de12015-12-07 10:51:44 +000010596OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10597 SourceLocation EndLoc) {
10598 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10599}
10600
Kelvin Li1408f912018-09-26 04:28:39 +000010601OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10602 SourceLocation EndLoc) {
10603 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10604}
10605
Patrick Lyster4a370b92018-10-01 13:47:43 +000010606OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10607 SourceLocation EndLoc) {
10608 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10609}
10610
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010611OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10612 SourceLocation EndLoc) {
10613 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10614}
10615
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010616OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10617 SourceLocation EndLoc) {
10618 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10619}
10620
Alexey Bataevc5e02582014-06-16 07:08:35 +000010621OMPClause *Sema::ActOnOpenMPVarListClause(
10622 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010623 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10624 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10625 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010626 OpenMPLinearClauseKind LinKind,
10627 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010628 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10629 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10630 SourceLocation StartLoc = Locs.StartLoc;
10631 SourceLocation LParenLoc = Locs.LParenLoc;
10632 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010633 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010634 switch (Kind) {
10635 case OMPC_private:
10636 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10637 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010638 case OMPC_firstprivate:
10639 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10640 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010641 case OMPC_lastprivate:
10642 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10643 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010644 case OMPC_shared:
10645 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10646 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010647 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010648 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010649 EndLoc, ReductionOrMapperIdScopeSpec,
10650 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010651 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010652 case OMPC_task_reduction:
10653 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010654 EndLoc, ReductionOrMapperIdScopeSpec,
10655 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010656 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010657 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010658 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10659 EndLoc, ReductionOrMapperIdScopeSpec,
10660 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010661 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010662 case OMPC_linear:
10663 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010664 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010665 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010666 case OMPC_aligned:
10667 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10668 ColonLoc, EndLoc);
10669 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010670 case OMPC_copyin:
10671 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10672 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010673 case OMPC_copyprivate:
10674 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10675 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010676 case OMPC_flush:
10677 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10678 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010679 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010680 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010681 StartLoc, LParenLoc, EndLoc);
10682 break;
10683 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010684 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10685 ReductionOrMapperIdScopeSpec,
10686 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10687 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010688 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010689 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010690 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10691 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010692 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010693 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010694 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10695 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010696 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010697 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010698 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010699 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010700 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010701 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010702 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000010703 case OMPC_allocate:
10704 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10705 ColonLoc, EndLoc);
10706 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010707 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010708 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010709 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010710 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010711 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010712 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010713 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010714 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010715 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010716 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010717 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010718 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010719 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010720 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010721 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010722 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010723 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010724 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010725 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010726 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010727 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010728 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010729 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010730 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010731 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010732 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010733 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010734 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010735 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010736 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010737 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010738 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010739 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010740 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010741 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010742 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010743 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010744 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010745 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010746 llvm_unreachable("Clause is not allowed.");
10747 }
10748 return Res;
10749}
10750
Alexey Bataev90c228f2016-02-08 09:29:13 +000010751ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010752 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010753 ExprResult Res = BuildDeclRefExpr(
10754 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10755 if (!Res.isUsable())
10756 return ExprError();
10757 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10758 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10759 if (!Res.isUsable())
10760 return ExprError();
10761 }
10762 if (VK != VK_LValue && Res.get()->isGLValue()) {
10763 Res = DefaultLvalueConversion(Res.get());
10764 if (!Res.isUsable())
10765 return ExprError();
10766 }
10767 return Res;
10768}
10769
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010770OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10771 SourceLocation StartLoc,
10772 SourceLocation LParenLoc,
10773 SourceLocation EndLoc) {
10774 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010775 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010776 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010777 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010778 SourceLocation ELoc;
10779 SourceRange ERange;
10780 Expr *SimpleRefExpr = RefExpr;
10781 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010782 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010783 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010784 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010785 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010786 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010787 ValueDecl *D = Res.first;
10788 if (!D)
10789 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010790
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010791 QualType Type = D->getType();
10792 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010793
10794 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10795 // A variable that appears in a private clause must not have an incomplete
10796 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010797 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010798 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010799 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010800
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010801 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10802 // A variable that is privatized must not have a const-qualified type
10803 // unless it is of class type with a mutable member. This restriction does
10804 // not apply to the firstprivate clause.
10805 //
10806 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10807 // A variable that appears in a private clause must not have a
10808 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010809 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010810 continue;
10811
Alexey Bataev758e55e2013-09-06 18:03:48 +000010812 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10813 // in a Construct]
10814 // Variables with the predetermined data-sharing attributes may not be
10815 // listed in data-sharing attributes clauses, except for the cases
10816 // listed below. For these exceptions only, listing a predetermined
10817 // variable in a data-sharing attribute clause is allowed and overrides
10818 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010819 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010820 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010821 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10822 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010823 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010824 continue;
10825 }
10826
Alexey Bataeve3727102018-04-18 15:57:46 +000010827 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010828 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010829 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010830 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010831 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10832 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010833 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010834 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010835 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010836 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010837 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010838 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010839 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010840 continue;
10841 }
10842
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010843 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10844 // A list item cannot appear in both a map clause and a data-sharing
10845 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010846 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010847 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010848 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010849 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010850 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10851 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10852 ConflictKind = WhereFoundClauseKind;
10853 return true;
10854 })) {
10855 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010856 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010857 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010858 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010859 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010860 continue;
10861 }
10862 }
10863
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010864 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10865 // A variable of class type (or array thereof) that appears in a private
10866 // clause requires an accessible, unambiguous default constructor for the
10867 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010868 // Generate helper private variable and initialize it with the default
10869 // value. The address of the original variable is replaced by the address of
10870 // the new private variable in CodeGen. This new variable is not added to
10871 // IdResolver, so the code in the OpenMP region uses original variable for
10872 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010873 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010874 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010875 buildVarDecl(*this, ELoc, Type, D->getName(),
10876 D->hasAttrs() ? &D->getAttrs() : nullptr,
10877 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010878 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010879 if (VDPrivate->isInvalidDecl())
10880 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010881 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010882 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010883
Alexey Bataev90c228f2016-02-08 09:29:13 +000010884 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010885 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010886 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010887 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010888 Vars.push_back((VD || CurContext->isDependentContext())
10889 ? RefExpr->IgnoreParens()
10890 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010891 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010892 }
10893
Alexey Bataeved09d242014-05-28 05:53:51 +000010894 if (Vars.empty())
10895 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010896
Alexey Bataev03b340a2014-10-21 03:16:40 +000010897 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10898 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010899}
10900
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010901namespace {
10902class DiagsUninitializedSeveretyRAII {
10903private:
10904 DiagnosticsEngine &Diags;
10905 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010906 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010907
10908public:
10909 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10910 bool IsIgnored)
10911 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10912 if (!IsIgnored) {
10913 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10914 /*Map*/ diag::Severity::Ignored, Loc);
10915 }
10916 }
10917 ~DiagsUninitializedSeveretyRAII() {
10918 if (!IsIgnored)
10919 Diags.popMappings(SavedLoc);
10920 }
10921};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010922}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010923
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010924OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10925 SourceLocation StartLoc,
10926 SourceLocation LParenLoc,
10927 SourceLocation EndLoc) {
10928 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010929 SmallVector<Expr *, 8> PrivateCopies;
10930 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010931 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010932 bool IsImplicitClause =
10933 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010934 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010935
Alexey Bataeve3727102018-04-18 15:57:46 +000010936 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010937 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010938 SourceLocation ELoc;
10939 SourceRange ERange;
10940 Expr *SimpleRefExpr = RefExpr;
10941 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010942 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010943 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010944 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010945 PrivateCopies.push_back(nullptr);
10946 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010947 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010948 ValueDecl *D = Res.first;
10949 if (!D)
10950 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010951
Alexey Bataev60da77e2016-02-29 05:54:20 +000010952 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010953 QualType Type = D->getType();
10954 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010955
10956 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10957 // A variable that appears in a private clause must not have an incomplete
10958 // type or a reference type.
10959 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010960 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010961 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010962 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010963
10964 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10965 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010966 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010967 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010968 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010969
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010970 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010971 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010972 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010973 DSAStackTy::DSAVarData DVar =
10974 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010975 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010976 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010977 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010978 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10979 // A list item that specifies a given variable may not appear in more
10980 // than one clause on the same directive, except that a variable may be
10981 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010982 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10983 // A list item may appear in a firstprivate or lastprivate clause but not
10984 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010985 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010986 (isOpenMPDistributeDirective(CurrDir) ||
10987 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010988 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010989 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010990 << getOpenMPClauseName(DVar.CKind)
10991 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010992 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010993 continue;
10994 }
10995
10996 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10997 // in a Construct]
10998 // Variables with the predetermined data-sharing attributes may not be
10999 // listed in data-sharing attributes clauses, except for the cases
11000 // listed below. For these exceptions only, listing a predetermined
11001 // variable in a data-sharing attribute clause is allowed and overrides
11002 // the variable's predetermined data-sharing attributes.
11003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11004 // in a Construct, C/C++, p.2]
11005 // Variables with const-qualified type having no mutable member may be
11006 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000011007 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011008 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
11009 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011010 << getOpenMPClauseName(DVar.CKind)
11011 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011012 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011013 continue;
11014 }
11015
11016 // OpenMP [2.9.3.4, Restrictions, p.2]
11017 // A list item that is private within a parallel region must not appear
11018 // in a firstprivate clause on a worksharing construct if any of the
11019 // worksharing regions arising from the worksharing construct ever bind
11020 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011021 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11022 // A list item that is private within a teams region must not appear in a
11023 // firstprivate clause on a distribute construct if any of the distribute
11024 // regions arising from the distribute construct ever bind to any of the
11025 // teams regions arising from the teams construct.
11026 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11027 // A list item that appears in a reduction clause of a teams construct
11028 // must not appear in a firstprivate clause on a distribute construct if
11029 // any of the distribute regions arising from the distribute construct
11030 // ever bind to any of the teams regions arising from the teams construct.
11031 if ((isOpenMPWorksharingDirective(CurrDir) ||
11032 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011033 !isOpenMPParallelDirective(CurrDir) &&
11034 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011035 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011036 if (DVar.CKind != OMPC_shared &&
11037 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011038 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011039 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000011040 Diag(ELoc, diag::err_omp_required_access)
11041 << getOpenMPClauseName(OMPC_firstprivate)
11042 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011043 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011044 continue;
11045 }
11046 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011047 // OpenMP [2.9.3.4, Restrictions, p.3]
11048 // A list item that appears in a reduction clause of a parallel construct
11049 // must not appear in a firstprivate clause on a worksharing or task
11050 // construct if any of the worksharing or task regions arising from the
11051 // worksharing or task construct ever bind to any of the parallel regions
11052 // arising from the parallel construct.
11053 // OpenMP [2.9.3.4, Restrictions, p.4]
11054 // A list item that appears in a reduction clause in worksharing
11055 // construct must not appear in a firstprivate clause in a task construct
11056 // encountered during execution of any of the worksharing regions arising
11057 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000011058 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011059 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011060 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
11061 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011062 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011063 isOpenMPWorksharingDirective(K) ||
11064 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011065 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011066 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011067 if (DVar.CKind == OMPC_reduction &&
11068 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011069 isOpenMPWorksharingDirective(DVar.DKind) ||
11070 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011071 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
11072 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000011073 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011074 continue;
11075 }
11076 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000011077
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011078 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11079 // A list item cannot appear in both a map clause and a data-sharing
11080 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000011081 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011082 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011083 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011084 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000011085 [&ConflictKind](
11086 OMPClauseMappableExprCommon::MappableExprComponentListRef,
11087 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000011088 ConflictKind = WhereFoundClauseKind;
11089 return true;
11090 })) {
11091 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011092 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000011093 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011094 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000011095 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011096 continue;
11097 }
11098 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011099 }
11100
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011101 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011102 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000011103 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011104 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11105 << getOpenMPClauseName(OMPC_firstprivate) << Type
11106 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11107 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011108 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011109 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011110 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011111 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000011112 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011113 continue;
11114 }
11115
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011116 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011117 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011118 buildVarDecl(*this, ELoc, Type, D->getName(),
11119 D->hasAttrs() ? &D->getAttrs() : nullptr,
11120 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011121 // Generate helper private variable and initialize it with the value of the
11122 // original variable. The address of the original variable is replaced by
11123 // the address of the new private variable in the CodeGen. This new variable
11124 // is not added to IdResolver, so the code in the OpenMP region uses
11125 // original variable for proper diagnostics and variable capturing.
11126 Expr *VDInitRefExpr = nullptr;
11127 // For arrays generate initializer for single element and replace it by the
11128 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011129 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011130 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011131 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011132 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011133 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011134 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011135 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
11136 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000011137 InitializedEntity Entity =
11138 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011139 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
11140
11141 InitializationSequence InitSeq(*this, Entity, Kind, Init);
11142 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
11143 if (Result.isInvalid())
11144 VDPrivate->setInvalidDecl();
11145 else
11146 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011147 // Remove temp variable declaration.
11148 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011149 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000011150 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
11151 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000011152 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11153 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000011154 AddInitializerToDecl(VDPrivate,
11155 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011156 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011157 }
11158 if (VDPrivate->isInvalidDecl()) {
11159 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011160 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011161 diag::note_omp_task_predetermined_firstprivate_here);
11162 }
11163 continue;
11164 }
11165 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011166 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000011167 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
11168 RefExpr->getExprLoc());
11169 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011170 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011171 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011172 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011173 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011174 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011175 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011176 ExprCaptures.push_back(Ref->getDecl());
11177 }
Alexey Bataev417089f2016-02-17 13:19:37 +000011178 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011179 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011180 Vars.push_back((VD || CurContext->isDependentContext())
11181 ? RefExpr->IgnoreParens()
11182 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011183 PrivateCopies.push_back(VDPrivateRefExpr);
11184 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011185 }
11186
Alexey Bataeved09d242014-05-28 05:53:51 +000011187 if (Vars.empty())
11188 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011189
11190 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011191 Vars, PrivateCopies, Inits,
11192 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011193}
11194
Alexander Musman1bb328c2014-06-04 13:06:39 +000011195OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
11196 SourceLocation StartLoc,
11197 SourceLocation LParenLoc,
11198 SourceLocation EndLoc) {
11199 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000011200 SmallVector<Expr *, 8> SrcExprs;
11201 SmallVector<Expr *, 8> DstExprs;
11202 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000011203 SmallVector<Decl *, 4> ExprCaptures;
11204 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000011205 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011206 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011207 SourceLocation ELoc;
11208 SourceRange ERange;
11209 Expr *SimpleRefExpr = RefExpr;
11210 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000011211 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011212 // It will be analyzed later.
11213 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011214 SrcExprs.push_back(nullptr);
11215 DstExprs.push_back(nullptr);
11216 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011217 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011218 ValueDecl *D = Res.first;
11219 if (!D)
11220 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011221
Alexey Bataev74caaf22016-02-20 04:09:36 +000011222 QualType Type = D->getType();
11223 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011224
11225 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
11226 // A variable that appears in a lastprivate clause must not have an
11227 // incomplete type or a reference type.
11228 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000011229 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000011230 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011231 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011232
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011233 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11234 // A variable that is privatized must not have a const-qualified type
11235 // unless it is of class type with a mutable member. This restriction does
11236 // not apply to the firstprivate clause.
11237 //
11238 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
11239 // A variable that appears in a lastprivate clause must not have a
11240 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011241 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011242 continue;
11243
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011244 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011245 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11246 // in a Construct]
11247 // Variables with the predetermined data-sharing attributes may not be
11248 // listed in data-sharing attributes clauses, except for the cases
11249 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011250 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11251 // A list item may appear in a firstprivate or lastprivate clause but not
11252 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000011253 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011254 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011255 (isOpenMPDistributeDirective(CurrDir) ||
11256 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000011257 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
11258 Diag(ELoc, diag::err_omp_wrong_dsa)
11259 << getOpenMPClauseName(DVar.CKind)
11260 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011261 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011262 continue;
11263 }
11264
Alexey Bataevf29276e2014-06-18 04:14:57 +000011265 // OpenMP [2.14.3.5, Restrictions, p.2]
11266 // A list item that is private within a parallel region, or that appears in
11267 // the reduction clause of a parallel construct, must not appear in a
11268 // lastprivate clause on a worksharing construct if any of the corresponding
11269 // worksharing regions ever binds to any of the corresponding parallel
11270 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000011271 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000011272 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011273 !isOpenMPParallelDirective(CurrDir) &&
11274 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000011275 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011276 if (DVar.CKind != OMPC_shared) {
11277 Diag(ELoc, diag::err_omp_required_access)
11278 << getOpenMPClauseName(OMPC_lastprivate)
11279 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011280 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011281 continue;
11282 }
11283 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011284
Alexander Musman1bb328c2014-06-04 13:06:39 +000011285 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000011286 // A variable of class type (or array thereof) that appears in a
11287 // lastprivate clause requires an accessible, unambiguous default
11288 // constructor for the class type, unless the list item is also specified
11289 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000011290 // A variable of class type (or array thereof) that appears in a
11291 // lastprivate clause requires an accessible, unambiguous copy assignment
11292 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000011293 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011294 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
11295 Type.getUnqualifiedType(), ".lastprivate.src",
11296 D->hasAttrs() ? &D->getAttrs() : nullptr);
11297 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000011298 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011299 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011300 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000011301 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011302 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000011303 // For arrays generate assignment operation for single element and replace
11304 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000011305 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
11306 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011307 if (AssignmentOp.isInvalid())
11308 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011309 AssignmentOp =
11310 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000011311 if (AssignmentOp.isInvalid())
11312 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011313
Alexey Bataev74caaf22016-02-20 04:09:36 +000011314 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011315 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011316 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011317 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011318 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011319 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011320 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011321 ExprCaptures.push_back(Ref->getDecl());
11322 }
11323 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000011324 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011325 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011326 ExprResult RefRes = DefaultLvalueConversion(Ref);
11327 if (!RefRes.isUsable())
11328 continue;
11329 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011330 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11331 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011332 if (!PostUpdateRes.isUsable())
11333 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011334 ExprPostUpdates.push_back(
11335 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011336 }
11337 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011338 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011339 Vars.push_back((VD || CurContext->isDependentContext())
11340 ? RefExpr->IgnoreParens()
11341 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000011342 SrcExprs.push_back(PseudoSrcExpr);
11343 DstExprs.push_back(PseudoDstExpr);
11344 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000011345 }
11346
11347 if (Vars.empty())
11348 return nullptr;
11349
11350 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000011351 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011352 buildPreInits(Context, ExprCaptures),
11353 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000011354}
11355
Alexey Bataev758e55e2013-09-06 18:03:48 +000011356OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11357 SourceLocation StartLoc,
11358 SourceLocation LParenLoc,
11359 SourceLocation EndLoc) {
11360 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011361 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011362 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011363 SourceLocation ELoc;
11364 SourceRange ERange;
11365 Expr *SimpleRefExpr = RefExpr;
11366 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011367 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000011368 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011369 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011370 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011371 ValueDecl *D = Res.first;
11372 if (!D)
11373 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011374
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011375 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011376 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11377 // in a Construct]
11378 // Variables with the predetermined data-sharing attributes may not be
11379 // listed in data-sharing attributes clauses, except for the cases
11380 // listed below. For these exceptions only, listing a predetermined
11381 // variable in a data-sharing attribute clause is allowed and overrides
11382 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011383 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000011384 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
11385 DVar.RefExpr) {
11386 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11387 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011388 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011389 continue;
11390 }
11391
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011392 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011393 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000011394 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011395 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011396 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
11397 ? RefExpr->IgnoreParens()
11398 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011399 }
11400
Alexey Bataeved09d242014-05-28 05:53:51 +000011401 if (Vars.empty())
11402 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011403
11404 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
11405}
11406
Alexey Bataevc5e02582014-06-16 07:08:35 +000011407namespace {
11408class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
11409 DSAStackTy *Stack;
11410
11411public:
11412 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011413 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
11414 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011415 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
11416 return false;
11417 if (DVar.CKind != OMPC_unknown)
11418 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011419 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011420 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011421 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011422 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011423 }
11424 return false;
11425 }
11426 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011427 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011428 if (Child && Visit(Child))
11429 return true;
11430 }
11431 return false;
11432 }
Alexey Bataev23b69422014-06-18 07:08:49 +000011433 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011434};
Alexey Bataev23b69422014-06-18 07:08:49 +000011435} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000011436
Alexey Bataev60da77e2016-02-29 05:54:20 +000011437namespace {
11438// Transform MemberExpression for specified FieldDecl of current class to
11439// DeclRefExpr to specified OMPCapturedExprDecl.
11440class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
11441 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000011442 ValueDecl *Field = nullptr;
11443 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011444
11445public:
11446 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
11447 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
11448
11449 ExprResult TransformMemberExpr(MemberExpr *E) {
11450 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
11451 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000011452 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011453 return CapturedExpr;
11454 }
11455 return BaseTransform::TransformMemberExpr(E);
11456 }
11457 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
11458};
11459} // namespace
11460
Alexey Bataev97d18bf2018-04-11 19:21:00 +000011461template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000011462static T filterLookupForUDReductionAndMapper(
11463 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011464 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011465 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011466 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011467 return Res;
11468 }
11469 }
11470 return T();
11471}
11472
Alexey Bataev43b90b72018-09-12 16:31:59 +000011473static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
11474 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
11475
11476 for (auto RD : D->redecls()) {
11477 // Don't bother with extra checks if we already know this one isn't visible.
11478 if (RD == D)
11479 continue;
11480
11481 auto ND = cast<NamedDecl>(RD);
11482 if (LookupResult::isVisible(SemaRef, ND))
11483 return ND;
11484 }
11485
11486 return nullptr;
11487}
11488
11489static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000011490argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000011491 SourceLocation Loc, QualType Ty,
11492 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11493 // Find all of the associated namespaces and classes based on the
11494 // arguments we have.
11495 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11496 Sema::AssociatedClassSet AssociatedClasses;
11497 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11498 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11499 AssociatedClasses);
11500
11501 // C++ [basic.lookup.argdep]p3:
11502 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11503 // and let Y be the lookup set produced by argument dependent
11504 // lookup (defined as follows). If X contains [...] then Y is
11505 // empty. Otherwise Y is the set of declarations found in the
11506 // namespaces associated with the argument types as described
11507 // below. The set of declarations found by the lookup of the name
11508 // is the union of X and Y.
11509 //
11510 // Here, we compute Y and add its members to the overloaded
11511 // candidate set.
11512 for (auto *NS : AssociatedNamespaces) {
11513 // When considering an associated namespace, the lookup is the
11514 // same as the lookup performed when the associated namespace is
11515 // used as a qualifier (3.4.3.2) except that:
11516 //
11517 // -- Any using-directives in the associated namespace are
11518 // ignored.
11519 //
11520 // -- Any namespace-scope friend functions declared in
11521 // associated classes are visible within their respective
11522 // namespaces even if they are not visible during an ordinary
11523 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011524 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011525 for (auto *D : R) {
11526 auto *Underlying = D;
11527 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11528 Underlying = USD->getTargetDecl();
11529
Michael Kruse4304e9d2019-02-19 16:38:20 +000011530 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11531 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011532 continue;
11533
11534 if (!SemaRef.isVisible(D)) {
11535 D = findAcceptableDecl(SemaRef, D);
11536 if (!D)
11537 continue;
11538 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11539 Underlying = USD->getTargetDecl();
11540 }
11541 Lookups.emplace_back();
11542 Lookups.back().addDecl(Underlying);
11543 }
11544 }
11545}
11546
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011547static ExprResult
11548buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11549 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11550 const DeclarationNameInfo &ReductionId, QualType Ty,
11551 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11552 if (ReductionIdScopeSpec.isInvalid())
11553 return ExprError();
11554 SmallVector<UnresolvedSet<8>, 4> Lookups;
11555 if (S) {
11556 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11557 Lookup.suppressDiagnostics();
11558 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011559 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011560 do {
11561 S = S->getParent();
11562 } while (S && !S->isDeclScope(D));
11563 if (S)
11564 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011565 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011566 Lookups.back().append(Lookup.begin(), Lookup.end());
11567 Lookup.clear();
11568 }
11569 } else if (auto *ULE =
11570 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11571 Lookups.push_back(UnresolvedSet<8>());
11572 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011573 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011574 if (D == PrevD)
11575 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011576 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011577 Lookups.back().addDecl(DRD);
11578 PrevD = D;
11579 }
11580 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011581 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11582 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011583 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011584 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011585 return !D->isInvalidDecl() &&
11586 (D->getType()->isDependentType() ||
11587 D->getType()->isInstantiationDependentType() ||
11588 D->getType()->containsUnexpandedParameterPack());
11589 })) {
11590 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011591 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011592 if (Set.empty())
11593 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011594 ResSet.append(Set.begin(), Set.end());
11595 // The last item marks the end of all declarations at the specified scope.
11596 ResSet.addDecl(Set[Set.size() - 1]);
11597 }
11598 return UnresolvedLookupExpr::Create(
11599 SemaRef.Context, /*NamingClass=*/nullptr,
11600 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11601 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11602 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011603 // Lookup inside the classes.
11604 // C++ [over.match.oper]p3:
11605 // For a unary operator @ with an operand of a type whose
11606 // cv-unqualified version is T1, and for a binary operator @ with
11607 // a left operand of a type whose cv-unqualified version is T1 and
11608 // a right operand of a type whose cv-unqualified version is T2,
11609 // three sets of candidate functions, designated member
11610 // candidates, non-member candidates and built-in candidates, are
11611 // constructed as follows:
11612 // -- If T1 is a complete class type or a class currently being
11613 // defined, the set of member candidates is the result of the
11614 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11615 // the set of member candidates is empty.
11616 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11617 Lookup.suppressDiagnostics();
11618 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11619 // Complete the type if it can be completed.
11620 // If the type is neither complete nor being defined, bail out now.
11621 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11622 TyRec->getDecl()->getDefinition()) {
11623 Lookup.clear();
11624 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11625 if (Lookup.empty()) {
11626 Lookups.emplace_back();
11627 Lookups.back().append(Lookup.begin(), Lookup.end());
11628 }
11629 }
11630 }
11631 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000011632 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000011633 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000011634 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11635 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11636 if (!D->isInvalidDecl() &&
11637 SemaRef.Context.hasSameType(D->getType(), Ty))
11638 return D;
11639 return nullptr;
11640 }))
11641 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11642 VK_LValue, Loc);
11643 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000011644 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11645 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11646 if (!D->isInvalidDecl() &&
11647 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11648 !Ty.isMoreQualifiedThan(D->getType()))
11649 return D;
11650 return nullptr;
11651 })) {
11652 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11653 /*DetectVirtual=*/false);
11654 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11655 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11656 VD->getType().getUnqualifiedType()))) {
11657 if (SemaRef.CheckBaseClassAccess(
11658 Loc, VD->getType(), Ty, Paths.front(),
11659 /*DiagID=*/0) != Sema::AR_inaccessible) {
11660 SemaRef.BuildBasePathArray(Paths, BasePath);
11661 return SemaRef.BuildDeclRefExpr(
11662 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11663 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011664 }
11665 }
11666 }
11667 }
11668 if (ReductionIdScopeSpec.isSet()) {
11669 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11670 return ExprError();
11671 }
11672 return ExprEmpty();
11673}
11674
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011675namespace {
11676/// Data for the reduction-based clauses.
11677struct ReductionData {
11678 /// List of original reduction items.
11679 SmallVector<Expr *, 8> Vars;
11680 /// List of private copies of the reduction items.
11681 SmallVector<Expr *, 8> Privates;
11682 /// LHS expressions for the reduction_op expressions.
11683 SmallVector<Expr *, 8> LHSs;
11684 /// RHS expressions for the reduction_op expressions.
11685 SmallVector<Expr *, 8> RHSs;
11686 /// Reduction operation expression.
11687 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011688 /// Taskgroup descriptors for the corresponding reduction items in
11689 /// in_reduction clauses.
11690 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011691 /// List of captures for clause.
11692 SmallVector<Decl *, 4> ExprCaptures;
11693 /// List of postupdate expressions.
11694 SmallVector<Expr *, 4> ExprPostUpdates;
11695 ReductionData() = delete;
11696 /// Reserves required memory for the reduction data.
11697 ReductionData(unsigned Size) {
11698 Vars.reserve(Size);
11699 Privates.reserve(Size);
11700 LHSs.reserve(Size);
11701 RHSs.reserve(Size);
11702 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011703 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011704 ExprCaptures.reserve(Size);
11705 ExprPostUpdates.reserve(Size);
11706 }
11707 /// Stores reduction item and reduction operation only (required for dependent
11708 /// reduction item).
11709 void push(Expr *Item, Expr *ReductionOp) {
11710 Vars.emplace_back(Item);
11711 Privates.emplace_back(nullptr);
11712 LHSs.emplace_back(nullptr);
11713 RHSs.emplace_back(nullptr);
11714 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011715 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011716 }
11717 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011718 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11719 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011720 Vars.emplace_back(Item);
11721 Privates.emplace_back(Private);
11722 LHSs.emplace_back(LHS);
11723 RHSs.emplace_back(RHS);
11724 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011725 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011726 }
11727};
11728} // namespace
11729
Alexey Bataeve3727102018-04-18 15:57:46 +000011730static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011731 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11732 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11733 const Expr *Length = OASE->getLength();
11734 if (Length == nullptr) {
11735 // For array sections of the form [1:] or [:], we would need to analyze
11736 // the lower bound...
11737 if (OASE->getColonLoc().isValid())
11738 return false;
11739
11740 // This is an array subscript which has implicit length 1!
11741 SingleElement = true;
11742 ArraySizes.push_back(llvm::APSInt::get(1));
11743 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011744 Expr::EvalResult Result;
11745 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011746 return false;
11747
Fangrui Song407659a2018-11-30 23:41:18 +000011748 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011749 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11750 ArraySizes.push_back(ConstantLengthValue);
11751 }
11752
11753 // Get the base of this array section and walk up from there.
11754 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11755
11756 // We require length = 1 for all array sections except the right-most to
11757 // guarantee that the memory region is contiguous and has no holes in it.
11758 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11759 Length = TempOASE->getLength();
11760 if (Length == nullptr) {
11761 // For array sections of the form [1:] or [:], we would need to analyze
11762 // the lower bound...
11763 if (OASE->getColonLoc().isValid())
11764 return false;
11765
11766 // This is an array subscript which has implicit length 1!
11767 ArraySizes.push_back(llvm::APSInt::get(1));
11768 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011769 Expr::EvalResult Result;
11770 if (!Length->EvaluateAsInt(Result, Context))
11771 return false;
11772
11773 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11774 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011775 return false;
11776
11777 ArraySizes.push_back(ConstantLengthValue);
11778 }
11779 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11780 }
11781
11782 // If we have a single element, we don't need to add the implicit lengths.
11783 if (!SingleElement) {
11784 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11785 // Has implicit length 1!
11786 ArraySizes.push_back(llvm::APSInt::get(1));
11787 Base = TempASE->getBase()->IgnoreParenImpCasts();
11788 }
11789 }
11790
11791 // This array section can be privatized as a single value or as a constant
11792 // sized array.
11793 return true;
11794}
11795
Alexey Bataeve3727102018-04-18 15:57:46 +000011796static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011797 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11798 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11799 SourceLocation ColonLoc, SourceLocation EndLoc,
11800 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011801 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011802 DeclarationName DN = ReductionId.getName();
11803 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011804 BinaryOperatorKind BOK = BO_Comma;
11805
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011806 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011807 // OpenMP [2.14.3.6, reduction clause]
11808 // C
11809 // reduction-identifier is either an identifier or one of the following
11810 // operators: +, -, *, &, |, ^, && and ||
11811 // C++
11812 // reduction-identifier is either an id-expression or one of the following
11813 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011814 switch (OOK) {
11815 case OO_Plus:
11816 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011817 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011818 break;
11819 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011820 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011821 break;
11822 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011823 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011824 break;
11825 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011826 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011827 break;
11828 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011829 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011830 break;
11831 case OO_AmpAmp:
11832 BOK = BO_LAnd;
11833 break;
11834 case OO_PipePipe:
11835 BOK = BO_LOr;
11836 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011837 case OO_New:
11838 case OO_Delete:
11839 case OO_Array_New:
11840 case OO_Array_Delete:
11841 case OO_Slash:
11842 case OO_Percent:
11843 case OO_Tilde:
11844 case OO_Exclaim:
11845 case OO_Equal:
11846 case OO_Less:
11847 case OO_Greater:
11848 case OO_LessEqual:
11849 case OO_GreaterEqual:
11850 case OO_PlusEqual:
11851 case OO_MinusEqual:
11852 case OO_StarEqual:
11853 case OO_SlashEqual:
11854 case OO_PercentEqual:
11855 case OO_CaretEqual:
11856 case OO_AmpEqual:
11857 case OO_PipeEqual:
11858 case OO_LessLess:
11859 case OO_GreaterGreater:
11860 case OO_LessLessEqual:
11861 case OO_GreaterGreaterEqual:
11862 case OO_EqualEqual:
11863 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011864 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011865 case OO_PlusPlus:
11866 case OO_MinusMinus:
11867 case OO_Comma:
11868 case OO_ArrowStar:
11869 case OO_Arrow:
11870 case OO_Call:
11871 case OO_Subscript:
11872 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011873 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011874 case NUM_OVERLOADED_OPERATORS:
11875 llvm_unreachable("Unexpected reduction identifier");
11876 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011877 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011878 if (II->isStr("max"))
11879 BOK = BO_GT;
11880 else if (II->isStr("min"))
11881 BOK = BO_LT;
11882 }
11883 break;
11884 }
11885 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011886 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011887 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011888 else
11889 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011890 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011891
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011892 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11893 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011894 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011895 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011896 // OpenMP [2.1, C/C++]
11897 // A list item is a variable or array section, subject to the restrictions
11898 // specified in Section 2.4 on page 42 and in each of the sections
11899 // describing clauses and directives for which a list appears.
11900 // OpenMP [2.14.3.3, Restrictions, p.1]
11901 // A variable that is part of another variable (as an array or
11902 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011903 if (!FirstIter && IR != ER)
11904 ++IR;
11905 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011906 SourceLocation ELoc;
11907 SourceRange ERange;
11908 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011909 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011910 /*AllowArraySection=*/true);
11911 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011912 // Try to find 'declare reduction' corresponding construct before using
11913 // builtin/overloaded operators.
11914 QualType Type = Context.DependentTy;
11915 CXXCastPath BasePath;
11916 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011917 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011918 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011919 Expr *ReductionOp = nullptr;
11920 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011921 (DeclareReductionRef.isUnset() ||
11922 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011923 ReductionOp = DeclareReductionRef.get();
11924 // It will be analyzed later.
11925 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011926 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011927 ValueDecl *D = Res.first;
11928 if (!D)
11929 continue;
11930
Alexey Bataev88202be2017-07-27 13:20:36 +000011931 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011932 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011933 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11934 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011935 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011936 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011937 } else if (OASE) {
11938 QualType BaseType =
11939 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11940 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011941 Type = ATy->getElementType();
11942 else
11943 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011944 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011945 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011946 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011947 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011948 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011949
Alexey Bataevc5e02582014-06-16 07:08:35 +000011950 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11951 // A variable that appears in a private clause must not have an incomplete
11952 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011953 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011954 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011955 continue;
11956 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011957 // A list item that appears in a reduction clause must not be
11958 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011959 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11960 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011961 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011962
11963 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011964 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11965 // If a list-item is a reference type then it must bind to the same object
11966 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011967 if (!ASE && !OASE) {
11968 if (VD) {
11969 VarDecl *VDDef = VD->getDefinition();
11970 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11971 DSARefChecker Check(Stack);
11972 if (Check.Visit(VDDef->getInit())) {
11973 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11974 << getOpenMPClauseName(ClauseKind) << ERange;
11975 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11976 continue;
11977 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011978 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011979 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011980
Alexey Bataevbc529672018-09-28 19:33:14 +000011981 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11982 // in a Construct]
11983 // Variables with the predetermined data-sharing attributes may not be
11984 // listed in data-sharing attributes clauses, except for the cases
11985 // listed below. For these exceptions only, listing a predetermined
11986 // variable in a data-sharing attribute clause is allowed and overrides
11987 // the variable's predetermined data-sharing attributes.
11988 // OpenMP [2.14.3.6, Restrictions, p.3]
11989 // Any number of reduction clauses can be specified on the directive,
11990 // but a list item can appear only once in the reduction clauses for that
11991 // directive.
11992 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11993 if (DVar.CKind == OMPC_reduction) {
11994 S.Diag(ELoc, diag::err_omp_once_referenced)
11995 << getOpenMPClauseName(ClauseKind);
11996 if (DVar.RefExpr)
11997 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11998 continue;
11999 }
12000 if (DVar.CKind != OMPC_unknown) {
12001 S.Diag(ELoc, diag::err_omp_wrong_dsa)
12002 << getOpenMPClauseName(DVar.CKind)
12003 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000012004 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012005 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000012006 }
Alexey Bataevbc529672018-09-28 19:33:14 +000012007
12008 // OpenMP [2.14.3.6, Restrictions, p.1]
12009 // A list item that appears in a reduction clause of a worksharing
12010 // construct must be shared in the parallel regions to which any of the
12011 // worksharing regions arising from the worksharing construct bind.
12012 if (isOpenMPWorksharingDirective(CurrDir) &&
12013 !isOpenMPParallelDirective(CurrDir) &&
12014 !isOpenMPTeamsDirective(CurrDir)) {
12015 DVar = Stack->getImplicitDSA(D, true);
12016 if (DVar.CKind != OMPC_shared) {
12017 S.Diag(ELoc, diag::err_omp_required_access)
12018 << getOpenMPClauseName(OMPC_reduction)
12019 << getOpenMPClauseName(OMPC_shared);
12020 reportOriginalDsa(S, Stack, D, DVar);
12021 continue;
12022 }
12023 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000012024 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012025
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012026 // Try to find 'declare reduction' corresponding construct before using
12027 // builtin/overloaded operators.
12028 CXXCastPath BasePath;
12029 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012030 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012031 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
12032 if (DeclareReductionRef.isInvalid())
12033 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012034 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012035 (DeclareReductionRef.isUnset() ||
12036 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012037 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012038 continue;
12039 }
12040 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
12041 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012042 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012043 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012044 << Type << ReductionIdRange;
12045 continue;
12046 }
12047
12048 // OpenMP [2.14.3.6, reduction clause, Restrictions]
12049 // The type of a list item that appears in a reduction clause must be valid
12050 // for the reduction-identifier. For a max or min reduction in C, the type
12051 // of the list item must be an allowed arithmetic data type: char, int,
12052 // float, double, or _Bool, possibly modified with long, short, signed, or
12053 // unsigned. For a max or min reduction in C++, the type of the list item
12054 // must be an allowed arithmetic data type: char, wchar_t, int, float,
12055 // double, or bool, possibly modified with long, short, signed, or unsigned.
12056 if (DeclareReductionRef.isUnset()) {
12057 if ((BOK == BO_GT || BOK == BO_LT) &&
12058 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012059 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
12060 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000012061 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012062 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012063 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12064 VarDecl::DeclarationOnly;
12065 S.Diag(D->getLocation(),
12066 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012067 << D;
12068 }
12069 continue;
12070 }
12071 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012072 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000012073 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
12074 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012075 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012076 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12077 VarDecl::DeclarationOnly;
12078 S.Diag(D->getLocation(),
12079 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012080 << D;
12081 }
12082 continue;
12083 }
12084 }
12085
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012086 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012087 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
12088 D->hasAttrs() ? &D->getAttrs() : nullptr);
12089 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
12090 D->hasAttrs() ? &D->getAttrs() : nullptr);
12091 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012092
12093 // Try if we can determine constant lengths for all array sections and avoid
12094 // the VLA.
12095 bool ConstantLengthOASE = false;
12096 if (OASE) {
12097 bool SingleElement;
12098 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000012099 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012100 Context, OASE, SingleElement, ArraySizes);
12101
12102 // If we don't have a single element, we must emit a constant array type.
12103 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012104 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012105 PrivateTy = Context.getConstantArrayType(
12106 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012107 }
12108 }
12109
12110 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000012111 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000012112 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000012113 if (!Context.getTargetInfo().isVLASupported() &&
12114 S.shouldDiagnoseTargetSupportFromOpenMP()) {
12115 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12116 S.Diag(ELoc, diag::note_vla_unsupported);
12117 continue;
12118 }
David Majnemer9d168222016-08-05 17:44:54 +000012119 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012120 // Create pseudo array type for private copy. The size for this array will
12121 // be generated during codegen.
12122 // For array subscripts or single variables Private Ty is the same as Type
12123 // (type of the variable or single array element).
12124 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012125 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000012126 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012127 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000012128 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000012129 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012130 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012131 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012132 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012133 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012134 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
12135 D->hasAttrs() ? &D->getAttrs() : nullptr,
12136 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012137 // Add initializer for private variable.
12138 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012139 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
12140 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012141 if (DeclareReductionRef.isUsable()) {
12142 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
12143 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
12144 if (DRD->getInitializer()) {
12145 Init = DRDRef;
12146 RHSVD->setInit(DRDRef);
12147 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012148 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012149 } else {
12150 switch (BOK) {
12151 case BO_Add:
12152 case BO_Xor:
12153 case BO_Or:
12154 case BO_LOr:
12155 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
12156 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012157 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012158 break;
12159 case BO_Mul:
12160 case BO_LAnd:
12161 if (Type->isScalarType() || Type->isAnyComplexType()) {
12162 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012163 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012164 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012165 break;
12166 case BO_And: {
12167 // '&' reduction op - initializer is '~0'.
12168 QualType OrigType = Type;
12169 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
12170 Type = ComplexTy->getElementType();
12171 if (Type->isRealFloatingType()) {
12172 llvm::APFloat InitValue =
12173 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
12174 /*isIEEE=*/true);
12175 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12176 Type, ELoc);
12177 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012178 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012179 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
12180 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
12181 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12182 }
12183 if (Init && OrigType->isAnyComplexType()) {
12184 // Init = 0xFFFF + 0xFFFFi;
12185 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012186 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012187 }
12188 Type = OrigType;
12189 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012190 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012191 case BO_LT:
12192 case BO_GT: {
12193 // 'min' reduction op - initializer is 'Largest representable number in
12194 // the reduction list item type'.
12195 // 'max' reduction op - initializer is 'Least representable number in
12196 // the reduction list item type'.
12197 if (Type->isIntegerType() || Type->isPointerType()) {
12198 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000012199 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012200 QualType IntTy =
12201 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
12202 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012203 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
12204 : llvm::APInt::getMinValue(Size)
12205 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
12206 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012207 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12208 if (Type->isPointerType()) {
12209 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012210 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000012211 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012212 if (CastExpr.isInvalid())
12213 continue;
12214 Init = CastExpr.get();
12215 }
12216 } else if (Type->isRealFloatingType()) {
12217 llvm::APFloat InitValue = llvm::APFloat::getLargest(
12218 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
12219 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12220 Type, ELoc);
12221 }
12222 break;
12223 }
12224 case BO_PtrMemD:
12225 case BO_PtrMemI:
12226 case BO_MulAssign:
12227 case BO_Div:
12228 case BO_Rem:
12229 case BO_Sub:
12230 case BO_Shl:
12231 case BO_Shr:
12232 case BO_LE:
12233 case BO_GE:
12234 case BO_EQ:
12235 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000012236 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012237 case BO_AndAssign:
12238 case BO_XorAssign:
12239 case BO_OrAssign:
12240 case BO_Assign:
12241 case BO_AddAssign:
12242 case BO_SubAssign:
12243 case BO_DivAssign:
12244 case BO_RemAssign:
12245 case BO_ShlAssign:
12246 case BO_ShrAssign:
12247 case BO_Comma:
12248 llvm_unreachable("Unexpected reduction operation");
12249 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012250 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012251 if (Init && DeclareReductionRef.isUnset())
12252 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
12253 else if (!Init)
12254 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012255 if (RHSVD->isInvalidDecl())
12256 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000012257 if (!RHSVD->hasInit() &&
12258 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012259 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
12260 << Type << ReductionIdRange;
12261 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12262 VarDecl::DeclarationOnly;
12263 S.Diag(D->getLocation(),
12264 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000012265 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012266 continue;
12267 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012268 // Store initializer for single element in private copy. Will be used during
12269 // codegen.
12270 PrivateVD->setInit(RHSVD->getInit());
12271 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000012272 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012273 ExprResult ReductionOp;
12274 if (DeclareReductionRef.isUsable()) {
12275 QualType RedTy = DeclareReductionRef.get()->getType();
12276 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012277 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
12278 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012279 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012280 LHS = S.DefaultLvalueConversion(LHS.get());
12281 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012282 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12283 CK_UncheckedDerivedToBase, LHS.get(),
12284 &BasePath, LHS.get()->getValueKind());
12285 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12286 CK_UncheckedDerivedToBase, RHS.get(),
12287 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012288 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012289 FunctionProtoType::ExtProtoInfo EPI;
12290 QualType Params[] = {PtrRedTy, PtrRedTy};
12291 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
12292 auto *OVE = new (Context) OpaqueValueExpr(
12293 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012294 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012295 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000012296 ReductionOp =
12297 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012298 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012299 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012300 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012301 if (ReductionOp.isUsable()) {
12302 if (BOK != BO_LT && BOK != BO_GT) {
12303 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012304 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012305 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012306 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000012307 auto *ConditionalOp = new (Context)
12308 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
12309 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012310 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012311 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012312 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012313 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012314 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012315 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
12316 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012317 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012318 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012319 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012320 }
12321
Alexey Bataevfa312f32017-07-21 18:48:21 +000012322 // OpenMP [2.15.4.6, Restrictions, p.2]
12323 // A list item that appears in an in_reduction clause of a task construct
12324 // must appear in a task_reduction clause of a construct associated with a
12325 // taskgroup region that includes the participating task in its taskgroup
12326 // set. The construct associated with the innermost region that meets this
12327 // condition must specify the same reduction-identifier as the in_reduction
12328 // clause.
12329 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000012330 SourceRange ParentSR;
12331 BinaryOperatorKind ParentBOK;
12332 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000012333 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000012334 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012335 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
12336 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012337 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012338 Stack->getTopMostTaskgroupReductionData(
12339 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012340 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
12341 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
12342 if (!IsParentBOK && !IsParentReductionOp) {
12343 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
12344 continue;
12345 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000012346 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
12347 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
12348 IsParentReductionOp) {
12349 bool EmitError = true;
12350 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
12351 llvm::FoldingSetNodeID RedId, ParentRedId;
12352 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
12353 DeclareReductionRef.get()->Profile(RedId, Context,
12354 /*Canonical=*/true);
12355 EmitError = RedId != ParentRedId;
12356 }
12357 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012358 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000012359 diag::err_omp_reduction_identifier_mismatch)
12360 << ReductionIdRange << RefExpr->getSourceRange();
12361 S.Diag(ParentSR.getBegin(),
12362 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000012363 << ParentSR
12364 << (IsParentBOK ? ParentBOKDSA.RefExpr
12365 : ParentReductionOpDSA.RefExpr)
12366 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000012367 continue;
12368 }
12369 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012370 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
12371 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000012372 }
12373
Alexey Bataev60da77e2016-02-29 05:54:20 +000012374 DeclRefExpr *Ref = nullptr;
12375 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012376 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012377 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012378 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012379 VarsExpr =
12380 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
12381 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000012382 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012383 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012384 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012385 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012386 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012387 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012388 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012389 if (!RefRes.isUsable())
12390 continue;
12391 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012392 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12393 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012394 if (!PostUpdateRes.isUsable())
12395 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012396 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
12397 Stack->getCurrentDirective() == OMPD_taskgroup) {
12398 S.Diag(RefExpr->getExprLoc(),
12399 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000012400 << RefExpr->getSourceRange();
12401 continue;
12402 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012403 RD.ExprPostUpdates.emplace_back(
12404 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000012405 }
12406 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012407 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000012408 // All reduction items are still marked as reduction (to do not increase
12409 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012410 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012411 if (CurrDir == OMPD_taskgroup) {
12412 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012413 Stack->addTaskgroupReductionData(D, ReductionIdRange,
12414 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000012415 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012416 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012417 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012418 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
12419 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012420 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012421 return RD.Vars.empty();
12422}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012423
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012424OMPClause *Sema::ActOnOpenMPReductionClause(
12425 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12426 SourceLocation ColonLoc, SourceLocation EndLoc,
12427 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12428 ArrayRef<Expr *> UnresolvedReductions) {
12429 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012430 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012431 StartLoc, LParenLoc, ColonLoc, EndLoc,
12432 ReductionIdScopeSpec, ReductionId,
12433 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012434 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000012435
Alexey Bataevc5e02582014-06-16 07:08:35 +000012436 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012437 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12438 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12439 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12440 buildPreInits(Context, RD.ExprCaptures),
12441 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000012442}
12443
Alexey Bataev169d96a2017-07-18 20:17:46 +000012444OMPClause *Sema::ActOnOpenMPTaskReductionClause(
12445 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12446 SourceLocation ColonLoc, SourceLocation EndLoc,
12447 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12448 ArrayRef<Expr *> UnresolvedReductions) {
12449 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012450 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
12451 StartLoc, LParenLoc, ColonLoc, EndLoc,
12452 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012453 UnresolvedReductions, RD))
12454 return nullptr;
12455
12456 return OMPTaskReductionClause::Create(
12457 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12458 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12459 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12460 buildPreInits(Context, RD.ExprCaptures),
12461 buildPostUpdate(*this, RD.ExprPostUpdates));
12462}
12463
Alexey Bataevfa312f32017-07-21 18:48:21 +000012464OMPClause *Sema::ActOnOpenMPInReductionClause(
12465 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12466 SourceLocation ColonLoc, SourceLocation EndLoc,
12467 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12468 ArrayRef<Expr *> UnresolvedReductions) {
12469 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012470 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012471 StartLoc, LParenLoc, ColonLoc, EndLoc,
12472 ReductionIdScopeSpec, ReductionId,
12473 UnresolvedReductions, RD))
12474 return nullptr;
12475
12476 return OMPInReductionClause::Create(
12477 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12478 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000012479 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012480 buildPreInits(Context, RD.ExprCaptures),
12481 buildPostUpdate(*this, RD.ExprPostUpdates));
12482}
12483
Alexey Bataevecba70f2016-04-12 11:02:11 +000012484bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
12485 SourceLocation LinLoc) {
12486 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
12487 LinKind == OMPC_LINEAR_unknown) {
12488 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
12489 return true;
12490 }
12491 return false;
12492}
12493
Alexey Bataeve3727102018-04-18 15:57:46 +000012494bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000012495 OpenMPLinearClauseKind LinKind,
12496 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012497 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000012498 // A variable must not have an incomplete type or a reference type.
12499 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12500 return true;
12501 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12502 !Type->isReferenceType()) {
12503 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12504 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12505 return true;
12506 }
12507 Type = Type.getNonReferenceType();
12508
Joel E. Dennybae586f2019-01-04 22:12:13 +000012509 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12510 // A variable that is privatized must not have a const-qualified type
12511 // unless it is of class type with a mutable member. This restriction does
12512 // not apply to the firstprivate clause.
12513 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012514 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012515
12516 // A list item must be of integral or pointer type.
12517 Type = Type.getUnqualifiedType().getCanonicalType();
12518 const auto *Ty = Type.getTypePtrOrNull();
12519 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12520 !Ty->isPointerType())) {
12521 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12522 if (D) {
12523 bool IsDecl =
12524 !VD ||
12525 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12526 Diag(D->getLocation(),
12527 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12528 << D;
12529 }
12530 return true;
12531 }
12532 return false;
12533}
12534
Alexey Bataev182227b2015-08-20 10:54:39 +000012535OMPClause *Sema::ActOnOpenMPLinearClause(
12536 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12537 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12538 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012539 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012540 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012541 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012542 SmallVector<Decl *, 4> ExprCaptures;
12543 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012544 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012545 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012546 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012547 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012548 SourceLocation ELoc;
12549 SourceRange ERange;
12550 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012551 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012552 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012553 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012554 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012555 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012556 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012557 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012558 ValueDecl *D = Res.first;
12559 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012560 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012561
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012562 QualType Type = D->getType();
12563 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012564
12565 // OpenMP [2.14.3.7, linear clause]
12566 // A list-item cannot appear in more than one linear clause.
12567 // A list-item that appears in a linear clause cannot appear in any
12568 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012569 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012570 if (DVar.RefExpr) {
12571 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12572 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012573 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012574 continue;
12575 }
12576
Alexey Bataevecba70f2016-04-12 11:02:11 +000012577 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012578 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012579 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012580
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012581 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012582 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012583 buildVarDecl(*this, ELoc, Type, D->getName(),
12584 D->hasAttrs() ? &D->getAttrs() : nullptr,
12585 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012586 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012587 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012588 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012589 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012590 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012591 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012592 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012593 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012594 ExprCaptures.push_back(Ref->getDecl());
12595 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12596 ExprResult RefRes = DefaultLvalueConversion(Ref);
12597 if (!RefRes.isUsable())
12598 continue;
12599 ExprResult PostUpdateRes =
12600 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12601 SimpleRefExpr, RefRes.get());
12602 if (!PostUpdateRes.isUsable())
12603 continue;
12604 ExprPostUpdates.push_back(
12605 IgnoredValueConversions(PostUpdateRes.get()).get());
12606 }
12607 }
12608 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012609 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012610 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012611 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012612 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012613 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012614 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012615 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012616
12617 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012618 Vars.push_back((VD || CurContext->isDependentContext())
12619 ? RefExpr->IgnoreParens()
12620 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012621 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012622 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012623 }
12624
12625 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012626 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012627
12628 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012629 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012630 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12631 !Step->isInstantiationDependent() &&
12632 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012633 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012634 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012635 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012636 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012637 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012638
Alexander Musman3276a272015-03-21 10:12:56 +000012639 // Build var to save the step value.
12640 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012641 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012642 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012643 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012644 ExprResult CalcStep =
12645 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012646 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012647
Alexander Musman8dba6642014-04-22 13:09:42 +000012648 // Warn about zero linear step (it would be probably better specified as
12649 // making corresponding variables 'const').
12650 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012651 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12652 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012653 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12654 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012655 if (!IsConstant && CalcStep.isUsable()) {
12656 // Calculate the step beforehand instead of doing this on each iteration.
12657 // (This is not used if the number of iterations may be kfold-ed).
12658 CalcStepExpr = CalcStep.get();
12659 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012660 }
12661
Alexey Bataev182227b2015-08-20 10:54:39 +000012662 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12663 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012664 StepExpr, CalcStepExpr,
12665 buildPreInits(Context, ExprCaptures),
12666 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012667}
12668
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012669static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12670 Expr *NumIterations, Sema &SemaRef,
12671 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012672 // Walk the vars and build update/final expressions for the CodeGen.
12673 SmallVector<Expr *, 8> Updates;
12674 SmallVector<Expr *, 8> Finals;
12675 Expr *Step = Clause.getStep();
12676 Expr *CalcStep = Clause.getCalcStep();
12677 // OpenMP [2.14.3.7, linear clause]
12678 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012679 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012680 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012681 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012682 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12683 bool HasErrors = false;
12684 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012685 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012686 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12687 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012688 SourceLocation ELoc;
12689 SourceRange ERange;
12690 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012691 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012692 ValueDecl *D = Res.first;
12693 if (Res.second || !D) {
12694 Updates.push_back(nullptr);
12695 Finals.push_back(nullptr);
12696 HasErrors = true;
12697 continue;
12698 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012699 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012700 // OpenMP [2.15.11, distribute simd Construct]
12701 // A list item may not appear in a linear clause, unless it is the loop
12702 // iteration variable.
12703 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12704 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12705 SemaRef.Diag(ELoc,
12706 diag::err_omp_linear_distribute_var_non_loop_iteration);
12707 Updates.push_back(nullptr);
12708 Finals.push_back(nullptr);
12709 HasErrors = true;
12710 continue;
12711 }
Alexander Musman3276a272015-03-21 10:12:56 +000012712 Expr *InitExpr = *CurInit;
12713
12714 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012715 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012716 Expr *CapturedRef;
12717 if (LinKind == OMPC_LINEAR_uval)
12718 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12719 else
12720 CapturedRef =
12721 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12722 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12723 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012724
12725 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012726 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012727 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012728 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012729 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012730 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012731 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012732 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012733 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012734 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012735
12736 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012737 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012738 if (!Info.first)
12739 Final =
12740 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12741 InitExpr, NumIterations, Step, /*Subtract=*/false);
12742 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012743 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012744 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012745 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012746
Alexander Musman3276a272015-03-21 10:12:56 +000012747 if (!Update.isUsable() || !Final.isUsable()) {
12748 Updates.push_back(nullptr);
12749 Finals.push_back(nullptr);
12750 HasErrors = true;
12751 } else {
12752 Updates.push_back(Update.get());
12753 Finals.push_back(Final.get());
12754 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012755 ++CurInit;
12756 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012757 }
12758 Clause.setUpdates(Updates);
12759 Clause.setFinals(Finals);
12760 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012761}
12762
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012763OMPClause *Sema::ActOnOpenMPAlignedClause(
12764 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12765 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012766 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012767 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012768 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12769 SourceLocation ELoc;
12770 SourceRange ERange;
12771 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012772 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012773 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012774 // It will be analyzed later.
12775 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012776 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012777 ValueDecl *D = Res.first;
12778 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012779 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012780
Alexey Bataev1efd1662016-03-29 10:59:56 +000012781 QualType QType = D->getType();
12782 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012783
12784 // OpenMP [2.8.1, simd construct, Restrictions]
12785 // The type of list items appearing in the aligned clause must be
12786 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012787 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012788 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012789 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012790 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012791 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012792 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012793 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012794 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012795 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012796 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012797 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012798 continue;
12799 }
12800
12801 // OpenMP [2.8.1, simd construct, Restrictions]
12802 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012803 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012804 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012805 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12806 << getOpenMPClauseName(OMPC_aligned);
12807 continue;
12808 }
12809
Alexey Bataev1efd1662016-03-29 10:59:56 +000012810 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012811 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012812 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12813 Vars.push_back(DefaultFunctionArrayConversion(
12814 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12815 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012816 }
12817
12818 // OpenMP [2.8.1, simd construct, Description]
12819 // The parameter of the aligned clause, alignment, must be a constant
12820 // positive integer expression.
12821 // If no optional parameter is specified, implementation-defined default
12822 // alignments for SIMD instructions on the target platforms are assumed.
12823 if (Alignment != nullptr) {
12824 ExprResult AlignResult =
12825 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12826 if (AlignResult.isInvalid())
12827 return nullptr;
12828 Alignment = AlignResult.get();
12829 }
12830 if (Vars.empty())
12831 return nullptr;
12832
12833 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12834 EndLoc, Vars, Alignment);
12835}
12836
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012837OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12838 SourceLocation StartLoc,
12839 SourceLocation LParenLoc,
12840 SourceLocation EndLoc) {
12841 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012842 SmallVector<Expr *, 8> SrcExprs;
12843 SmallVector<Expr *, 8> DstExprs;
12844 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012845 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012846 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12847 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012848 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012849 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012850 SrcExprs.push_back(nullptr);
12851 DstExprs.push_back(nullptr);
12852 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012853 continue;
12854 }
12855
Alexey Bataeved09d242014-05-28 05:53:51 +000012856 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012857 // OpenMP [2.1, C/C++]
12858 // A list item is a variable name.
12859 // OpenMP [2.14.4.1, Restrictions, p.1]
12860 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012861 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012862 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012863 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12864 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012865 continue;
12866 }
12867
12868 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012869 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012870
12871 QualType Type = VD->getType();
12872 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12873 // It will be analyzed later.
12874 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012875 SrcExprs.push_back(nullptr);
12876 DstExprs.push_back(nullptr);
12877 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012878 continue;
12879 }
12880
12881 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12882 // A list item that appears in a copyin clause must be threadprivate.
12883 if (!DSAStack->isThreadPrivate(VD)) {
12884 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012885 << getOpenMPClauseName(OMPC_copyin)
12886 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012887 continue;
12888 }
12889
12890 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12891 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012892 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012893 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012894 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12895 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012896 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012897 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012898 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012899 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012900 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012901 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012902 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012903 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012904 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012905 // For arrays generate assignment operation for single element and replace
12906 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012907 ExprResult AssignmentOp =
12908 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12909 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012910 if (AssignmentOp.isInvalid())
12911 continue;
12912 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012913 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012914 if (AssignmentOp.isInvalid())
12915 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012916
12917 DSAStack->addDSA(VD, DE, OMPC_copyin);
12918 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012919 SrcExprs.push_back(PseudoSrcExpr);
12920 DstExprs.push_back(PseudoDstExpr);
12921 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012922 }
12923
Alexey Bataeved09d242014-05-28 05:53:51 +000012924 if (Vars.empty())
12925 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012926
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012927 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12928 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012929}
12930
Alexey Bataevbae9a792014-06-27 10:37:06 +000012931OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12932 SourceLocation StartLoc,
12933 SourceLocation LParenLoc,
12934 SourceLocation EndLoc) {
12935 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012936 SmallVector<Expr *, 8> SrcExprs;
12937 SmallVector<Expr *, 8> DstExprs;
12938 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012939 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012940 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12941 SourceLocation ELoc;
12942 SourceRange ERange;
12943 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012944 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012945 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012946 // It will be analyzed later.
12947 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012948 SrcExprs.push_back(nullptr);
12949 DstExprs.push_back(nullptr);
12950 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012951 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012952 ValueDecl *D = Res.first;
12953 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012954 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012955
Alexey Bataeve122da12016-03-17 10:50:17 +000012956 QualType Type = D->getType();
12957 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012958
12959 // OpenMP [2.14.4.2, Restrictions, p.2]
12960 // A list item that appears in a copyprivate clause may not appear in a
12961 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012962 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012963 DSAStackTy::DSAVarData DVar =
12964 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012965 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12966 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012967 Diag(ELoc, diag::err_omp_wrong_dsa)
12968 << getOpenMPClauseName(DVar.CKind)
12969 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012970 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012971 continue;
12972 }
12973
12974 // OpenMP [2.11.4.2, Restrictions, p.1]
12975 // All list items that appear in a copyprivate clause must be either
12976 // threadprivate or private in the enclosing context.
12977 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012978 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012979 if (DVar.CKind == OMPC_shared) {
12980 Diag(ELoc, diag::err_omp_required_access)
12981 << getOpenMPClauseName(OMPC_copyprivate)
12982 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012983 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012984 continue;
12985 }
12986 }
12987 }
12988
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012989 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012990 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012991 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012992 << getOpenMPClauseName(OMPC_copyprivate) << Type
12993 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012994 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012995 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012996 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012997 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012998 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012999 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013000 continue;
13001 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013002
Alexey Bataevbae9a792014-06-27 10:37:06 +000013003 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13004 // A variable of class type (or array thereof) that appears in a
13005 // copyin clause requires an accessible, unambiguous copy assignment
13006 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013007 Type = Context.getBaseElementType(Type.getNonReferenceType())
13008 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013009 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013010 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000013011 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013012 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
13013 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013014 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000013015 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013016 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
13017 ExprResult AssignmentOp = BuildBinOp(
13018 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013019 if (AssignmentOp.isInvalid())
13020 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013021 AssignmentOp =
13022 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013023 if (AssignmentOp.isInvalid())
13024 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013025
13026 // No need to mark vars as copyprivate, they are already threadprivate or
13027 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000013028 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000013029 Vars.push_back(
13030 VD ? RefExpr->IgnoreParens()
13031 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000013032 SrcExprs.push_back(PseudoSrcExpr);
13033 DstExprs.push_back(PseudoDstExpr);
13034 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000013035 }
13036
13037 if (Vars.empty())
13038 return nullptr;
13039
Alexey Bataeva63048e2015-03-23 06:18:07 +000013040 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13041 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013042}
13043
Alexey Bataev6125da92014-07-21 11:26:11 +000013044OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
13045 SourceLocation StartLoc,
13046 SourceLocation LParenLoc,
13047 SourceLocation EndLoc) {
13048 if (VarList.empty())
13049 return nullptr;
13050
13051 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
13052}
Alexey Bataevdea47612014-07-23 07:46:59 +000013053
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013054OMPClause *
13055Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
13056 SourceLocation DepLoc, SourceLocation ColonLoc,
13057 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13058 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013059 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013060 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013061 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013062 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000013063 return nullptr;
13064 }
13065 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013066 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
13067 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000013068 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013069 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013070 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13071 /*Last=*/OMPC_DEPEND_unknown, Except)
13072 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013073 return nullptr;
13074 }
13075 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000013076 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013077 llvm::APSInt DepCounter(/*BitWidth=*/32);
13078 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000013079 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
13080 if (const Expr *OrderedCountExpr =
13081 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013082 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
13083 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013084 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013085 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013086 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000013087 assert(RefExpr && "NULL expr in OpenMP shared clause.");
13088 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
13089 // It will be analyzed later.
13090 Vars.push_back(RefExpr);
13091 continue;
13092 }
13093
13094 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000013095 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000013096 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000013097 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013098 DepCounter >= TotalDepCount) {
13099 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
13100 continue;
13101 }
13102 ++DepCounter;
13103 // OpenMP [2.13.9, Summary]
13104 // depend(dependence-type : vec), where dependence-type is:
13105 // 'sink' and where vec is the iteration vector, which has the form:
13106 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
13107 // where n is the value specified by the ordered clause in the loop
13108 // directive, xi denotes the loop iteration variable of the i-th nested
13109 // loop associated with the loop directive, and di is a constant
13110 // non-negative integer.
13111 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013112 // It will be analyzed later.
13113 Vars.push_back(RefExpr);
13114 continue;
13115 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013116 SimpleExpr = SimpleExpr->IgnoreImplicit();
13117 OverloadedOperatorKind OOK = OO_None;
13118 SourceLocation OOLoc;
13119 Expr *LHS = SimpleExpr;
13120 Expr *RHS = nullptr;
13121 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
13122 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
13123 OOLoc = BO->getOperatorLoc();
13124 LHS = BO->getLHS()->IgnoreParenImpCasts();
13125 RHS = BO->getRHS()->IgnoreParenImpCasts();
13126 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
13127 OOK = OCE->getOperator();
13128 OOLoc = OCE->getOperatorLoc();
13129 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
13130 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
13131 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
13132 OOK = MCE->getMethodDecl()
13133 ->getNameInfo()
13134 .getName()
13135 .getCXXOverloadedOperator();
13136 OOLoc = MCE->getCallee()->getExprLoc();
13137 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
13138 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013139 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013140 SourceLocation ELoc;
13141 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000013142 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013143 if (Res.second) {
13144 // It will be analyzed later.
13145 Vars.push_back(RefExpr);
13146 }
13147 ValueDecl *D = Res.first;
13148 if (!D)
13149 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013150
Alexey Bataev17daedf2018-02-15 22:42:57 +000013151 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
13152 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
13153 continue;
13154 }
13155 if (RHS) {
13156 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
13157 RHS, OMPC_depend, /*StrictlyPositive=*/false);
13158 if (RHSRes.isInvalid())
13159 continue;
13160 }
13161 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013162 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013163 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013164 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000013165 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000013166 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000013167 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
13168 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000013169 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000013170 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000013171 continue;
13172 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013173 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013174 } else {
13175 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
13176 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
13177 (ASE &&
13178 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
13179 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
13180 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13181 << RefExpr->getSourceRange();
13182 continue;
13183 }
13184 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
13185 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
13186 ExprResult Res =
13187 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
13188 getDiagnostics().setSuppressAllDiagnostics(Suppress);
13189 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
13190 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13191 << RefExpr->getSourceRange();
13192 continue;
13193 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013194 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013195 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013196 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013197
13198 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
13199 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013200 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013201 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
13202 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
13203 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
13204 }
13205 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
13206 Vars.empty())
13207 return nullptr;
13208
Alexey Bataev8b427062016-05-25 12:36:08 +000013209 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000013210 DepKind, DepLoc, ColonLoc, Vars,
13211 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000013212 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
13213 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000013214 DSAStack->addDoacrossDependClause(C, OpsOffs);
13215 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013216}
Michael Wonge710d542015-08-07 16:16:36 +000013217
13218OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
13219 SourceLocation LParenLoc,
13220 SourceLocation EndLoc) {
13221 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013222 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000013223
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013224 // OpenMP [2.9.1, Restrictions]
13225 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013226 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000013227 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013228 return nullptr;
13229
Alexey Bataev931e19b2017-10-02 16:32:39 +000013230 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013231 OpenMPDirectiveKind CaptureRegion =
13232 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
13233 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013234 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013235 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013236 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13237 HelperValStmt = buildPreInits(Context, Captures);
13238 }
13239
Alexey Bataev8451efa2018-01-15 19:06:12 +000013240 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
13241 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000013242}
Kelvin Li0bff7af2015-11-23 05:32:03 +000013243
Alexey Bataeve3727102018-04-18 15:57:46 +000013244static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000013245 DSAStackTy *Stack, QualType QTy,
13246 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000013247 NamedDecl *ND;
13248 if (QTy->isIncompleteType(&ND)) {
13249 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
13250 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013251 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000013252 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
13253 !QTy.isTrivialType(SemaRef.Context))
13254 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013255 return true;
13256}
13257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013258/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013259/// (array section or array subscript) does NOT specify the whole size of the
13260/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013261static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013262 const Expr *E,
13263 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013264 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013265
13266 // If this is an array subscript, it refers to the whole size if the size of
13267 // the dimension is constant and equals 1. Also, an array section assumes the
13268 // format of an array subscript if no colon is used.
13269 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013270 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013271 return ATy->getSize().getSExtValue() != 1;
13272 // Size can't be evaluated statically.
13273 return false;
13274 }
13275
13276 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013277 const Expr *LowerBound = OASE->getLowerBound();
13278 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013279
13280 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000013281 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013282 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000013283 Expr::EvalResult Result;
13284 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013285 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000013286
13287 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013288 if (ConstLowerBound.getSExtValue())
13289 return true;
13290 }
13291
13292 // If we don't have a length we covering the whole dimension.
13293 if (!Length)
13294 return false;
13295
13296 // If the base is a pointer, we don't have a way to get the size of the
13297 // pointee.
13298 if (BaseQTy->isPointerType())
13299 return false;
13300
13301 // We can only check if the length is the same as the size of the dimension
13302 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000013303 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013304 if (!CATy)
13305 return false;
13306
Fangrui Song407659a2018-11-30 23:41:18 +000013307 Expr::EvalResult Result;
13308 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013309 return false; // Can't get the integer value as a constant.
13310
Fangrui Song407659a2018-11-30 23:41:18 +000013311 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013312 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
13313}
13314
13315// Return true if it can be proven that the provided array expression (array
13316// section or array subscript) does NOT specify a single element of the array
13317// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013318static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000013319 const Expr *E,
13320 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013321 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013322
13323 // An array subscript always refer to a single element. Also, an array section
13324 // assumes the format of an array subscript if no colon is used.
13325 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
13326 return false;
13327
13328 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013329 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013330
13331 // If we don't have a length we have to check if the array has unitary size
13332 // for this dimension. Also, we should always expect a length if the base type
13333 // is pointer.
13334 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013335 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013336 return ATy->getSize().getSExtValue() != 1;
13337 // We cannot assume anything.
13338 return false;
13339 }
13340
13341 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000013342 Expr::EvalResult Result;
13343 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013344 return false; // Can't get the integer value as a constant.
13345
Fangrui Song407659a2018-11-30 23:41:18 +000013346 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013347 return ConstLength.getSExtValue() != 1;
13348}
13349
Samuel Antao661c0902016-05-26 17:39:58 +000013350// Return the expression of the base of the mappable expression or null if it
13351// cannot be determined and do all the necessary checks to see if the expression
13352// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000013353// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013354static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000013355 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000013356 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013357 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013358 SourceLocation ELoc = E->getExprLoc();
13359 SourceRange ERange = E->getSourceRange();
13360
13361 // The base of elements of list in a map clause have to be either:
13362 // - a reference to variable or field.
13363 // - a member expression.
13364 // - an array expression.
13365 //
13366 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
13367 // reference to 'r'.
13368 //
13369 // If we have:
13370 //
13371 // struct SS {
13372 // Bla S;
13373 // foo() {
13374 // #pragma omp target map (S.Arr[:12]);
13375 // }
13376 // }
13377 //
13378 // We want to retrieve the member expression 'this->S';
13379
Alexey Bataeve3727102018-04-18 15:57:46 +000013380 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013381
Samuel Antao5de996e2016-01-22 20:21:36 +000013382 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
13383 // If a list item is an array section, it must specify contiguous storage.
13384 //
13385 // For this restriction it is sufficient that we make sure only references
13386 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013387 // exist except in the rightmost expression (unless they cover the whole
13388 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000013389 //
13390 // r.ArrS[3:5].Arr[6:7]
13391 //
13392 // r.ArrS[3:5].x
13393 //
13394 // but these would be valid:
13395 // r.ArrS[3].Arr[6:7]
13396 //
13397 // r.ArrS[3].x
13398
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013399 bool AllowUnitySizeArraySection = true;
13400 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013401
Dmitry Polukhin644a9252016-03-11 07:58:34 +000013402 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013403 E = E->IgnoreParenImpCasts();
13404
13405 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
13406 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000013407 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013408
13409 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013410
13411 // If we got a reference to a declaration, we should not expect any array
13412 // section before that.
13413 AllowUnitySizeArraySection = false;
13414 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013415
13416 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013417 CurComponents.emplace_back(CurE, CurE->getDecl());
13418 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013419 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000013420
13421 if (isa<CXXThisExpr>(BaseE))
13422 // We found a base expression: this->Val.
13423 RelevantExpr = CurE;
13424 else
13425 E = BaseE;
13426
13427 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013428 if (!NoDiagnose) {
13429 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
13430 << CurE->getSourceRange();
13431 return nullptr;
13432 }
13433 if (RelevantExpr)
13434 return nullptr;
13435 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013436 }
13437
13438 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
13439
13440 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
13441 // A bit-field cannot appear in a map clause.
13442 //
13443 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013444 if (!NoDiagnose) {
13445 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
13446 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
13447 return nullptr;
13448 }
13449 if (RelevantExpr)
13450 return nullptr;
13451 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013452 }
13453
13454 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13455 // If the type of a list item is a reference to a type T then the type
13456 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013457 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013458
13459 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
13460 // A list item cannot be a variable that is a member of a structure with
13461 // a union type.
13462 //
Alexey Bataeve3727102018-04-18 15:57:46 +000013463 if (CurType->isUnionType()) {
13464 if (!NoDiagnose) {
13465 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
13466 << CurE->getSourceRange();
13467 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013468 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013469 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013470 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013471
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013472 // If we got a member expression, we should not expect any array section
13473 // before that:
13474 //
13475 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
13476 // If a list item is an element of a structure, only the rightmost symbol
13477 // of the variable reference can be an array section.
13478 //
13479 AllowUnitySizeArraySection = false;
13480 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013481
13482 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013483 CurComponents.emplace_back(CurE, FD);
13484 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013485 E = CurE->getBase()->IgnoreParenImpCasts();
13486
13487 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013488 if (!NoDiagnose) {
13489 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13490 << 0 << CurE->getSourceRange();
13491 return nullptr;
13492 }
13493 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013494 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013495
13496 // If we got an array subscript that express the whole dimension we
13497 // can have any array expressions before. If it only expressing part of
13498 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000013499 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013500 E->getType()))
13501 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013502
Patrick Lystere13b1e32019-01-02 19:28:48 +000013503 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13504 Expr::EvalResult Result;
13505 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13506 if (!Result.Val.getInt().isNullValue()) {
13507 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13508 diag::err_omp_invalid_map_this_expr);
13509 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13510 diag::note_omp_invalid_subscript_on_this_ptr_map);
13511 }
13512 }
13513 RelevantExpr = TE;
13514 }
13515
Samuel Antao90927002016-04-26 14:54:23 +000013516 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013517 CurComponents.emplace_back(CurE, nullptr);
13518 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013519 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013520 E = CurE->getBase()->IgnoreParenImpCasts();
13521
Alexey Bataev27041fa2017-12-05 15:22:49 +000013522 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013523 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13524
Samuel Antao5de996e2016-01-22 20:21:36 +000013525 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13526 // If the type of a list item is a reference to a type T then the type
13527 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013528 if (CurType->isReferenceType())
13529 CurType = CurType->getPointeeType();
13530
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013531 bool IsPointer = CurType->isAnyPointerType();
13532
13533 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013534 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13535 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013536 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013537 }
13538
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013539 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013540 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013541 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013542 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013543
Samuel Antaodab51bb2016-07-18 23:22:11 +000013544 if (AllowWholeSizeArraySection) {
13545 // Any array section is currently allowed. Allowing a whole size array
13546 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013547 //
13548 // If this array section refers to the whole dimension we can still
13549 // accept other array sections before this one, except if the base is a
13550 // pointer. Otherwise, only unitary sections are accepted.
13551 if (NotWhole || IsPointer)
13552 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013553 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013554 // A unity or whole array section is not allowed and that is not
13555 // compatible with the properties of the current array section.
13556 SemaRef.Diag(
13557 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13558 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013559 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013560 }
Samuel Antao90927002016-04-26 14:54:23 +000013561
Patrick Lystere13b1e32019-01-02 19:28:48 +000013562 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13563 Expr::EvalResult ResultR;
13564 Expr::EvalResult ResultL;
13565 if (CurE->getLength()->EvaluateAsInt(ResultR,
13566 SemaRef.getASTContext())) {
13567 if (!ResultR.Val.getInt().isOneValue()) {
13568 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13569 diag::err_omp_invalid_map_this_expr);
13570 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13571 diag::note_omp_invalid_length_on_this_ptr_mapping);
13572 }
13573 }
13574 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13575 ResultL, SemaRef.getASTContext())) {
13576 if (!ResultL.Val.getInt().isNullValue()) {
13577 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13578 diag::err_omp_invalid_map_this_expr);
13579 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13580 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13581 }
13582 }
13583 RelevantExpr = TE;
13584 }
13585
Samuel Antao90927002016-04-26 14:54:23 +000013586 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013587 CurComponents.emplace_back(CurE, nullptr);
13588 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013589 if (!NoDiagnose) {
13590 // If nothing else worked, this is not a valid map clause expression.
13591 SemaRef.Diag(
13592 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13593 << ERange;
13594 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013595 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013596 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013597 }
13598
13599 return RelevantExpr;
13600}
13601
13602// Return true if expression E associated with value VD has conflicts with other
13603// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013604static bool checkMapConflicts(
13605 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013606 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013607 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13608 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013609 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013610 SourceLocation ELoc = E->getExprLoc();
13611 SourceRange ERange = E->getSourceRange();
13612
13613 // In order to easily check the conflicts we need to match each component of
13614 // the expression under test with the components of the expressions that are
13615 // already in the stack.
13616
Samuel Antao5de996e2016-01-22 20:21:36 +000013617 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013618 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013619 "Map clause expression with unexpected base!");
13620
13621 // Variables to help detecting enclosing problems in data environment nests.
13622 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013623 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013624
Samuel Antao90927002016-04-26 14:54:23 +000013625 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13626 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013627 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13628 ERange, CKind, &EnclosingExpr,
13629 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13630 StackComponents,
13631 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013632 assert(!StackComponents.empty() &&
13633 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013634 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013635 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013636 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013637
Samuel Antao90927002016-04-26 14:54:23 +000013638 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013639 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013640
Samuel Antao5de996e2016-01-22 20:21:36 +000013641 // Expressions must start from the same base. Here we detect at which
13642 // point both expressions diverge from each other and see if we can
13643 // detect if the memory referred to both expressions is contiguous and
13644 // do not overlap.
13645 auto CI = CurComponents.rbegin();
13646 auto CE = CurComponents.rend();
13647 auto SI = StackComponents.rbegin();
13648 auto SE = StackComponents.rend();
13649 for (; CI != CE && SI != SE; ++CI, ++SI) {
13650
13651 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13652 // At most one list item can be an array item derived from a given
13653 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013654 if (CurrentRegionOnly &&
13655 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13656 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13657 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13658 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13659 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013660 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013661 << CI->getAssociatedExpression()->getSourceRange();
13662 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13663 diag::note_used_here)
13664 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013665 return true;
13666 }
13667
13668 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013669 if (CI->getAssociatedExpression()->getStmtClass() !=
13670 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013671 break;
13672
13673 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013674 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013675 break;
13676 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013677 // Check if the extra components of the expressions in the enclosing
13678 // data environment are redundant for the current base declaration.
13679 // If they are, the maps completely overlap, which is legal.
13680 for (; SI != SE; ++SI) {
13681 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013682 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013683 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013684 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013685 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013686 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013687 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013688 Type =
13689 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13690 }
13691 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013692 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013693 SemaRef, SI->getAssociatedExpression(), Type))
13694 break;
13695 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013696
13697 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13698 // List items of map clauses in the same construct must not share
13699 // original storage.
13700 //
13701 // If the expressions are exactly the same or one is a subset of the
13702 // other, it means they are sharing storage.
13703 if (CI == CE && SI == SE) {
13704 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013705 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013706 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013707 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013708 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013709 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13710 << ERange;
13711 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013712 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13713 << RE->getSourceRange();
13714 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013715 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013716 // If we find the same expression in the enclosing data environment,
13717 // that is legal.
13718 IsEnclosedByDataEnvironmentExpr = true;
13719 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013720 }
13721
Samuel Antao90927002016-04-26 14:54:23 +000013722 QualType DerivedType =
13723 std::prev(CI)->getAssociatedDeclaration()->getType();
13724 SourceLocation DerivedLoc =
13725 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013726
13727 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13728 // If the type of a list item is a reference to a type T then the type
13729 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013730 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013731
13732 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13733 // A variable for which the type is pointer and an array section
13734 // derived from that variable must not appear as list items of map
13735 // clauses of the same construct.
13736 //
13737 // Also, cover one of the cases in:
13738 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13739 // If any part of the original storage of a list item has corresponding
13740 // storage in the device data environment, all of the original storage
13741 // must have corresponding storage in the device data environment.
13742 //
13743 if (DerivedType->isAnyPointerType()) {
13744 if (CI == CE || SI == SE) {
13745 SemaRef.Diag(
13746 DerivedLoc,
13747 diag::err_omp_pointer_mapped_along_with_derived_section)
13748 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013749 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13750 << RE->getSourceRange();
13751 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013752 }
13753 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013754 SI->getAssociatedExpression()->getStmtClass() ||
13755 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13756 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013757 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013758 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013759 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013760 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13761 << RE->getSourceRange();
13762 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013763 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013764 }
13765
13766 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13767 // List items of map clauses in the same construct must not share
13768 // original storage.
13769 //
13770 // An expression is a subset of the other.
13771 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013772 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013773 if (CI != CE || SI != SE) {
13774 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13775 // a pointer.
13776 auto Begin =
13777 CI != CE ? CurComponents.begin() : StackComponents.begin();
13778 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13779 auto It = Begin;
13780 while (It != End && !It->getAssociatedDeclaration())
13781 std::advance(It, 1);
13782 assert(It != End &&
13783 "Expected at least one component with the declaration.");
13784 if (It != Begin && It->getAssociatedDeclaration()
13785 ->getType()
13786 .getCanonicalType()
13787 ->isAnyPointerType()) {
13788 IsEnclosedByDataEnvironmentExpr = false;
13789 EnclosingExpr = nullptr;
13790 return false;
13791 }
13792 }
Samuel Antao661c0902016-05-26 17:39:58 +000013793 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013794 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013795 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013796 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13797 << ERange;
13798 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013799 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13800 << RE->getSourceRange();
13801 return true;
13802 }
13803
13804 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013805 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013806 if (!CurrentRegionOnly && SI != SE)
13807 EnclosingExpr = RE;
13808
13809 // The current expression is a subset of the expression in the data
13810 // environment.
13811 IsEnclosedByDataEnvironmentExpr |=
13812 (!CurrentRegionOnly && CI != CE && SI == SE);
13813
13814 return false;
13815 });
13816
13817 if (CurrentRegionOnly)
13818 return FoundError;
13819
13820 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13821 // If any part of the original storage of a list item has corresponding
13822 // storage in the device data environment, all of the original storage must
13823 // have corresponding storage in the device data environment.
13824 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13825 // If a list item is an element of a structure, and a different element of
13826 // the structure has a corresponding list item in the device data environment
13827 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013828 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013829 // data environment prior to the task encountering the construct.
13830 //
13831 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13832 SemaRef.Diag(ELoc,
13833 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13834 << ERange;
13835 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13836 << EnclosingExpr->getSourceRange();
13837 return true;
13838 }
13839
13840 return FoundError;
13841}
13842
Michael Kruse4304e9d2019-02-19 16:38:20 +000013843// Look up the user-defined mapper given the mapper name and mapped type, and
13844// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000013845static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13846 CXXScopeSpec &MapperIdScopeSpec,
13847 const DeclarationNameInfo &MapperId,
13848 QualType Type,
13849 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013850 if (MapperIdScopeSpec.isInvalid())
13851 return ExprError();
13852 // Find all user-defined mappers with the given MapperId.
13853 SmallVector<UnresolvedSet<8>, 4> Lookups;
13854 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13855 Lookup.suppressDiagnostics();
13856 if (S) {
13857 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13858 NamedDecl *D = Lookup.getRepresentativeDecl();
13859 while (S && !S->isDeclScope(D))
13860 S = S->getParent();
13861 if (S)
13862 S = S->getParent();
13863 Lookups.emplace_back();
13864 Lookups.back().append(Lookup.begin(), Lookup.end());
13865 Lookup.clear();
13866 }
13867 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13868 // Extract the user-defined mappers with the given MapperId.
13869 Lookups.push_back(UnresolvedSet<8>());
13870 for (NamedDecl *D : ULE->decls()) {
13871 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13872 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13873 Lookups.back().addDecl(DMD);
13874 }
13875 }
13876 // Defer the lookup for dependent types. The results will be passed through
13877 // UnresolvedMapper on instantiation.
13878 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13879 Type->isInstantiationDependentType() ||
13880 Type->containsUnexpandedParameterPack() ||
13881 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13882 return !D->isInvalidDecl() &&
13883 (D->getType()->isDependentType() ||
13884 D->getType()->isInstantiationDependentType() ||
13885 D->getType()->containsUnexpandedParameterPack());
13886 })) {
13887 UnresolvedSet<8> URS;
13888 for (const UnresolvedSet<8> &Set : Lookups) {
13889 if (Set.empty())
13890 continue;
13891 URS.append(Set.begin(), Set.end());
13892 }
13893 return UnresolvedLookupExpr::Create(
13894 SemaRef.Context, /*NamingClass=*/nullptr,
13895 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13896 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13897 }
13898 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13899 // The type must be of struct, union or class type in C and C++
13900 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13901 return ExprEmpty();
13902 SourceLocation Loc = MapperId.getLoc();
13903 // Perform argument dependent lookup.
13904 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13905 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13906 // Return the first user-defined mapper with the desired type.
13907 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13908 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13909 if (!D->isInvalidDecl() &&
13910 SemaRef.Context.hasSameType(D->getType(), Type))
13911 return D;
13912 return nullptr;
13913 }))
13914 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13915 // Find the first user-defined mapper with a type derived from the desired
13916 // type.
13917 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13918 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13919 if (!D->isInvalidDecl() &&
13920 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13921 !Type.isMoreQualifiedThan(D->getType()))
13922 return D;
13923 return nullptr;
13924 })) {
13925 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13926 /*DetectVirtual=*/false);
13927 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13928 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13929 VD->getType().getUnqualifiedType()))) {
13930 if (SemaRef.CheckBaseClassAccess(
13931 Loc, VD->getType(), Type, Paths.front(),
13932 /*DiagID=*/0) != Sema::AR_inaccessible) {
13933 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13934 }
13935 }
13936 }
13937 }
13938 // Report error if a mapper is specified, but cannot be found.
13939 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13940 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13941 << Type << MapperId.getName();
13942 return ExprError();
13943 }
13944 return ExprEmpty();
13945}
13946
Samuel Antao661c0902016-05-26 17:39:58 +000013947namespace {
13948// Utility struct that gathers all the related lists associated with a mappable
13949// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013950struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013951 // The list of expressions.
13952 ArrayRef<Expr *> VarList;
13953 // The list of processed expressions.
13954 SmallVector<Expr *, 16> ProcessedVarList;
13955 // The mappble components for each expression.
13956 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13957 // The base declaration of the variable.
13958 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013959 // The reference to the user-defined mapper associated with every expression.
13960 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013961
13962 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13963 // We have a list of components and base declarations for each entry in the
13964 // variable list.
13965 VarComponents.reserve(VarList.size());
13966 VarBaseDeclarations.reserve(VarList.size());
13967 }
13968};
13969}
13970
13971// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013972// \a CKind. In the check process the valid expressions, mappable expression
13973// components, variables, and user-defined mappers are extracted and used to
13974// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13975// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13976// and \a MapperId are expected to be valid if the clause kind is 'map'.
13977static void checkMappableExpressionList(
13978 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13979 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013980 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13981 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013982 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013983 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013984 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13985 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013986 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013987
13988 // If the identifier of user-defined mapper is not specified, it is "default".
13989 // We do not change the actual name in this clause to distinguish whether a
13990 // mapper is specified explicitly, i.e., it is not explicitly specified when
13991 // MapperId.getName() is empty.
13992 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13993 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13994 MapperId.setName(DeclNames.getIdentifier(
13995 &SemaRef.getASTContext().Idents.get("default")));
13996 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013997
13998 // Iterators to find the current unresolved mapper expression.
13999 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
14000 bool UpdateUMIt = false;
14001 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014002
Samuel Antao90927002016-04-26 14:54:23 +000014003 // Keep track of the mappable components and base declarations in this clause.
14004 // Each entry in the list is going to have a list of components associated. We
14005 // record each set of the components so that we can build the clause later on.
14006 // In the end we should have the same amount of declarations and component
14007 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000014008
Alexey Bataeve3727102018-04-18 15:57:46 +000014009 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014010 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014011 SourceLocation ELoc = RE->getExprLoc();
14012
Michael Kruse4304e9d2019-02-19 16:38:20 +000014013 // Find the current unresolved mapper expression.
14014 if (UpdateUMIt && UMIt != UMEnd) {
14015 UMIt++;
14016 assert(
14017 UMIt != UMEnd &&
14018 "Expect the size of UnresolvedMappers to match with that of VarList");
14019 }
14020 UpdateUMIt = true;
14021 if (UMIt != UMEnd)
14022 UnresolvedMapper = *UMIt;
14023
Alexey Bataeve3727102018-04-18 15:57:46 +000014024 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014025
14026 if (VE->isValueDependent() || VE->isTypeDependent() ||
14027 VE->isInstantiationDependent() ||
14028 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000014029 // Try to find the associated user-defined mapper.
14030 ExprResult ER = buildUserDefinedMapperRef(
14031 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14032 VE->getType().getCanonicalType(), UnresolvedMapper);
14033 if (ER.isInvalid())
14034 continue;
14035 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000014036 // We can only analyze this information once the missing information is
14037 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000014038 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014039 continue;
14040 }
14041
Alexey Bataeve3727102018-04-18 15:57:46 +000014042 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014043
Samuel Antao5de996e2016-01-22 20:21:36 +000014044 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000014045 SemaRef.Diag(ELoc,
14046 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000014047 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014048 continue;
14049 }
14050
Samuel Antao90927002016-04-26 14:54:23 +000014051 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
14052 ValueDecl *CurDeclaration = nullptr;
14053
14054 // Obtain the array or member expression bases if required. Also, fill the
14055 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000014056 const Expr *BE = checkMapClauseExpressionBase(
14057 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000014058 if (!BE)
14059 continue;
14060
Samuel Antao90927002016-04-26 14:54:23 +000014061 assert(!CurComponents.empty() &&
14062 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014063
Patrick Lystere13b1e32019-01-02 19:28:48 +000014064 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
14065 // Add store "this" pointer to class in DSAStackTy for future checking
14066 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000014067 // Try to find the associated user-defined mapper.
14068 ExprResult ER = buildUserDefinedMapperRef(
14069 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14070 VE->getType().getCanonicalType(), UnresolvedMapper);
14071 if (ER.isInvalid())
14072 continue;
14073 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000014074 // Skip restriction checking for variable or field declarations
14075 MVLI.ProcessedVarList.push_back(RE);
14076 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14077 MVLI.VarComponents.back().append(CurComponents.begin(),
14078 CurComponents.end());
14079 MVLI.VarBaseDeclarations.push_back(nullptr);
14080 continue;
14081 }
14082
Samuel Antao90927002016-04-26 14:54:23 +000014083 // For the following checks, we rely on the base declaration which is
14084 // expected to be associated with the last component. The declaration is
14085 // expected to be a variable or a field (if 'this' is being mapped).
14086 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
14087 assert(CurDeclaration && "Null decl on map clause.");
14088 assert(
14089 CurDeclaration->isCanonicalDecl() &&
14090 "Expecting components to have associated only canonical declarations.");
14091
14092 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000014093 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000014094
14095 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000014096 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014097
14098 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000014099 // threadprivate variables cannot appear in a map clause.
14100 // OpenMP 4.5 [2.10.5, target update Construct]
14101 // threadprivate variables cannot appear in a from clause.
14102 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014103 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014104 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
14105 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000014106 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014107 continue;
14108 }
14109
Samuel Antao5de996e2016-01-22 20:21:36 +000014110 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
14111 // A list item cannot appear in both a map clause and a data-sharing
14112 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000014113
Samuel Antao5de996e2016-01-22 20:21:36 +000014114 // Check conflicts with other map clause expressions. We check the conflicts
14115 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000014116 // environment, because the restrictions are different. We only have to
14117 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000014118 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014119 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014120 break;
Samuel Antao661c0902016-05-26 17:39:58 +000014121 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014122 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014123 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014124 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014125
Samuel Antao661c0902016-05-26 17:39:58 +000014126 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000014127 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14128 // If the type of a list item is a reference to a type T then the type will
14129 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000014130 auto I = llvm::find_if(
14131 CurComponents,
14132 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
14133 return MC.getAssociatedDeclaration();
14134 });
14135 assert(I != CurComponents.end() && "Null decl on map clause.");
14136 QualType Type =
14137 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014138
Samuel Antao661c0902016-05-26 17:39:58 +000014139 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
14140 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000014141 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000014142 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014143 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000014144 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000014145 continue;
14146
Samuel Antao661c0902016-05-26 17:39:58 +000014147 if (CKind == OMPC_map) {
14148 // target enter data
14149 // OpenMP [2.10.2, Restrictions, p. 99]
14150 // A map-type must be specified in all map clauses and must be either
14151 // to or alloc.
14152 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
14153 if (DKind == OMPD_target_enter_data &&
14154 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
14155 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14156 << (IsMapTypeImplicit ? 1 : 0)
14157 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14158 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014159 continue;
14160 }
Samuel Antao661c0902016-05-26 17:39:58 +000014161
14162 // target exit_data
14163 // OpenMP [2.10.3, Restrictions, p. 102]
14164 // A map-type must be specified in all map clauses and must be either
14165 // from, release, or delete.
14166 if (DKind == OMPD_target_exit_data &&
14167 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
14168 MapType == OMPC_MAP_delete)) {
14169 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14170 << (IsMapTypeImplicit ? 1 : 0)
14171 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14172 << getOpenMPDirectiveName(DKind);
14173 continue;
14174 }
14175
14176 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
14177 // A list item cannot appear in both a map clause and a data-sharing
14178 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000014179 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
14180 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014181 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000014182 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000014183 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000014184 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000014185 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014186 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000014187 continue;
14188 }
14189 }
Michael Kruse01f670d2019-02-22 22:29:42 +000014190 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014191
Michael Kruse01f670d2019-02-22 22:29:42 +000014192 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000014193 ExprResult ER = buildUserDefinedMapperRef(
14194 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14195 Type.getCanonicalType(), UnresolvedMapper);
14196 if (ER.isInvalid())
14197 continue;
14198 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014199
Samuel Antao90927002016-04-26 14:54:23 +000014200 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000014201 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000014202
14203 // Store the components in the stack so that they can be used to check
14204 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000014205 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
14206 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000014207
14208 // Save the components and declaration to create the clause. For purposes of
14209 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000014210 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000014211 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14212 MVLI.VarComponents.back().append(CurComponents.begin(),
14213 CurComponents.end());
14214 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
14215 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014216 }
Samuel Antao661c0902016-05-26 17:39:58 +000014217}
14218
Michael Kruse4304e9d2019-02-19 16:38:20 +000014219OMPClause *Sema::ActOnOpenMPMapClause(
14220 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14221 ArrayRef<SourceLocation> MapTypeModifiersLoc,
14222 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
14223 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
14224 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
14225 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
14226 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
14227 OMPC_MAP_MODIFIER_unknown,
14228 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000014229 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
14230
14231 // Process map-type-modifiers, flag errors for duplicate modifiers.
14232 unsigned Count = 0;
14233 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
14234 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
14235 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
14236 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
14237 continue;
14238 }
14239 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000014240 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000014241 Modifiers[Count] = MapTypeModifiers[I];
14242 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
14243 ++Count;
14244 }
14245
Michael Kruse4304e9d2019-02-19 16:38:20 +000014246 MappableVarListInfo MVLI(VarList);
14247 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014248 MapperIdScopeSpec, MapperId, UnresolvedMappers,
14249 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000014250
Samuel Antao5de996e2016-01-22 20:21:36 +000014251 // We need to produce a map clause even if we don't have variables so that
14252 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000014253 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
14254 MVLI.VarBaseDeclarations, MVLI.VarComponents,
14255 MVLI.UDMapperList, Modifiers, ModifiersLoc,
14256 MapperIdScopeSpec.getWithLocInContext(Context),
14257 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014258}
Kelvin Li099bb8c2015-11-24 20:50:12 +000014259
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014260QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
14261 TypeResult ParsedType) {
14262 assert(ParsedType.isUsable());
14263
14264 QualType ReductionType = GetTypeFromParser(ParsedType.get());
14265 if (ReductionType.isNull())
14266 return QualType();
14267
14268 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
14269 // A type name in a declare reduction directive cannot be a function type, an
14270 // array type, a reference type, or a type qualified with const, volatile or
14271 // restrict.
14272 if (ReductionType.hasQualifiers()) {
14273 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
14274 return QualType();
14275 }
14276
14277 if (ReductionType->isFunctionType()) {
14278 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
14279 return QualType();
14280 }
14281 if (ReductionType->isReferenceType()) {
14282 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
14283 return QualType();
14284 }
14285 if (ReductionType->isArrayType()) {
14286 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
14287 return QualType();
14288 }
14289 return ReductionType;
14290}
14291
14292Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
14293 Scope *S, DeclContext *DC, DeclarationName Name,
14294 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
14295 AccessSpecifier AS, Decl *PrevDeclInScope) {
14296 SmallVector<Decl *, 8> Decls;
14297 Decls.reserve(ReductionTypes.size());
14298
14299 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000014300 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014301 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
14302 // A reduction-identifier may not be re-declared in the current scope for the
14303 // same type or for a type that is compatible according to the base language
14304 // rules.
14305 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14306 OMPDeclareReductionDecl *PrevDRD = nullptr;
14307 bool InCompoundScope = true;
14308 if (S != nullptr) {
14309 // Find previous declaration with the same name not referenced in other
14310 // declarations.
14311 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14312 InCompoundScope =
14313 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14314 LookupName(Lookup, S);
14315 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14316 /*AllowInlineNamespace=*/false);
14317 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000014318 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014319 while (Filter.hasNext()) {
14320 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
14321 if (InCompoundScope) {
14322 auto I = UsedAsPrevious.find(PrevDecl);
14323 if (I == UsedAsPrevious.end())
14324 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000014325 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014326 UsedAsPrevious[D] = true;
14327 }
14328 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14329 PrevDecl->getLocation();
14330 }
14331 Filter.done();
14332 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014333 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014334 if (!PrevData.second) {
14335 PrevDRD = PrevData.first;
14336 break;
14337 }
14338 }
14339 }
14340 } else if (PrevDeclInScope != nullptr) {
14341 auto *PrevDRDInScope = PrevDRD =
14342 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
14343 do {
14344 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
14345 PrevDRDInScope->getLocation();
14346 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
14347 } while (PrevDRDInScope != nullptr);
14348 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014349 for (const auto &TyData : ReductionTypes) {
14350 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014351 bool Invalid = false;
14352 if (I != PreviousRedeclTypes.end()) {
14353 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
14354 << TyData.first;
14355 Diag(I->second, diag::note_previous_definition);
14356 Invalid = true;
14357 }
14358 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
14359 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
14360 Name, TyData.first, PrevDRD);
14361 DC->addDecl(DRD);
14362 DRD->setAccess(AS);
14363 Decls.push_back(DRD);
14364 if (Invalid)
14365 DRD->setInvalidDecl();
14366 else
14367 PrevDRD = DRD;
14368 }
14369
14370 return DeclGroupPtrTy::make(
14371 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
14372}
14373
14374void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
14375 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14376
14377 // Enter new function scope.
14378 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014379 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014380 getCurFunction()->setHasOMPDeclareReductionCombiner();
14381
14382 if (S != nullptr)
14383 PushDeclContext(S, DRD);
14384 else
14385 CurContext = DRD;
14386
Faisal Valid143a0c2017-04-01 21:30:49 +000014387 PushExpressionEvaluationContext(
14388 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014389
14390 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014391 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
14392 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
14393 // uses semantics of argument handles by value, but it should be passed by
14394 // reference. C lang does not support references, so pass all parameters as
14395 // pointers.
14396 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014397 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014398 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014399 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
14400 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
14401 // uses semantics of argument handles by value, but it should be passed by
14402 // reference. C lang does not support references, so pass all parameters as
14403 // pointers.
14404 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014405 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014406 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
14407 if (S != nullptr) {
14408 PushOnScopeChains(OmpInParm, S);
14409 PushOnScopeChains(OmpOutParm, S);
14410 } else {
14411 DRD->addDecl(OmpInParm);
14412 DRD->addDecl(OmpOutParm);
14413 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014414 Expr *InE =
14415 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
14416 Expr *OutE =
14417 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
14418 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014419}
14420
14421void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
14422 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14423 DiscardCleanupsInEvaluationContext();
14424 PopExpressionEvaluationContext();
14425
14426 PopDeclContext();
14427 PopFunctionScopeInfo();
14428
14429 if (Combiner != nullptr)
14430 DRD->setCombiner(Combiner);
14431 else
14432 DRD->setInvalidDecl();
14433}
14434
Alexey Bataev070f43a2017-09-06 14:49:58 +000014435VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014436 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14437
14438 // Enter new function scope.
14439 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014440 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014441
14442 if (S != nullptr)
14443 PushDeclContext(S, DRD);
14444 else
14445 CurContext = DRD;
14446
Faisal Valid143a0c2017-04-01 21:30:49 +000014447 PushExpressionEvaluationContext(
14448 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014449
14450 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014451 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
14452 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
14453 // uses semantics of argument handles by value, but it should be passed by
14454 // reference. C lang does not support references, so pass all parameters as
14455 // pointers.
14456 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014457 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014458 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014459 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
14460 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
14461 // uses semantics of argument handles by value, but it should be passed by
14462 // reference. C lang does not support references, so pass all parameters as
14463 // pointers.
14464 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014465 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014466 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014467 if (S != nullptr) {
14468 PushOnScopeChains(OmpPrivParm, S);
14469 PushOnScopeChains(OmpOrigParm, S);
14470 } else {
14471 DRD->addDecl(OmpPrivParm);
14472 DRD->addDecl(OmpOrigParm);
14473 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014474 Expr *OrigE =
14475 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
14476 Expr *PrivE =
14477 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
14478 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000014479 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014480}
14481
Alexey Bataev070f43a2017-09-06 14:49:58 +000014482void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
14483 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014484 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14485 DiscardCleanupsInEvaluationContext();
14486 PopExpressionEvaluationContext();
14487
14488 PopDeclContext();
14489 PopFunctionScopeInfo();
14490
Alexey Bataev070f43a2017-09-06 14:49:58 +000014491 if (Initializer != nullptr) {
14492 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14493 } else if (OmpPrivParm->hasInit()) {
14494 DRD->setInitializer(OmpPrivParm->getInit(),
14495 OmpPrivParm->isDirectInit()
14496 ? OMPDeclareReductionDecl::DirectInit
14497 : OMPDeclareReductionDecl::CopyInit);
14498 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014499 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000014500 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014501}
14502
14503Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14504 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014505 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014506 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014507 if (S)
14508 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14509 /*AddToContext=*/false);
14510 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014511 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014512 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014513 }
14514 return DeclReductions;
14515}
14516
Michael Kruse251e1482019-02-01 20:25:04 +000014517TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14518 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14519 QualType T = TInfo->getType();
14520 if (D.isInvalidType())
14521 return true;
14522
14523 if (getLangOpts().CPlusPlus) {
14524 // Check that there are no default arguments (C++ only).
14525 CheckExtraCXXDefaultArguments(D);
14526 }
14527
14528 return CreateParsedType(T, TInfo);
14529}
14530
14531QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14532 TypeResult ParsedType) {
14533 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14534
14535 QualType MapperType = GetTypeFromParser(ParsedType.get());
14536 assert(!MapperType.isNull() && "Expect valid mapper type");
14537
14538 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14539 // The type must be of struct, union or class type in C and C++
14540 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14541 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14542 return QualType();
14543 }
14544 return MapperType;
14545}
14546
14547OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14548 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14549 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14550 Decl *PrevDeclInScope) {
14551 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14552 forRedeclarationInCurContext());
14553 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14554 // A mapper-identifier may not be redeclared in the current scope for the
14555 // same type or for a type that is compatible according to the base language
14556 // rules.
14557 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14558 OMPDeclareMapperDecl *PrevDMD = nullptr;
14559 bool InCompoundScope = true;
14560 if (S != nullptr) {
14561 // Find previous declaration with the same name not referenced in other
14562 // declarations.
14563 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14564 InCompoundScope =
14565 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14566 LookupName(Lookup, S);
14567 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14568 /*AllowInlineNamespace=*/false);
14569 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14570 LookupResult::Filter Filter = Lookup.makeFilter();
14571 while (Filter.hasNext()) {
14572 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14573 if (InCompoundScope) {
14574 auto I = UsedAsPrevious.find(PrevDecl);
14575 if (I == UsedAsPrevious.end())
14576 UsedAsPrevious[PrevDecl] = false;
14577 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14578 UsedAsPrevious[D] = true;
14579 }
14580 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14581 PrevDecl->getLocation();
14582 }
14583 Filter.done();
14584 if (InCompoundScope) {
14585 for (const auto &PrevData : UsedAsPrevious) {
14586 if (!PrevData.second) {
14587 PrevDMD = PrevData.first;
14588 break;
14589 }
14590 }
14591 }
14592 } else if (PrevDeclInScope) {
14593 auto *PrevDMDInScope = PrevDMD =
14594 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14595 do {
14596 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14597 PrevDMDInScope->getLocation();
14598 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14599 } while (PrevDMDInScope != nullptr);
14600 }
14601 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14602 bool Invalid = false;
14603 if (I != PreviousRedeclTypes.end()) {
14604 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14605 << MapperType << Name;
14606 Diag(I->second, diag::note_previous_definition);
14607 Invalid = true;
14608 }
14609 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14610 MapperType, VN, PrevDMD);
14611 DC->addDecl(DMD);
14612 DMD->setAccess(AS);
14613 if (Invalid)
14614 DMD->setInvalidDecl();
14615
14616 // Enter new function scope.
14617 PushFunctionScope();
14618 setFunctionHasBranchProtectedScope();
14619
14620 CurContext = DMD;
14621
14622 return DMD;
14623}
14624
14625void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14626 Scope *S,
14627 QualType MapperType,
14628 SourceLocation StartLoc,
14629 DeclarationName VN) {
14630 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14631 if (S)
14632 PushOnScopeChains(VD, S);
14633 else
14634 DMD->addDecl(VD);
14635 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14636 DMD->setMapperVarRef(MapperVarRefExpr);
14637}
14638
14639Sema::DeclGroupPtrTy
14640Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14641 ArrayRef<OMPClause *> ClauseList) {
14642 PopDeclContext();
14643 PopFunctionScopeInfo();
14644
14645 if (D) {
14646 if (S)
14647 PushOnScopeChains(D, S, /*AddToContext=*/false);
14648 D->CreateClauses(Context, ClauseList);
14649 }
14650
14651 return DeclGroupPtrTy::make(DeclGroupRef(D));
14652}
14653
David Majnemer9d168222016-08-05 17:44:54 +000014654OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014655 SourceLocation StartLoc,
14656 SourceLocation LParenLoc,
14657 SourceLocation EndLoc) {
14658 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014659 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014660
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014661 // OpenMP [teams Constrcut, Restrictions]
14662 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014663 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014664 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014665 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014666
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014667 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014668 OpenMPDirectiveKind CaptureRegion =
14669 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14670 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014671 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014672 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014673 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14674 HelperValStmt = buildPreInits(Context, Captures);
14675 }
14676
14677 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14678 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014679}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014680
14681OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14682 SourceLocation StartLoc,
14683 SourceLocation LParenLoc,
14684 SourceLocation EndLoc) {
14685 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014686 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014687
14688 // OpenMP [teams Constrcut, Restrictions]
14689 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014690 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014691 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014692 return nullptr;
14693
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014694 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014695 OpenMPDirectiveKind CaptureRegion =
14696 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14697 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014698 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014699 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014700 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14701 HelperValStmt = buildPreInits(Context, Captures);
14702 }
14703
14704 return new (Context) OMPThreadLimitClause(
14705 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014706}
Alexey Bataeva0569352015-12-01 10:17:31 +000014707
14708OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14709 SourceLocation StartLoc,
14710 SourceLocation LParenLoc,
14711 SourceLocation EndLoc) {
14712 Expr *ValExpr = Priority;
14713
14714 // OpenMP [2.9.1, task Constrcut]
14715 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014716 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014717 /*StrictlyPositive=*/false))
14718 return nullptr;
14719
14720 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14721}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014722
14723OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14724 SourceLocation StartLoc,
14725 SourceLocation LParenLoc,
14726 SourceLocation EndLoc) {
14727 Expr *ValExpr = Grainsize;
14728
14729 // OpenMP [2.9.2, taskloop Constrcut]
14730 // The parameter of the grainsize clause must be a positive integer
14731 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014732 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014733 /*StrictlyPositive=*/true))
14734 return nullptr;
14735
14736 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14737}
Alexey Bataev382967a2015-12-08 12:06:20 +000014738
14739OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14740 SourceLocation StartLoc,
14741 SourceLocation LParenLoc,
14742 SourceLocation EndLoc) {
14743 Expr *ValExpr = NumTasks;
14744
14745 // OpenMP [2.9.2, taskloop Constrcut]
14746 // The parameter of the num_tasks clause must be a positive integer
14747 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014748 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014749 /*StrictlyPositive=*/true))
14750 return nullptr;
14751
14752 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14753}
14754
Alexey Bataev28c75412015-12-15 08:19:24 +000014755OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14756 SourceLocation LParenLoc,
14757 SourceLocation EndLoc) {
14758 // OpenMP [2.13.2, critical construct, Description]
14759 // ... where hint-expression is an integer constant expression that evaluates
14760 // to a valid lock hint.
14761 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14762 if (HintExpr.isInvalid())
14763 return nullptr;
14764 return new (Context)
14765 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14766}
14767
Carlo Bertollib4adf552016-01-15 18:50:31 +000014768OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14769 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14770 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14771 SourceLocation EndLoc) {
14772 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14773 std::string Values;
14774 Values += "'";
14775 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14776 Values += "'";
14777 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14778 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14779 return nullptr;
14780 }
14781 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014782 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014783 if (ChunkSize) {
14784 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14785 !ChunkSize->isInstantiationDependent() &&
14786 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014787 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014788 ExprResult Val =
14789 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14790 if (Val.isInvalid())
14791 return nullptr;
14792
14793 ValExpr = Val.get();
14794
14795 // OpenMP [2.7.1, Restrictions]
14796 // chunk_size must be a loop invariant integer expression with a positive
14797 // value.
14798 llvm::APSInt Result;
14799 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14800 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14801 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14802 << "dist_schedule" << ChunkSize->getSourceRange();
14803 return nullptr;
14804 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014805 } else if (getOpenMPCaptureRegionForClause(
14806 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14807 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014808 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014809 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014810 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014811 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14812 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014813 }
14814 }
14815 }
14816
14817 return new (Context)
14818 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014819 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014820}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014821
14822OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14823 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14824 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14825 SourceLocation KindLoc, SourceLocation EndLoc) {
14826 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014827 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014828 std::string Value;
14829 SourceLocation Loc;
14830 Value += "'";
14831 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14832 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014833 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014834 Loc = MLoc;
14835 } else {
14836 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014837 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014838 Loc = KindLoc;
14839 }
14840 Value += "'";
14841 Diag(Loc, diag::err_omp_unexpected_clause_value)
14842 << Value << getOpenMPClauseName(OMPC_defaultmap);
14843 return nullptr;
14844 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014845 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014846
14847 return new (Context)
14848 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14849}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014850
14851bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14852 DeclContext *CurLexicalContext = getCurLexicalContext();
14853 if (!CurLexicalContext->isFileContext() &&
14854 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014855 !CurLexicalContext->isExternCXXContext() &&
14856 !isa<CXXRecordDecl>(CurLexicalContext) &&
14857 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14858 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14859 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014860 Diag(Loc, diag::err_omp_region_not_file_context);
14861 return false;
14862 }
Kelvin Libc38e632018-09-10 02:07:09 +000014863 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014864 return true;
14865}
14866
14867void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014868 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014869 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014870 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014871}
14872
David Majnemer9d168222016-08-05 17:44:54 +000014873void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14874 CXXScopeSpec &ScopeSpec,
14875 const DeclarationNameInfo &Id,
14876 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14877 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014878 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14879 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14880
14881 if (Lookup.isAmbiguous())
14882 return;
14883 Lookup.suppressDiagnostics();
14884
14885 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000014886 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014887 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000014888 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014889 CTK_ErrorRecovery)) {
14890 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14891 << Id.getName());
14892 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14893 return;
14894 }
14895
14896 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14897 return;
14898 }
14899
14900 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014901 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14902 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014903 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14904 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014905 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14906 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14907 cast<ValueDecl>(ND));
14908 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014909 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014910 ND->addAttr(A);
14911 if (ASTMutationListener *ML = Context.getASTMutationListener())
14912 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014913 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014914 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014915 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14916 << Id.getName();
14917 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014918 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014919 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014920 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014921}
14922
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014923static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14924 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014925 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014926 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014927 auto *VD = cast<VarDecl>(D);
14928 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14929 return;
14930 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14931 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014932}
14933
14934static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14935 Sema &SemaRef, DSAStackTy *Stack,
14936 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014937 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14938 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14939 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014940}
14941
Kelvin Li1ce87c72017-12-12 20:08:12 +000014942void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14943 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014944 if (!D || D->isInvalidDecl())
14945 return;
14946 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014947 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014948 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014949 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014950 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14951 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014952 return;
14953 // 2.10.6: threadprivate variable cannot appear in a declare target
14954 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014955 if (DSAStack->isThreadPrivate(VD)) {
14956 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014957 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014958 return;
14959 }
14960 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014961 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14962 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014963 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014964 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14965 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14966 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014967 assert(IdLoc.isValid() && "Source location is expected");
14968 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14969 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14970 return;
14971 }
14972 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014973 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14974 // Problem if any with var declared with incomplete type will be reported
14975 // as normal, so no need to check it here.
14976 if ((E || !VD->getType()->isIncompleteType()) &&
14977 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14978 return;
14979 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14980 // Checking declaration inside declare target region.
14981 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14982 isa<FunctionTemplateDecl>(D)) {
14983 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14984 Context, OMPDeclareTargetDeclAttr::MT_To);
14985 D->addAttr(A);
14986 if (ASTMutationListener *ML = Context.getASTMutationListener())
14987 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14988 }
14989 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014990 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014991 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014992 if (!E)
14993 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014994 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14995}
Samuel Antao661c0902016-05-26 17:39:58 +000014996
14997OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014998 CXXScopeSpec &MapperIdScopeSpec,
14999 DeclarationNameInfo &MapperId,
15000 const OMPVarListLocTy &Locs,
15001 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000015002 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015003 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
15004 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000015005 if (MVLI.ProcessedVarList.empty())
15006 return nullptr;
15007
Michael Kruse01f670d2019-02-22 22:29:42 +000015008 return OMPToClause::Create(
15009 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15010 MVLI.VarComponents, MVLI.UDMapperList,
15011 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000015012}
Samuel Antaoec172c62016-05-26 17:49:04 +000015013
15014OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000015015 CXXScopeSpec &MapperIdScopeSpec,
15016 DeclarationNameInfo &MapperId,
15017 const OMPVarListLocTy &Locs,
15018 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015019 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015020 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
15021 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000015022 if (MVLI.ProcessedVarList.empty())
15023 return nullptr;
15024
Michael Kruse0336c752019-02-25 20:34:15 +000015025 return OMPFromClause::Create(
15026 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15027 MVLI.VarComponents, MVLI.UDMapperList,
15028 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000015029}
Carlo Bertolli2404b172016-07-13 15:37:16 +000015030
15031OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015032 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000015033 MappableVarListInfo MVLI(VarList);
15034 SmallVector<Expr *, 8> PrivateCopies;
15035 SmallVector<Expr *, 8> Inits;
15036
Alexey Bataeve3727102018-04-18 15:57:46 +000015037 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015038 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
15039 SourceLocation ELoc;
15040 SourceRange ERange;
15041 Expr *SimpleRefExpr = RefExpr;
15042 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15043 if (Res.second) {
15044 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000015045 MVLI.ProcessedVarList.push_back(RefExpr);
15046 PrivateCopies.push_back(nullptr);
15047 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015048 }
15049 ValueDecl *D = Res.first;
15050 if (!D)
15051 continue;
15052
15053 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000015054 Type = Type.getNonReferenceType().getUnqualifiedType();
15055
15056 auto *VD = dyn_cast<VarDecl>(D);
15057
15058 // Item should be a pointer or reference to pointer.
15059 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015060 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
15061 << 0 << RefExpr->getSourceRange();
15062 continue;
15063 }
Samuel Antaocc10b852016-07-28 14:23:26 +000015064
15065 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000015066 auto VDPrivate =
15067 buildVarDecl(*this, ELoc, Type, D->getName(),
15068 D->hasAttrs() ? &D->getAttrs() : nullptr,
15069 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000015070 if (VDPrivate->isInvalidDecl())
15071 continue;
15072
15073 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000015074 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000015075 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15076
15077 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000015078 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000015079 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000015080 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
15081 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000015082 AddInitializerToDecl(VDPrivate,
15083 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000015084 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000015085
15086 // If required, build a capture to implement the privatization initialized
15087 // with the current list item value.
15088 DeclRefExpr *Ref = nullptr;
15089 if (!VD)
15090 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15091 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
15092 PrivateCopies.push_back(VDPrivateRefExpr);
15093 Inits.push_back(VDInitRefExpr);
15094
15095 // We need to add a data sharing attribute for this variable to make sure it
15096 // is correctly captured. A variable that shows up in a use_device_ptr has
15097 // similar properties of a first private variable.
15098 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15099
15100 // Create a mappable component for the list item. List items in this clause
15101 // only need a component.
15102 MVLI.VarBaseDeclarations.push_back(D);
15103 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15104 MVLI.VarComponents.back().push_back(
15105 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000015106 }
15107
Samuel Antaocc10b852016-07-28 14:23:26 +000015108 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000015109 return nullptr;
15110
Samuel Antaocc10b852016-07-28 14:23:26 +000015111 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000015112 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
15113 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015114}
Carlo Bertolli70594e92016-07-13 17:16:49 +000015115
15116OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015117 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000015118 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000015119 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000015120 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000015121 SourceLocation ELoc;
15122 SourceRange ERange;
15123 Expr *SimpleRefExpr = RefExpr;
15124 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15125 if (Res.second) {
15126 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000015127 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015128 }
15129 ValueDecl *D = Res.first;
15130 if (!D)
15131 continue;
15132
15133 QualType Type = D->getType();
15134 // item should be a pointer or array or reference to pointer or array
15135 if (!Type.getNonReferenceType()->isPointerType() &&
15136 !Type.getNonReferenceType()->isArrayType()) {
15137 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
15138 << 0 << RefExpr->getSourceRange();
15139 continue;
15140 }
Samuel Antao6890b092016-07-28 14:25:09 +000015141
15142 // Check if the declaration in the clause does not show up in any data
15143 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000015144 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000015145 if (isOpenMPPrivate(DVar.CKind)) {
15146 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15147 << getOpenMPClauseName(DVar.CKind)
15148 << getOpenMPClauseName(OMPC_is_device_ptr)
15149 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015150 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000015151 continue;
15152 }
15153
Alexey Bataeve3727102018-04-18 15:57:46 +000015154 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000015155 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000015156 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000015157 [&ConflictExpr](
15158 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
15159 OpenMPClauseKind) -> bool {
15160 ConflictExpr = R.front().getAssociatedExpression();
15161 return true;
15162 })) {
15163 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
15164 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
15165 << ConflictExpr->getSourceRange();
15166 continue;
15167 }
15168
15169 // Store the components in the stack so that they can be used to check
15170 // against other clauses later on.
15171 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
15172 DSAStack->addMappableExpressionComponents(
15173 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
15174
15175 // Record the expression we've just processed.
15176 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
15177
15178 // Create a mappable component for the list item. List items in this clause
15179 // only need a component. We use a null declaration to signal fields in
15180 // 'this'.
15181 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
15182 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
15183 "Unexpected device pointer expression!");
15184 MVLI.VarBaseDeclarations.push_back(
15185 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
15186 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15187 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015188 }
15189
Samuel Antao6890b092016-07-28 14:25:09 +000015190 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000015191 return nullptr;
15192
Michael Kruse4304e9d2019-02-19 16:38:20 +000015193 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
15194 MVLI.VarBaseDeclarations,
15195 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015196}
Alexey Bataeve04483e2019-03-27 14:14:31 +000015197
15198OMPClause *Sema::ActOnOpenMPAllocateClause(
15199 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15200 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15201 if (Allocator) {
15202 // OpenMP [2.11.4 allocate Clause, Description]
15203 // allocator is an expression of omp_allocator_handle_t type.
15204 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
15205 return nullptr;
15206
15207 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
15208 if (AllocatorRes.isInvalid())
15209 return nullptr;
15210 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
15211 DSAStack->getOMPAllocatorHandleT(),
15212 Sema::AA_Initializing,
15213 /*AllowExplicit=*/true);
15214 if (AllocatorRes.isInvalid())
15215 return nullptr;
15216 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000015217 } else {
15218 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
15219 // allocate clauses that appear on a target construct or on constructs in a
15220 // target region must specify an allocator expression unless a requires
15221 // directive with the dynamic_allocators clause is present in the same
15222 // compilation unit.
15223 if (LangOpts.OpenMPIsDevice &&
15224 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
15225 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000015226 }
15227 // Analyze and build list of variables.
15228 SmallVector<Expr *, 8> Vars;
15229 for (Expr *RefExpr : VarList) {
15230 assert(RefExpr && "NULL expr in OpenMP private clause.");
15231 SourceLocation ELoc;
15232 SourceRange ERange;
15233 Expr *SimpleRefExpr = RefExpr;
15234 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15235 if (Res.second) {
15236 // It will be analyzed later.
15237 Vars.push_back(RefExpr);
15238 }
15239 ValueDecl *D = Res.first;
15240 if (!D)
15241 continue;
15242
15243 auto *VD = dyn_cast<VarDecl>(D);
15244 DeclRefExpr *Ref = nullptr;
15245 if (!VD && !CurContext->isDependentContext())
15246 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15247 Vars.push_back((VD || CurContext->isDependentContext())
15248 ? RefExpr->IgnoreParens()
15249 : Ref);
15250 }
15251
15252 if (Vars.empty())
15253 return nullptr;
15254
15255 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
15256 ColonLoc, EndLoc, Vars);
15257}