blob: 5f37b949a62555ee6d79b43a2eada25741498e5d [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000052/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000053class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000054public:
Alexey Bataeve3727102018-04-18 15:57:46 +000055 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000056 OpenMPDirectiveKind DKind = OMPD_unknown;
57 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000058 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000060 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000061 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000062 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
63 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
64 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000065 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
66 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000067 };
Alexey Bataeve3727102018-04-18 15:57:46 +000068 using OperatorOffsetTy =
69 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000070 using DoacrossDependMapTy =
71 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000072
Alexey Bataev758e55e2013-09-06 18:03:48 +000073private:
Alexey Bataeve3727102018-04-18 15:57:46 +000074 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000075 OpenMPClauseKind Attributes = OMPC_unknown;
76 /// Pointer to a reference expression and a flag which shows that the
77 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000078 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000079 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000080 };
Alexey Bataeve3727102018-04-18 15:57:46 +000081 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
82 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
83 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
84 using LoopControlVariablesMapTy =
85 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000086 /// Struct that associates a component with the clause kind where they are
87 /// found.
88 struct MappedExprComponentTy {
89 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
90 OpenMPClauseKind Kind = OMPC_unknown;
91 };
Alexey Bataeve3727102018-04-18 15:57:46 +000092 using MappedExprComponentsTy =
93 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
94 using CriticalsWithHintsTy =
95 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +000096 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +000097 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +000098 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +000099 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 ReductionData() = default;
101 void set(BinaryOperatorKind BO, SourceRange RR) {
102 ReductionRange = RR;
103 ReductionOp = BO;
104 }
105 void set(const Expr *RefExpr, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = RefExpr;
108 }
109 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000110 using DeclReductionMapTy =
111 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500112 struct DefaultmapInfo {
113 OpenMPDefaultmapClauseModifier ImplicitBehavior =
114 OMPC_DEFAULTMAP_MODIFIER_unknown;
115 SourceLocation SLoc;
116 DefaultmapInfo() = default;
117 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
118 : ImplicitBehavior(M), SLoc(Loc) {}
119 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120
Alexey Bataeve3727102018-04-18 15:57:46 +0000121 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000122 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000123 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000124 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000125 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000126 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000127 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000128 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500129 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000130 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000131 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000132 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000133 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000134 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
135 /// get the data (loop counters etc.) about enclosing loop-based construct.
136 /// This data is required during codegen.
137 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000138 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000139 /// 'ordered' clause, the second one is true if the regions has 'ordered'
140 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000141 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000142 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000143 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000144 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000145 bool NowaitRegion = false;
146 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000147 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000148 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000149 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000150 /// Reference to the taskgroup task_reduction reference expression.
151 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000152 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000153 /// List of globals marked as declare target link in this target region
154 /// (isOpenMPTargetExecutionDirective(Directive) == true).
155 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000156 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000157 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000158 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
159 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000160 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161 };
162
Alexey Bataeve3727102018-04-18 15:57:46 +0000163 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000165 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000166 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000167 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
168 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000169 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000170 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000171 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000172 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000173 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000174 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000175 /// captured by reference.
176 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000177 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000178 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000179
Richard Smith375dec52019-05-30 23:21:14 +0000180 /// Iterators over the stack iterate in order from innermost to outermost
181 /// directive.
182 using const_iterator = StackTy::const_reverse_iterator;
183 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000184 return Stack.empty() ? const_iterator()
185 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000186 }
187 const_iterator end() const {
188 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
189 }
190 using iterator = StackTy::reverse_iterator;
191 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000192 return Stack.empty() ? iterator()
193 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000194 }
195 iterator end() {
196 return Stack.empty() ? iterator() : Stack.back().first.rend();
197 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198
Richard Smith375dec52019-05-30 23:21:14 +0000199 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000200
Alexey Bataev4b465392017-04-26 15:06:24 +0000201 bool isStackEmpty() const {
202 return Stack.empty() ||
203 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000204 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000205 }
Richard Smith375dec52019-05-30 23:21:14 +0000206 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000207 return isStackEmpty() ? 0
208 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000209 }
210
211 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000212 size_t Size = getStackSize();
213 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000214 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000215 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000216 }
217 const SharingMapTy *getTopOfStackOrNull() const {
218 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
219 }
220 SharingMapTy &getTopOfStack() {
221 assert(!isStackEmpty() && "no current directive");
222 return *getTopOfStackOrNull();
223 }
224 const SharingMapTy &getTopOfStack() const {
225 return const_cast<DSAStackTy&>(*this).getTopOfStack();
226 }
227
228 SharingMapTy *getSecondOnStackOrNull() {
229 size_t Size = getStackSize();
230 if (Size <= 1)
231 return nullptr;
232 return &Stack.back().first[Size - 2];
233 }
234 const SharingMapTy *getSecondOnStackOrNull() const {
235 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
236 }
237
238 /// Get the stack element at a certain level (previously returned by
239 /// \c getNestingLevel).
240 ///
241 /// Note that nesting levels count from outermost to innermost, and this is
242 /// the reverse of our iteration order where new inner levels are pushed at
243 /// the front of the stack.
244 SharingMapTy &getStackElemAtLevel(unsigned Level) {
245 assert(Level < getStackSize() && "no such stack element");
246 return Stack.back().first[Level];
247 }
248 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
249 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
250 }
251
252 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
253
254 /// Checks if the variable is a local for OpenMP region.
255 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000256
Kelvin Li1408f912018-09-26 04:28:39 +0000257 /// Vector of previously declared requires directives
258 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000259 /// omp_allocator_handle_t type.
260 QualType OMPAllocatorHandleT;
261 /// Expression for the predefined allocators.
262 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
263 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000264 /// Vector of previously encountered target directives
265 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000266
Alexey Bataev758e55e2013-09-06 18:03:48 +0000267public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000268 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000269
Alexey Bataev27ef9512019-03-20 20:14:22 +0000270 /// Sets omp_allocator_handle_t type.
271 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
272 /// Gets omp_allocator_handle_t type.
273 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
274 /// Sets the given default allocator.
275 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
276 Expr *Allocator) {
277 OMPPredefinedAllocators[AllocatorKind] = Allocator;
278 }
279 /// Returns the specified default allocator.
280 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
281 return OMPPredefinedAllocators[AllocatorKind];
282 }
283
Alexey Bataevaac108a2015-06-23 04:51:00 +0000284 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000285 OpenMPClauseKind getClauseParsingMode() const {
286 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
287 return ClauseKindMode;
288 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000289 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290
Richard Smith0621a8f2019-05-31 00:45:10 +0000291 bool isBodyComplete() const {
292 const SharingMapTy *Top = getTopOfStackOrNull();
293 return Top && Top->BodyComplete;
294 }
295 void setBodyComplete() {
296 getTopOfStack().BodyComplete = true;
297 }
298
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000299 bool isForceVarCapturing() const { return ForceCapturing; }
300 void setForceVarCapturing(bool V) { ForceCapturing = V; }
301
Alexey Bataev60705422018-10-30 15:50:12 +0000302 void setForceCaptureByReferenceInTargetExecutable(bool V) {
303 ForceCaptureByReferenceInTargetExecutable = V;
304 }
305 bool isForceCaptureByReferenceInTargetExecutable() const {
306 return ForceCaptureByReferenceInTargetExecutable;
307 }
308
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000310 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000311 assert(!IgnoredStackElements &&
312 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000313 if (Stack.empty() ||
314 Stack.back().second != CurrentNonCapturingFunctionScope)
315 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
316 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
317 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000318 }
319
320 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000321 assert(!IgnoredStackElements &&
322 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000323 assert(!Stack.back().first.empty() &&
324 "Data-sharing attributes stack is empty!");
325 Stack.back().first.pop_back();
326 }
327
Richard Smith0621a8f2019-05-31 00:45:10 +0000328 /// RAII object to temporarily leave the scope of a directive when we want to
329 /// logically operate in its parent.
330 class ParentDirectiveScope {
331 DSAStackTy &Self;
332 bool Active;
333 public:
334 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
335 : Self(Self), Active(false) {
336 if (Activate)
337 enable();
338 }
339 ~ParentDirectiveScope() { disable(); }
340 void disable() {
341 if (Active) {
342 --Self.IgnoredStackElements;
343 Active = false;
344 }
345 }
346 void enable() {
347 if (!Active) {
348 ++Self.IgnoredStackElements;
349 Active = true;
350 }
351 }
352 };
353
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000354 /// Marks that we're started loop parsing.
355 void loopInit() {
356 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
357 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000358 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000359 }
360 /// Start capturing of the variables in the loop context.
361 void loopStart() {
362 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
363 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000364 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000365 }
366 /// true, if variables are captured, false otherwise.
367 bool isLoopStarted() const {
368 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
369 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000370 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000371 }
372 /// Marks (or clears) declaration as possibly loop counter.
373 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000374 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000375 D ? D->getCanonicalDecl() : D;
376 }
377 /// Gets the possible loop counter decl.
378 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000379 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000380 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000381 /// Start new OpenMP region stack in new non-capturing function.
382 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000383 assert(!IgnoredStackElements &&
384 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000385 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
386 assert(!isa<CapturingScopeInfo>(CurFnScope));
387 CurrentNonCapturingFunctionScope = CurFnScope;
388 }
389 /// Pop region stack for non-capturing function.
390 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000391 assert(!IgnoredStackElements &&
392 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 if (!Stack.empty() && Stack.back().second == OldFSI) {
394 assert(Stack.back().first.empty());
395 Stack.pop_back();
396 }
397 CurrentNonCapturingFunctionScope = nullptr;
398 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
399 if (!isa<CapturingScopeInfo>(FSI)) {
400 CurrentNonCapturingFunctionScope = FSI;
401 break;
402 }
403 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000404 }
405
Alexey Bataeve3727102018-04-18 15:57:46 +0000406 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000407 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000408 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000409 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000410 getCriticalWithHint(const DeclarationNameInfo &Name) const {
411 auto I = Criticals.find(Name.getAsString());
412 if (I != Criticals.end())
413 return I->second;
414 return std::make_pair(nullptr, llvm::APSInt());
415 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000416 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000417 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000418 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000419 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000420
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000421 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000422 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000423 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000424 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000425 /// \return The index of the loop control variable in the list of associated
426 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000427 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000428 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000429 /// parent region.
430 /// \return The index of the loop control variable in the list of associated
431 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000432 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000434 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000435 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000438 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000439 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000440
Alexey Bataevfa312f32017-07-21 18:48:21 +0000441 /// Adds additional information for the reduction items with the reduction id
442 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000443 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000444 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000445 /// Adds additional information for the reduction items with the reduction id
446 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000447 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000448 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000449 /// Returns the location and reduction operation from the innermost parent
450 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000451 const DSAVarData
452 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
453 BinaryOperatorKind &BOK,
454 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000455 /// Returns the location and reduction operation from the innermost parent
456 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000457 const DSAVarData
458 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
459 const Expr *&ReductionRef,
460 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000461 /// Return reduction reference expression for the current taskgroup.
462 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000463 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000464 "taskgroup reference expression requested for non taskgroup "
465 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000466 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000467 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000468 /// Checks if the given \p VD declaration is actually a taskgroup reduction
469 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000470 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000471 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
472 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000473 ->getDecl() == VD;
474 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000476 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000477 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000478 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000479 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000480 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000481 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000482 /// match specified \a CPred predicate in any directive which matches \a DPred
483 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000484 const DSAVarData
485 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
486 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
487 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000488 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000489 /// match specified \a CPred predicate in any innermost directive which
490 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000491 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000492 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000493 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
494 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000495 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000496 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000497 /// attributes which match specified \a CPred predicate at the specified
498 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000499 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000500 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000501 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000504 /// specified \a DPred predicate.
505 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000506 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000507 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000509 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000510 bool hasDirective(
511 const llvm::function_ref<bool(
512 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
513 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000514 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000518 const SharingMapTy *Top = getTopOfStackOrNull();
519 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000521 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000522 OpenMPDirectiveKind getDirective(unsigned Level) const {
523 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000524 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000525 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000526 /// Returns the capture region at the specified level.
527 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
528 unsigned OpenMPCaptureLevel) const {
529 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
530 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
531 return CaptureRegions[OpenMPCaptureLevel];
532 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000533 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000534 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000535 const SharingMapTy *Parent = getSecondOnStackOrNull();
536 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000537 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000538
Kelvin Li1408f912018-09-26 04:28:39 +0000539 /// Add requires decl to internal vector
540 void addRequiresDecl(OMPRequiresDecl *RD) {
541 RequiresDecls.push_back(RD);
542 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543
Alexey Bataev318f431b2019-03-22 15:25:12 +0000544 /// Checks if the defined 'requires' directive has specified type of clause.
545 template <typename ClauseType>
546 bool hasRequiresDeclWithClause() {
547 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
548 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
549 return isa<ClauseType>(C);
550 });
551 });
552 }
553
Kelvin Li1408f912018-09-26 04:28:39 +0000554 /// Checks for a duplicate clause amongst previously declared requires
555 /// directives
556 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
557 bool IsDuplicate = false;
558 for (OMPClause *CNew : ClauseList) {
559 for (const OMPRequiresDecl *D : RequiresDecls) {
560 for (const OMPClause *CPrev : D->clauselists()) {
561 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
562 SemaRef.Diag(CNew->getBeginLoc(),
563 diag::err_omp_requires_clause_redeclaration)
564 << getOpenMPClauseName(CNew->getClauseKind());
565 SemaRef.Diag(CPrev->getBeginLoc(),
566 diag::note_omp_requires_previous_clause)
567 << getOpenMPClauseName(CPrev->getClauseKind());
568 IsDuplicate = true;
569 }
570 }
571 }
572 }
573 return IsDuplicate;
574 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000575
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000576 /// Add location of previously encountered target to internal vector
577 void addTargetDirLocation(SourceLocation LocStart) {
578 TargetLocations.push_back(LocStart);
579 }
580
581 // Return previously encountered target region locations.
582 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
583 return TargetLocations;
584 }
585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000586 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000587 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000588 getTopOfStack().DefaultAttr = DSA_none;
589 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000590 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000591 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000592 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000593 getTopOfStack().DefaultAttr = DSA_shared;
594 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000595 }
cchene06f3e02019-11-15 13:02:06 -0500596 /// Set default data mapping attribute to Modifier:Kind
597 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
598 OpenMPDefaultmapClauseKind Kind,
599 SourceLocation Loc) {
600 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
601 DMI.ImplicitBehavior = M;
602 DMI.SLoc = Loc;
603 }
604 /// Check whether the implicit-behavior has been set in defaultmap
605 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
606 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
607 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000608 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000609
610 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000611 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000612 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000614 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000615 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000616 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000617 }
cchene06f3e02019-11-15 13:02:06 -0500618 OpenMPDefaultmapClauseModifier
619 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
620 return isStackEmpty()
621 ? OMPC_DEFAULTMAP_MODIFIER_unknown
622 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000623 }
cchene06f3e02019-11-15 13:02:06 -0500624 OpenMPDefaultmapClauseModifier
625 getDefaultmapModifierAtLevel(unsigned Level,
626 OpenMPDefaultmapClauseKind Kind) const {
627 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000628 }
cchene06f3e02019-11-15 13:02:06 -0500629 bool isDefaultmapCapturedByRef(unsigned Level,
630 OpenMPDefaultmapClauseKind Kind) const {
631 OpenMPDefaultmapClauseModifier M =
632 getDefaultmapModifierAtLevel(Level, Kind);
633 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
634 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
635 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
636 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
637 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
638 }
639 return true;
640 }
641 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
642 OpenMPDefaultmapClauseKind Kind) {
643 switch (Kind) {
644 case OMPC_DEFAULTMAP_scalar:
645 case OMPC_DEFAULTMAP_pointer:
646 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
647 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
648 (M == OMPC_DEFAULTMAP_MODIFIER_default);
649 case OMPC_DEFAULTMAP_aggregate:
650 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000651 default:
652 break;
cchene06f3e02019-11-15 13:02:06 -0500653 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000654 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500655 }
656 bool mustBeFirstprivateAtLevel(unsigned Level,
657 OpenMPDefaultmapClauseKind Kind) const {
658 OpenMPDefaultmapClauseModifier M =
659 getDefaultmapModifierAtLevel(Level, Kind);
660 return mustBeFirstprivateBase(M, Kind);
661 }
662 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
663 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
664 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000665 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000667 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000668 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000669 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000670 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000671 }
672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000673 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000674 void setOrderedRegion(bool IsOrdered, const Expr *Param,
675 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000676 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000677 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000678 else
Richard Smith375dec52019-05-30 23:21:14 +0000679 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000680 }
681 /// Returns true, if region is ordered (has associated 'ordered' clause),
682 /// false - otherwise.
683 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000684 if (const SharingMapTy *Top = getTopOfStackOrNull())
685 return Top->OrderedRegion.hasValue();
686 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000687 }
688 /// Returns optional parameter for the ordered region.
689 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000690 if (const SharingMapTy *Top = getTopOfStackOrNull())
691 if (Top->OrderedRegion.hasValue())
692 return Top->OrderedRegion.getValue();
693 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000694 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000695 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000696 /// 'ordered' clause), false - otherwise.
697 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000698 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
699 return Parent->OrderedRegion.hasValue();
700 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000701 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000702 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000703 std::pair<const Expr *, OMPOrderedClause *>
704 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000705 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
706 if (Parent->OrderedRegion.hasValue())
707 return Parent->OrderedRegion.getValue();
708 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000709 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000710 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000711 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000712 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000713 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000714 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000715 /// 'nowait' clause), false - otherwise.
716 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000717 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
718 return Parent->NowaitRegion;
719 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000720 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000721 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000722 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000723 if (SharingMapTy *Parent = getSecondOnStackOrNull())
724 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000725 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000726 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000727 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000728 const SharingMapTy *Top = getTopOfStackOrNull();
729 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000730 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000731
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000732 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000733 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000734 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000735 if (Val > 1)
736 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000737 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000738 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000739 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000740 const SharingMapTy *Top = getTopOfStackOrNull();
741 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000742 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000743 /// Returns true if the construct is associated with multiple loops.
744 bool hasMutipleLoops() const {
745 const SharingMapTy *Top = getTopOfStackOrNull();
746 return Top ? Top->HasMutipleLoops : false;
747 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000749 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000750 /// region.
751 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000752 if (SharingMapTy *Parent = getSecondOnStackOrNull())
753 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000754 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000755 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000756 bool hasInnerTeamsRegion() const {
757 return getInnerTeamsRegionLoc().isValid();
758 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000760 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000761 const SharingMapTy *Top = getTopOfStackOrNull();
762 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000763 }
764
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000765 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000766 const SharingMapTy *Top = getTopOfStackOrNull();
767 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000768 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000769 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000770 const SharingMapTy *Top = getTopOfStackOrNull();
771 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000772 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000773
Samuel Antao4c8035b2016-12-12 18:00:20 +0000774 /// Do the check specified in \a Check to all component lists and return true
775 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000776 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000777 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000778 const llvm::function_ref<
779 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000780 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000782 if (isStackEmpty())
783 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000784 auto SI = begin();
785 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000786
787 if (SI == SE)
788 return false;
789
Alexey Bataeve3727102018-04-18 15:57:46 +0000790 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000791 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000792 else
793 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000794
795 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000796 auto MI = SI->MappedExprComponents.find(VD);
797 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000798 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
799 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000800 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000801 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000802 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000803 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000804 }
805
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000806 /// Do the check specified in \a Check to all component lists at a given level
807 /// and return true if any issue is found.
808 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000809 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000810 const llvm::function_ref<
811 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000812 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000813 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000814 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000815 return false;
816
Richard Smith375dec52019-05-30 23:21:14 +0000817 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
818 auto MI = StackElem.MappedExprComponents.find(VD);
819 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000820 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
821 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000822 if (Check(L, MI->second.Kind))
823 return true;
824 return false;
825 }
826
Samuel Antao4c8035b2016-12-12 18:00:20 +0000827 /// Create a new mappable expression component list associated with a given
828 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000829 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000830 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000831 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
832 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000833 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000834 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000835 MEC.Components.resize(MEC.Components.size() + 1);
836 MEC.Components.back().append(Components.begin(), Components.end());
837 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000838 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000839
840 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000841 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000842 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000843 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000844 void addDoacrossDependClause(OMPDependClause *C,
845 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000846 SharingMapTy *Parent = getSecondOnStackOrNull();
847 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
848 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000849 }
850 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
851 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000852 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000853 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000854 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000855 return llvm::make_range(Ref.begin(), Ref.end());
856 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000857 return llvm::make_range(StackElem.DoacrossDepends.end(),
858 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000859 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000860
861 // Store types of classes which have been explicitly mapped
862 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000863 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000864 StackElem.MappedClassesQualTypes.insert(QT);
865 }
866
867 // Return set of mapped classes types
868 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000869 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000870 return StackElem.MappedClassesQualTypes.count(QT) != 0;
871 }
872
Alexey Bataeva495c642019-03-11 19:51:42 +0000873 /// Adds global declare target to the parent target region.
874 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
875 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
876 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
877 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000878 for (auto &Elem : *this) {
879 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
880 Elem.DeclareTargetLinkVarDecls.push_back(E);
881 return;
882 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000883 }
884 }
885
886 /// Returns the list of globals with declare target link if current directive
887 /// is target.
888 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
889 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
890 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000891 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000892 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000893};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000894
895bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
896 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
897}
898
899bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000900 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
901 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000902}
Alexey Bataeve3727102018-04-18 15:57:46 +0000903
Alexey Bataeved09d242014-05-28 05:53:51 +0000904} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905
Alexey Bataeve3727102018-04-18 15:57:46 +0000906static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000907 if (const auto *FE = dyn_cast<FullExpr>(E))
908 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000909
Alexey Bataeve3727102018-04-18 15:57:46 +0000910 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100911 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000912
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000914 E = Binder->getSubExpr();
915
Alexey Bataeve3727102018-04-18 15:57:46 +0000916 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000917 E = ICE->getSubExprAsWritten();
918 return E->IgnoreParens();
919}
920
Alexey Bataeve3727102018-04-18 15:57:46 +0000921static Expr *getExprAsWritten(Expr *E) {
922 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
923}
924
925static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
926 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
927 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000928 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000929 const auto *VD = dyn_cast<VarDecl>(D);
930 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000931 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000932 VD = VD->getCanonicalDecl();
933 D = VD;
934 } else {
935 assert(FD);
936 FD = FD->getCanonicalDecl();
937 D = FD;
938 }
939 return D;
940}
941
Alexey Bataeve3727102018-04-18 15:57:46 +0000942static ValueDecl *getCanonicalDecl(ValueDecl *D) {
943 return const_cast<ValueDecl *>(
944 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
945}
946
Richard Smith375dec52019-05-30 23:21:14 +0000947DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000948 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000949 D = getCanonicalDecl(D);
950 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000951 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000952 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000953 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000954 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
955 // in a region but not in construct]
956 // File-scope or namespace-scope variables referenced in called routines
957 // in the region are shared unless they appear in a threadprivate
958 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000959 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000960 DVar.CKind = OMPC_shared;
961
962 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
963 // in a region but not in construct]
964 // Variables with static storage duration that are declared in called
965 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000966 if (VD && VD->hasGlobalStorage())
967 DVar.CKind = OMPC_shared;
968
969 // Non-static data members are shared by default.
970 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000971 DVar.CKind = OMPC_shared;
972
Alexey Bataev758e55e2013-09-06 18:03:48 +0000973 return DVar;
974 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000975
Alexey Bataevec3da872014-01-31 05:15:34 +0000976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
977 // in a Construct, C/C++, predetermined, p.1]
978 // Variables with automatic storage duration that are declared in a scope
979 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000980 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
981 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000982 DVar.CKind = OMPC_private;
983 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000984 }
985
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000986 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987 // Explicitly specified attributes and local variables with predetermined
988 // attributes.
989 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000990 const DSAInfo &Data = Iter->SharingMap.lookup(D);
991 DVar.RefExpr = Data.RefExpr.getPointer();
992 DVar.PrivateCopy = Data.PrivateCopy;
993 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000994 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995 return DVar;
996 }
997
998 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
999 // in a Construct, C/C++, implicitly determined, p.1]
1000 // In a parallel or task construct, the data-sharing attributes of these
1001 // variables are determined by the default clause, if present.
1002 switch (Iter->DefaultAttr) {
1003 case DSA_shared:
1004 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001005 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001006 return DVar;
1007 case DSA_none:
1008 return DVar;
1009 case DSA_unspecified:
1010 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1011 // in a Construct, implicitly determined, p.2]
1012 // In a parallel construct, if no default clause is present, these
1013 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001014 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001015 if ((isOpenMPParallelDirective(DVar.DKind) &&
1016 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001017 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001018 DVar.CKind = OMPC_shared;
1019 return DVar;
1020 }
1021
1022 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1023 // in a Construct, implicitly determined, p.4]
1024 // In a task construct, if no default clause is present, a variable that in
1025 // the enclosing context is determined to be shared by all implicit tasks
1026 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001027 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001029 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001030 do {
1031 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001032 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001033 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // In a task construct, if no default clause is present, a variable
1035 // whose data-sharing attribute is not determined by the rules above is
1036 // firstprivate.
1037 DVarTemp = getDSA(I, D);
1038 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001039 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001040 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001041 return DVar;
1042 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001043 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001044 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001045 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001046 return DVar;
1047 }
1048 }
1049 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1050 // in a Construct, implicitly determined, p.3]
1051 // For constructs other than task, if no default clause is present, these
1052 // variables inherit their data-sharing attributes from the enclosing
1053 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001054 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001055}
1056
Alexey Bataeve3727102018-04-18 15:57:46 +00001057const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1058 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001059 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001060 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001061 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001062 auto It = StackElem.AlignedMap.find(D);
1063 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001064 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001065 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001066 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001067 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001068 assert(It->second && "Unexpected nullptr expr in the aligned map");
1069 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001070}
1071
Alexey Bataeve3727102018-04-18 15:57:46 +00001072void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001073 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001074 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001075 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001076 StackElem.LCVMap.try_emplace(
1077 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001078}
1079
Alexey Bataeve3727102018-04-18 15:57:46 +00001080const DSAStackTy::LCDeclInfo
1081DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001082 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001083 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001084 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001085 auto It = StackElem.LCVMap.find(D);
1086 if (It != StackElem.LCVMap.end())
1087 return It->second;
1088 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001089}
1090
Alexey Bataeve3727102018-04-18 15:57:46 +00001091const DSAStackTy::LCDeclInfo
1092DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001093 const SharingMapTy *Parent = getSecondOnStackOrNull();
1094 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001095 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001096 auto It = Parent->LCVMap.find(D);
1097 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001098 return It->second;
1099 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001100}
1101
Alexey Bataeve3727102018-04-18 15:57:46 +00001102const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001103 const SharingMapTy *Parent = getSecondOnStackOrNull();
1104 assert(Parent && "Data-sharing attributes stack is empty");
1105 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001106 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001107 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001108 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001109 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001110 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001111}
1112
Alexey Bataeve3727102018-04-18 15:57:46 +00001113void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001114 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001115 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001116 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001117 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001118 Data.Attributes = A;
1119 Data.RefExpr.setPointer(E);
1120 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001121 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001122 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001123 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1124 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1125 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1126 (isLoopControlVariable(D).first && A == OMPC_private));
1127 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1128 Data.RefExpr.setInt(/*IntVal=*/true);
1129 return;
1130 }
1131 const bool IsLastprivate =
1132 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1133 Data.Attributes = A;
1134 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1135 Data.PrivateCopy = PrivateCopy;
1136 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001137 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001138 Data.Attributes = A;
1139 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1140 Data.PrivateCopy = nullptr;
1141 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001142 }
1143}
1144
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001145/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001146static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001147 StringRef Name, const AttrVec *Attrs = nullptr,
1148 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001149 DeclContext *DC = SemaRef.CurContext;
1150 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1151 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001152 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001153 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1154 if (Attrs) {
1155 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1156 I != E; ++I)
1157 Decl->addAttr(*I);
1158 }
1159 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001160 if (OrigRef) {
1161 Decl->addAttr(
1162 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1163 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001164 return Decl;
1165}
1166
1167static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1168 SourceLocation Loc,
1169 bool RefersToCapture = false) {
1170 D->setReferenced();
1171 D->markUsed(S.Context);
1172 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1173 SourceLocation(), D, RefersToCapture, Loc, Ty,
1174 VK_LValue);
1175}
1176
Alexey Bataeve3727102018-04-18 15:57:46 +00001177void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001178 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001179 D = getCanonicalDecl(D);
1180 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001181 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001182 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001183 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001184 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001185 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001186 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001187 "Additional reduction info may be specified only once for reduction "
1188 "items.");
1189 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001190 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001191 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001192 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001193 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1194 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001195 TaskgroupReductionRef =
1196 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001197 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001198}
1199
Alexey Bataeve3727102018-04-18 15:57:46 +00001200void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001201 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001202 D = getCanonicalDecl(D);
1203 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001204 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001205 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001206 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001207 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001208 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001209 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001210 "Additional reduction info may be specified only once for reduction "
1211 "items.");
1212 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001213 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001214 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001215 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001216 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1217 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001218 TaskgroupReductionRef =
1219 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001220 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001221}
1222
Alexey Bataeve3727102018-04-18 15:57:46 +00001223const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1224 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1225 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001226 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001227 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001228 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001229 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001230 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001231 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001232 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001233 if (!ReductionData.ReductionOp ||
1234 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001235 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001236 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001237 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001238 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1239 "expression for the descriptor is not "
1240 "set.");
1241 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001242 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1243 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001244 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001245 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001246}
1247
Alexey Bataeve3727102018-04-18 15:57:46 +00001248const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1249 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1250 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001251 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001252 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001253 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001254 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001255 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001256 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001257 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001258 if (!ReductionData.ReductionOp ||
1259 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001260 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001261 SR = ReductionData.ReductionRange;
1262 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001263 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1264 "expression for the descriptor is not "
1265 "set.");
1266 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001267 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1268 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001269 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001270 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001271}
1272
Richard Smith375dec52019-05-30 23:21:14 +00001273bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001274 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001275 for (const_iterator E = end(); I != E; ++I) {
1276 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1277 isOpenMPTargetExecutionDirective(I->Directive)) {
1278 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1279 Scope *CurScope = getCurScope();
1280 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1281 CurScope = CurScope->getParent();
1282 return CurScope != TopScope;
1283 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001284 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001285 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001286}
1287
Joel E. Dennyd2649292019-01-04 22:11:56 +00001288static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1289 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001290 bool *IsClassType = nullptr) {
1291 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001292 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001293 bool IsConstant = Type.isConstant(Context);
1294 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001295 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1296 ? Type->getAsCXXRecordDecl()
1297 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001298 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1299 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1300 RD = CTD->getTemplatedDecl();
1301 if (IsClassType)
1302 *IsClassType = RD;
1303 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1304 RD->hasDefinition() && RD->hasMutableFields());
1305}
1306
Joel E. Dennyd2649292019-01-04 22:11:56 +00001307static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1308 QualType Type, OpenMPClauseKind CKind,
1309 SourceLocation ELoc,
1310 bool AcceptIfMutable = true,
1311 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001312 ASTContext &Context = SemaRef.getASTContext();
1313 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001314 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1315 unsigned Diag = ListItemNotVar
1316 ? diag::err_omp_const_list_item
1317 : IsClassType ? diag::err_omp_const_not_mutable_variable
1318 : diag::err_omp_const_variable;
1319 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1320 if (!ListItemNotVar && D) {
1321 const VarDecl *VD = dyn_cast<VarDecl>(D);
1322 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1323 VarDecl::DeclarationOnly;
1324 SemaRef.Diag(D->getLocation(),
1325 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1326 << D;
1327 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001328 return true;
1329 }
1330 return false;
1331}
1332
Alexey Bataeve3727102018-04-18 15:57:46 +00001333const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1334 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001335 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001336 DSAVarData DVar;
1337
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001338 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001339 auto TI = Threadprivates.find(D);
1340 if (TI != Threadprivates.end()) {
1341 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001342 DVar.CKind = OMPC_threadprivate;
1343 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001344 }
1345 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001346 DVar.RefExpr = buildDeclRefExpr(
1347 SemaRef, VD, D->getType().getNonReferenceType(),
1348 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1349 DVar.CKind = OMPC_threadprivate;
1350 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001351 return DVar;
1352 }
1353 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1354 // in a Construct, C/C++, predetermined, p.1]
1355 // Variables appearing in threadprivate directives are threadprivate.
1356 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1357 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1358 SemaRef.getLangOpts().OpenMPUseTLS &&
1359 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1360 (VD && VD->getStorageClass() == SC_Register &&
1361 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1362 DVar.RefExpr = buildDeclRefExpr(
1363 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1364 DVar.CKind = OMPC_threadprivate;
1365 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1366 return DVar;
1367 }
1368 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1369 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1370 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001371 const_iterator IterTarget =
1372 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1373 return isOpenMPTargetExecutionDirective(Data.Directive);
1374 });
1375 if (IterTarget != end()) {
1376 const_iterator ParentIterTarget = IterTarget + 1;
1377 for (const_iterator Iter = begin();
1378 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001379 if (isOpenMPLocal(VD, Iter)) {
1380 DVar.RefExpr =
1381 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1382 D->getLocation());
1383 DVar.CKind = OMPC_threadprivate;
1384 return DVar;
1385 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001386 }
Richard Smith375dec52019-05-30 23:21:14 +00001387 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001388 auto DSAIter = IterTarget->SharingMap.find(D);
1389 if (DSAIter != IterTarget->SharingMap.end() &&
1390 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1391 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1392 DVar.CKind = OMPC_threadprivate;
1393 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001394 }
Richard Smith375dec52019-05-30 23:21:14 +00001395 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001396 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001397 D, std::distance(ParentIterTarget, End),
1398 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001399 DVar.RefExpr =
1400 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1401 IterTarget->ConstructLoc);
1402 DVar.CKind = OMPC_threadprivate;
1403 return DVar;
1404 }
1405 }
1406 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001407 }
1408
Alexey Bataev4b465392017-04-26 15:06:24 +00001409 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001410 // Not in OpenMP execution region and top scope was already checked.
1411 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001412
Alexey Bataev758e55e2013-09-06 18:03:48 +00001413 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001414 // in a Construct, C/C++, predetermined, p.4]
1415 // Static data members are shared.
1416 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1417 // in a Construct, C/C++, predetermined, p.7]
1418 // Variables with static storage duration that are declared in a scope
1419 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001420 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001421 // Check for explicitly specified attributes.
1422 const_iterator I = begin();
1423 const_iterator EndI = end();
1424 if (FromParent && I != EndI)
1425 ++I;
1426 auto It = I->SharingMap.find(D);
1427 if (It != I->SharingMap.end()) {
1428 const DSAInfo &Data = It->getSecond();
1429 DVar.RefExpr = Data.RefExpr.getPointer();
1430 DVar.PrivateCopy = Data.PrivateCopy;
1431 DVar.CKind = Data.Attributes;
1432 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1433 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001434 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001435 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001436
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001437 DVar.CKind = OMPC_shared;
1438 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001439 }
1440
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001441 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001442 // The predetermined shared attribute for const-qualified types having no
1443 // mutable members was removed after OpenMP 3.1.
1444 if (SemaRef.LangOpts.OpenMP <= 31) {
1445 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1446 // in a Construct, C/C++, predetermined, p.6]
1447 // Variables with const qualified type having no mutable member are
1448 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001449 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001450 // Variables with const-qualified type having no mutable member may be
1451 // listed in a firstprivate clause, even if they are static data members.
1452 DSAVarData DVarTemp = hasInnermostDSA(
1453 D,
1454 [](OpenMPClauseKind C) {
1455 return C == OMPC_firstprivate || C == OMPC_shared;
1456 },
1457 MatchesAlways, FromParent);
1458 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1459 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001460
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001461 DVar.CKind = OMPC_shared;
1462 return DVar;
1463 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001464 }
1465
Alexey Bataev758e55e2013-09-06 18:03:48 +00001466 // Explicitly specified attributes and local variables with predetermined
1467 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001468 const_iterator I = begin();
1469 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001470 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001471 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001472 auto It = I->SharingMap.find(D);
1473 if (It != I->SharingMap.end()) {
1474 const DSAInfo &Data = It->getSecond();
1475 DVar.RefExpr = Data.RefExpr.getPointer();
1476 DVar.PrivateCopy = Data.PrivateCopy;
1477 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001478 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001479 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001480 }
1481
1482 return DVar;
1483}
1484
Alexey Bataeve3727102018-04-18 15:57:46 +00001485const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1486 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001487 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001488 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001489 return getDSA(I, D);
1490 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001491 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001492 const_iterator StartI = begin();
1493 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001494 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001495 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001496 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001497}
1498
Alexey Bataeve3727102018-04-18 15:57:46 +00001499const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001500DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001501 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1502 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001503 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001504 if (isStackEmpty())
1505 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001506 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001507 const_iterator I = begin();
1508 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001509 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001510 ++I;
1511 for (; I != EndI; ++I) {
1512 if (!DPred(I->Directive) &&
1513 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001514 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001515 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001516 DSAVarData DVar = getDSA(NewI, D);
1517 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001518 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001519 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001520 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001521}
1522
Alexey Bataeve3727102018-04-18 15:57:46 +00001523const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001524 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1525 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001526 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001527 if (isStackEmpty())
1528 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001529 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001530 const_iterator StartI = begin();
1531 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001532 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001533 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001534 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001535 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001536 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001537 DSAVarData DVar = getDSA(NewI, D);
1538 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001539}
1540
Alexey Bataevaac108a2015-06-23 04:51:00 +00001541bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001542 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1543 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001544 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001545 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001546 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001547 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1548 auto I = StackElem.SharingMap.find(D);
1549 if (I != StackElem.SharingMap.end() &&
1550 I->getSecond().RefExpr.getPointer() &&
1551 CPred(I->getSecond().Attributes) &&
1552 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001553 return true;
1554 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001555 auto LI = StackElem.LCVMap.find(D);
1556 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001557 return CPred(OMPC_private);
1558 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001559}
1560
Samuel Antao4be30e92015-10-02 17:14:03 +00001561bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001562 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1563 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001564 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001565 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001566 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1567 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001568}
1569
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001570bool DSAStackTy::hasDirective(
1571 const llvm::function_ref<bool(OpenMPDirectiveKind,
1572 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001573 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001574 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001575 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001576 size_t Skip = FromParent ? 2 : 1;
1577 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1578 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001579 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1580 return true;
1581 }
1582 return false;
1583}
1584
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585void Sema::InitDataSharingAttributesStack() {
1586 VarDataSharingAttributesStack = new DSAStackTy(*this);
1587}
1588
1589#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1590
Alexey Bataev4b465392017-04-26 15:06:24 +00001591void Sema::pushOpenMPFunctionRegion() {
1592 DSAStack->pushFunction();
1593}
1594
1595void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1596 DSAStack->popFunction(OldFSI);
1597}
1598
Alexey Bataevc416e642019-02-08 18:02:25 +00001599static bool isOpenMPDeviceDelayedContext(Sema &S) {
1600 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1601 "Expected OpenMP device compilation.");
1602 return !S.isInOpenMPTargetExecutionDirective() &&
1603 !S.isInOpenMPDeclareTargetContext();
1604}
1605
Alexey Bataev729e2422019-08-23 16:11:14 +00001606namespace {
1607/// Status of the function emission on the host/device.
1608enum class FunctionEmissionStatus {
1609 Emitted,
1610 Discarded,
1611 Unknown,
1612};
1613} // anonymous namespace
1614
Alexey Bataevc416e642019-02-08 18:02:25 +00001615Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1616 unsigned DiagID) {
1617 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1618 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001619 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001620 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1621 switch (FES) {
1622 case FunctionEmissionStatus::Emitted:
1623 Kind = DeviceDiagBuilder::K_Immediate;
1624 break;
1625 case FunctionEmissionStatus::Unknown:
1626 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1627 : DeviceDiagBuilder::K_Immediate;
1628 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001629 case FunctionEmissionStatus::TemplateDiscarded:
1630 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001631 Kind = DeviceDiagBuilder::K_Nop;
1632 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001633 case FunctionEmissionStatus::CUDADiscarded:
1634 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1635 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001636 }
1637
1638 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1639}
1640
Alexey Bataev729e2422019-08-23 16:11:14 +00001641Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1642 unsigned DiagID) {
1643 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1644 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001645 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001646 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1647 switch (FES) {
1648 case FunctionEmissionStatus::Emitted:
1649 Kind = DeviceDiagBuilder::K_Immediate;
1650 break;
1651 case FunctionEmissionStatus::Unknown:
1652 Kind = DeviceDiagBuilder::K_Deferred;
1653 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001654 case FunctionEmissionStatus::TemplateDiscarded:
1655 case FunctionEmissionStatus::OMPDiscarded:
1656 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001657 Kind = DeviceDiagBuilder::K_Nop;
1658 break;
1659 }
1660
1661 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001662}
1663
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001664void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1665 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001666 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1667 "Expected OpenMP device compilation.");
1668 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001669 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001670 FunctionDecl *Caller = getCurFunctionDecl();
1671
Alexey Bataev729e2422019-08-23 16:11:14 +00001672 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001673 if (Caller) {
1674 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1675 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1676 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1677 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1678 "CUDADiscarded unexpected in OpenMP device function check");
1679 if ((CallerS == FunctionEmissionStatus::Emitted ||
1680 (!isOpenMPDeviceDelayedContext(*this) &&
1681 CallerS == FunctionEmissionStatus::Unknown)) &&
1682 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1683 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1684 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1685 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1686 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1687 diag::note_omp_marked_device_type_here)
1688 << HostDevTy;
1689 return;
1690 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001691 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001692 // If the caller is known-emitted, mark the callee as known-emitted.
1693 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001694 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1695 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001696 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001697 markKnownEmitted(*this, Caller, Callee, Loc,
1698 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001699 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001700 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001701 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001702 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001703 else if (Caller)
1704 DeviceCallGraph[Caller].insert({Callee, Loc});
1705}
1706
Alexey Bataev729e2422019-08-23 16:11:14 +00001707void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1708 bool CheckCaller) {
1709 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1710 "Expected OpenMP host compilation.");
1711 assert(Callee && "Callee may not be null.");
1712 Callee = Callee->getMostRecentDecl();
1713 FunctionDecl *Caller = getCurFunctionDecl();
1714
1715 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001716 if (Caller) {
1717 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1718 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1719 assert(
1720 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1721 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1722 "CUDADiscarded unexpected in OpenMP host function check");
1723 if (CallerS == FunctionEmissionStatus::Emitted &&
1724 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1725 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1726 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1727 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1728 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1729 diag::note_omp_marked_device_type_here)
1730 << NoHostDevTy;
1731 return;
1732 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001733 }
1734 // If the caller is known-emitted, mark the callee as known-emitted.
1735 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001736 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1737 if ((!CheckCaller && !Caller) ||
1738 (Caller &&
1739 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1740 markKnownEmitted(
1741 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1742 return CheckCaller &&
1743 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1744 });
1745 else if (Caller)
1746 DeviceCallGraph[Caller].insert({Callee, Loc});
1747 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001748}
1749
Alexey Bataev123ad192019-02-27 20:29:45 +00001750void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1751 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1752 "OpenMP device compilation mode is expected.");
1753 QualType Ty = E->getType();
1754 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001755 ((Ty->isFloat128Type() ||
1756 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1757 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001758 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1759 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001760 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1761 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1762 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001763}
1764
cchene06f3e02019-11-15 13:02:06 -05001765static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001766getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1767 if (LO.OpenMP <= 45) {
1768 if (VD->getType().getNonReferenceType()->isScalarType())
1769 return OMPC_DEFAULTMAP_scalar;
1770 return OMPC_DEFAULTMAP_aggregate;
1771 }
cchene06f3e02019-11-15 13:02:06 -05001772 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1773 return OMPC_DEFAULTMAP_pointer;
1774 if (VD->getType().getNonReferenceType()->isScalarType())
1775 return OMPC_DEFAULTMAP_scalar;
1776 return OMPC_DEFAULTMAP_aggregate;
1777}
1778
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001779bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1780 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001781 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1782
Alexey Bataeve3727102018-04-18 15:57:46 +00001783 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001784 bool IsByRef = true;
1785
1786 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001787 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001788 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001789
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001790 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001791 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001792 // This table summarizes how a given variable should be passed to the device
1793 // given its type and the clauses where it appears. This table is based on
1794 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1795 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1796 //
1797 // =========================================================================
1798 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1799 // | |(tofrom:scalar)| | pvt | | | |
1800 // =========================================================================
1801 // | scl | | | | - | | bycopy|
1802 // | scl | | - | x | - | - | bycopy|
1803 // | scl | | x | - | - | - | null |
1804 // | scl | x | | | - | | byref |
1805 // | scl | x | - | x | - | - | bycopy|
1806 // | scl | x | x | - | - | - | null |
1807 // | scl | | - | - | - | x | byref |
1808 // | scl | x | - | - | - | x | byref |
1809 //
1810 // | agg | n.a. | | | - | | byref |
1811 // | agg | n.a. | - | x | - | - | byref |
1812 // | agg | n.a. | x | - | - | - | null |
1813 // | agg | n.a. | - | - | - | x | byref |
1814 // | agg | n.a. | - | - | - | x[] | byref |
1815 //
1816 // | ptr | n.a. | | | - | | bycopy|
1817 // | ptr | n.a. | - | x | - | - | bycopy|
1818 // | ptr | n.a. | x | - | - | - | null |
1819 // | ptr | n.a. | - | - | - | x | byref |
1820 // | ptr | n.a. | - | - | - | x[] | bycopy|
1821 // | ptr | n.a. | - | - | x | | bycopy|
1822 // | ptr | n.a. | - | - | x | x | bycopy|
1823 // | ptr | n.a. | - | - | x | x[] | bycopy|
1824 // =========================================================================
1825 // Legend:
1826 // scl - scalar
1827 // ptr - pointer
1828 // agg - aggregate
1829 // x - applies
1830 // - - invalid in this combination
1831 // [] - mapped with an array section
1832 // byref - should be mapped by reference
1833 // byval - should be mapped by value
1834 // null - initialize a local variable to null on the device
1835 //
1836 // Observations:
1837 // - All scalar declarations that show up in a map clause have to be passed
1838 // by reference, because they may have been mapped in the enclosing data
1839 // environment.
1840 // - If the scalar value does not fit the size of uintptr, it has to be
1841 // passed by reference, regardless the result in the table above.
1842 // - For pointers mapped by value that have either an implicit map or an
1843 // array section, the runtime library may pass the NULL value to the
1844 // device instead of the value passed to it by the compiler.
1845
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001846 if (Ty->isReferenceType())
1847 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001848
1849 // Locate map clauses and see if the variable being captured is referred to
1850 // in any of those clauses. Here we only care about variables, not fields,
1851 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001852 bool IsVariableAssociatedWithSection = false;
1853
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001854 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001855 D, Level,
1856 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1857 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001858 MapExprComponents,
1859 OpenMPClauseKind WhereFoundClauseKind) {
1860 // Only the map clause information influences how a variable is
1861 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001862 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001863 if (WhereFoundClauseKind != OMPC_map)
1864 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001865
1866 auto EI = MapExprComponents.rbegin();
1867 auto EE = MapExprComponents.rend();
1868
1869 assert(EI != EE && "Invalid map expression!");
1870
1871 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1872 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1873
1874 ++EI;
1875 if (EI == EE)
1876 return false;
1877
1878 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1879 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1880 isa<MemberExpr>(EI->getAssociatedExpression())) {
1881 IsVariableAssociatedWithSection = true;
1882 // There is nothing more we need to know about this variable.
1883 return true;
1884 }
1885
1886 // Keep looking for more map info.
1887 return false;
1888 });
1889
1890 if (IsVariableUsedInMapClause) {
1891 // If variable is identified in a map clause it is always captured by
1892 // reference except if it is a pointer that is dereferenced somehow.
1893 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1894 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001895 // By default, all the data that has a scalar type is mapped by copy
1896 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001897 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001898 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001899 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1900 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001901 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001902 DSAStack->isDefaultmapCapturedByRef(
1903 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001904 DSAStack->hasExplicitDSA(
1905 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001906 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001907 }
1908
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001909 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001910 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001911 ((IsVariableUsedInMapClause &&
1912 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1913 OMPD_target) ||
1914 !DSAStack->hasExplicitDSA(
1915 D,
1916 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1917 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001918 // If the variable is artificial and must be captured by value - try to
1919 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001920 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1921 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001922 }
1923
Samuel Antao86ace552016-04-27 22:40:57 +00001924 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001925 // and alignment, because the runtime library only deals with uintptr types.
1926 // If it does not fit the uintptr size, we need to pass the data by reference
1927 // instead.
1928 if (!IsByRef &&
1929 (Ctx.getTypeSizeInChars(Ty) >
1930 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001931 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001932 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001933 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001934
1935 return IsByRef;
1936}
1937
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001938unsigned Sema::getOpenMPNestingLevel() const {
1939 assert(getLangOpts().OpenMP);
1940 return DSAStack->getNestingLevel();
1941}
1942
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001943bool Sema::isInOpenMPTargetExecutionDirective() const {
1944 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1945 !DSAStack->isClauseParsingMode()) ||
1946 DSAStack->hasDirective(
1947 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1948 SourceLocation) -> bool {
1949 return isOpenMPTargetExecutionDirective(K);
1950 },
1951 false);
1952}
1953
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001954VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1955 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001956 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001957 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001958
Alexey Bataev7c860692019-10-25 16:35:32 -04001959 auto *VD = dyn_cast<VarDecl>(D);
1960 // Do not capture constexpr variables.
1961 if (VD && VD->isConstexpr())
1962 return nullptr;
1963
Richard Smith0621a8f2019-05-31 00:45:10 +00001964 // If we want to determine whether the variable should be captured from the
1965 // perspective of the current capturing scope, and we've already left all the
1966 // capturing scopes of the top directive on the stack, check from the
1967 // perspective of its parent directive (if any) instead.
1968 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1969 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1970
Samuel Antao4be30e92015-10-02 17:14:03 +00001971 // If we are attempting to capture a global variable in a directive with
1972 // 'target' we return true so that this global is also mapped to the device.
1973 //
Richard Smith0621a8f2019-05-31 00:45:10 +00001974 if (VD && !VD->hasLocalStorage() &&
1975 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1976 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001977 // Try to mark variable as declare target if it is used in capturing
1978 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001979 if (LangOpts.OpenMP <= 45 &&
1980 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001981 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001982 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001983 } else if (isInOpenMPTargetExecutionDirective()) {
1984 // If the declaration is enclosed in a 'declare target' directive,
1985 // then it should not be captured.
1986 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001987 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001988 return nullptr;
1989 return VD;
1990 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001991 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001992
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001993 if (CheckScopeInfo) {
1994 bool OpenMPFound = false;
1995 for (unsigned I = StopAt + 1; I > 0; --I) {
1996 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1997 if(!isa<CapturingScopeInfo>(FSI))
1998 return nullptr;
1999 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2000 if (RSI->CapRegionKind == CR_OpenMP) {
2001 OpenMPFound = true;
2002 break;
2003 }
2004 }
2005 if (!OpenMPFound)
2006 return nullptr;
2007 }
2008
Alexey Bataev48977c32015-08-04 08:10:48 +00002009 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2010 (!DSAStack->isClauseParsingMode() ||
2011 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002012 auto &&Info = DSAStack->isLoopControlVariable(D);
2013 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002014 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002015 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002016 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002017 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002018 DSAStackTy::DSAVarData DVarPrivate =
2019 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002022 // Threadprivate variables must not be captured.
2023 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2024 return nullptr;
2025 // The variable is not private or it is the variable in the directive with
2026 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002027 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2028 [](OpenMPDirectiveKind) { return true; },
2029 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002030 if (DVarPrivate.CKind != OMPC_unknown ||
2031 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002032 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002033 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002034 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002035}
2036
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002037void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2038 unsigned Level) const {
2039 SmallVector<OpenMPDirectiveKind, 4> Regions;
2040 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2041 FunctionScopesIndex -= Regions.size();
2042}
2043
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002044void Sema::startOpenMPLoop() {
2045 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2046 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2047 DSAStack->loopInit();
2048}
2049
Alexey Bataevbef93a92019-10-07 18:54:57 +00002050void Sema::startOpenMPCXXRangeFor() {
2051 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2052 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2053 DSAStack->resetPossibleLoopCounter();
2054 DSAStack->loopStart();
2055 }
2056}
2057
Alexey Bataeve3727102018-04-18 15:57:46 +00002058bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002059 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002060 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2061 if (DSAStack->getAssociatedLoops() > 0 &&
2062 !DSAStack->isLoopStarted()) {
2063 DSAStack->resetPossibleLoopCounter(D);
2064 DSAStack->loopStart();
2065 return true;
2066 }
2067 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2068 DSAStack->isLoopControlVariable(D).first) &&
2069 !DSAStack->hasExplicitDSA(
2070 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2071 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2072 return true;
2073 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002074 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2075 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2076 DSAStack->isForceVarCapturing() &&
2077 !DSAStack->hasExplicitDSA(
2078 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2079 return true;
2080 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002081 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002082 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002083 (DSAStack->isClauseParsingMode() &&
2084 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002085 // Consider taskgroup reduction descriptor variable a private to avoid
2086 // possible capture in the region.
2087 (DSAStack->hasExplicitDirective(
2088 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2089 Level) &&
2090 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002091}
2092
Alexey Bataeve3727102018-04-18 15:57:46 +00002093void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2094 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002095 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2096 D = getCanonicalDecl(D);
2097 OpenMPClauseKind OMPC = OMPC_unknown;
2098 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2099 const unsigned NewLevel = I - 1;
2100 if (DSAStack->hasExplicitDSA(D,
2101 [&OMPC](const OpenMPClauseKind K) {
2102 if (isOpenMPPrivate(K)) {
2103 OMPC = K;
2104 return true;
2105 }
2106 return false;
2107 },
2108 NewLevel))
2109 break;
2110 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2111 D, NewLevel,
2112 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2113 OpenMPClauseKind) { return true; })) {
2114 OMPC = OMPC_map;
2115 break;
2116 }
2117 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2118 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002119 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002120 if (DSAStack->mustBeFirstprivateAtLevel(
2121 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002122 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002123 break;
2124 }
2125 }
2126 if (OMPC != OMPC_unknown)
2127 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2128}
2129
Alexey Bataeve3727102018-04-18 15:57:46 +00002130bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2131 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002132 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2133 // Return true if the current level is no longer enclosed in a target region.
2134
Alexey Bataeve3727102018-04-18 15:57:46 +00002135 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002136 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002137 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2138 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002139}
2140
Alexey Bataeved09d242014-05-28 05:53:51 +00002141void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002142
Alexey Bataev729e2422019-08-23 16:11:14 +00002143void Sema::finalizeOpenMPDelayedAnalysis() {
2144 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2145 // Diagnose implicit declare target functions and their callees.
2146 for (const auto &CallerCallees : DeviceCallGraph) {
2147 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2148 OMPDeclareTargetDeclAttr::getDeviceType(
2149 CallerCallees.getFirst()->getMostRecentDecl());
2150 // Ignore host functions during device analyzis.
2151 if (LangOpts.OpenMPIsDevice && DevTy &&
2152 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2153 continue;
2154 // Ignore nohost functions during host analyzis.
2155 if (!LangOpts.OpenMPIsDevice && DevTy &&
2156 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2157 continue;
2158 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2159 &Callee : CallerCallees.getSecond()) {
2160 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2161 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2162 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2163 if (LangOpts.OpenMPIsDevice && DevTy &&
2164 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2165 // Diagnose host function called during device codegen.
2166 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2167 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2168 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2169 << HostDevTy << 0;
2170 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2171 diag::note_omp_marked_device_type_here)
2172 << HostDevTy;
2173 continue;
2174 }
2175 if (!LangOpts.OpenMPIsDevice && DevTy &&
2176 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2177 // Diagnose nohost function called during host codegen.
2178 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2179 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2180 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2181 << NoHostDevTy << 1;
2182 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2183 diag::note_omp_marked_device_type_here)
2184 << NoHostDevTy;
2185 continue;
2186 }
2187 }
2188 }
2189}
2190
Alexey Bataev758e55e2013-09-06 18:03:48 +00002191void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2192 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002193 Scope *CurScope, SourceLocation Loc) {
2194 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002195 PushExpressionEvaluationContext(
2196 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002197}
2198
Alexey Bataevaac108a2015-06-23 04:51:00 +00002199void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2200 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002201}
2202
Alexey Bataevaac108a2015-06-23 04:51:00 +00002203void Sema::EndOpenMPClause() {
2204 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002205}
2206
Alexey Bataeve106f252019-04-01 14:25:31 +00002207static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2208 ArrayRef<OMPClause *> Clauses);
2209
Alexey Bataev758e55e2013-09-06 18:03:48 +00002210void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002211 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2212 // A variable of class type (or array thereof) that appears in a lastprivate
2213 // clause requires an accessible, unambiguous default constructor for the
2214 // class type, unless the list item is also specified in a firstprivate
2215 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002216 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2217 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002218 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2219 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002220 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002221 if (DE->isValueDependent() || DE->isTypeDependent()) {
2222 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002223 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002224 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002225 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002226 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002227 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002228 const DSAStackTy::DSAVarData DVar =
2229 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002230 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002231 // Generate helper private variable and initialize it with the
2232 // default value. The address of the original variable is replaced
2233 // by the address of the new private variable in CodeGen. This new
2234 // variable is not added to IdResolver, so the code in the OpenMP
2235 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002236 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002237 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002238 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002239 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002240 if (VDPrivate->isInvalidDecl()) {
2241 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002242 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002243 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002244 PrivateCopies.push_back(buildDeclRefExpr(
2245 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002246 } else {
2247 // The variable is also a firstprivate, so initialization sequence
2248 // for private copy is generated already.
2249 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002250 }
2251 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002252 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002253 }
2254 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002255 // Check allocate clauses.
2256 if (!CurContext->isDependentContext())
2257 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002258 }
2259
Alexey Bataev758e55e2013-09-06 18:03:48 +00002260 DSAStack->pop();
2261 DiscardCleanupsInEvaluationContext();
2262 PopExpressionEvaluationContext();
2263}
2264
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002265static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2266 Expr *NumIterations, Sema &SemaRef,
2267 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002268
Alexey Bataeva769e072013-03-22 06:34:35 +00002269namespace {
2270
Alexey Bataeve3727102018-04-18 15:57:46 +00002271class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002272private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002273 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002274
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002275public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002276 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002277 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002278 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002279 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002280 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002281 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2282 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002283 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002284 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002285 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002286
2287 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002288 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002289 }
2290
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002291};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002292
Alexey Bataeve3727102018-04-18 15:57:46 +00002293class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002294private:
2295 Sema &SemaRef;
2296
2297public:
2298 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2299 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2300 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002301 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2302 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002303 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2304 SemaRef.getCurScope());
2305 }
2306 return false;
2307 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002308
2309 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002310 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002311 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002312};
2313
Alexey Bataeved09d242014-05-28 05:53:51 +00002314} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315
2316ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2317 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002318 const DeclarationNameInfo &Id,
2319 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002320 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2321 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2322
2323 if (Lookup.isAmbiguous())
2324 return ExprError();
2325
2326 VarDecl *VD;
2327 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002328 VarDeclFilterCCC CCC(*this);
2329 if (TypoCorrection Corrected =
2330 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2331 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002332 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002333 PDiag(Lookup.empty()
2334 ? diag::err_undeclared_var_use_suggest
2335 : diag::err_omp_expected_var_arg_suggest)
2336 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002337 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002338 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002339 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2340 : diag::err_omp_expected_var_arg)
2341 << Id.getName();
2342 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002343 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002344 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2345 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2346 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2347 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002348 }
2349 Lookup.suppressDiagnostics();
2350
2351 // OpenMP [2.9.2, Syntax, C/C++]
2352 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002353 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002354 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002355 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002356 bool IsDecl =
2357 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002358 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002359 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2360 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002361 return ExprError();
2362 }
2363
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002364 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002365 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002366 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2367 // A threadprivate directive for file-scope variables must appear outside
2368 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002369 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2370 !getCurLexicalContext()->isTranslationUnit()) {
2371 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002372 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002373 bool IsDecl =
2374 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2375 Diag(VD->getLocation(),
2376 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2377 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002378 return ExprError();
2379 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002380 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2381 // A threadprivate directive for static class member variables must appear
2382 // in the class definition, in the same scope in which the member
2383 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002384 if (CanonicalVD->isStaticDataMember() &&
2385 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2386 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002387 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002388 bool IsDecl =
2389 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2390 Diag(VD->getLocation(),
2391 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2392 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002393 return ExprError();
2394 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002395 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2396 // A threadprivate directive for namespace-scope variables must appear
2397 // outside any definition or declaration other than the namespace
2398 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002399 if (CanonicalVD->getDeclContext()->isNamespace() &&
2400 (!getCurLexicalContext()->isFileContext() ||
2401 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2402 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002403 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002404 bool IsDecl =
2405 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2406 Diag(VD->getLocation(),
2407 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2408 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002409 return ExprError();
2410 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002411 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2412 // A threadprivate directive for static block-scope variables must appear
2413 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002414 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002415 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002416 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002417 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002418 bool IsDecl =
2419 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2420 Diag(VD->getLocation(),
2421 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2422 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002423 return ExprError();
2424 }
2425
2426 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2427 // A threadprivate directive must lexically precede all references to any
2428 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002429 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2430 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002431 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002432 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002433 return ExprError();
2434 }
2435
2436 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002437 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2438 SourceLocation(), VD,
2439 /*RefersToEnclosingVariableOrCapture=*/false,
2440 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002441}
2442
Alexey Bataeved09d242014-05-28 05:53:51 +00002443Sema::DeclGroupPtrTy
2444Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2445 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002446 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002447 CurContext->addDecl(D);
2448 return DeclGroupPtrTy::make(DeclGroupRef(D));
2449 }
David Blaikie0403cb12016-01-15 23:43:25 +00002450 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002451}
2452
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002453namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002454class LocalVarRefChecker final
2455 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002456 Sema &SemaRef;
2457
2458public:
2459 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002460 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002461 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002462 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002463 diag::err_omp_local_var_in_threadprivate_init)
2464 << E->getSourceRange();
2465 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2466 << VD << VD->getSourceRange();
2467 return true;
2468 }
2469 }
2470 return false;
2471 }
2472 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002473 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002474 if (Child && Visit(Child))
2475 return true;
2476 }
2477 return false;
2478 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002479 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002480};
2481} // namespace
2482
Alexey Bataeved09d242014-05-28 05:53:51 +00002483OMPThreadPrivateDecl *
2484Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002485 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002486 for (Expr *RefExpr : VarList) {
2487 auto *DE = cast<DeclRefExpr>(RefExpr);
2488 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002489 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002490
Alexey Bataev376b4a42016-02-09 09:41:09 +00002491 // Mark variable as used.
2492 VD->setReferenced();
2493 VD->markUsed(Context);
2494
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002495 QualType QType = VD->getType();
2496 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2497 // It will be analyzed later.
2498 Vars.push_back(DE);
2499 continue;
2500 }
2501
Alexey Bataeva769e072013-03-22 06:34:35 +00002502 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2503 // A threadprivate variable must not have an incomplete type.
2504 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002505 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002506 continue;
2507 }
2508
2509 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2510 // A threadprivate variable must not have a reference type.
2511 if (VD->getType()->isReferenceType()) {
2512 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002513 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2514 bool IsDecl =
2515 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2516 Diag(VD->getLocation(),
2517 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2518 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002519 continue;
2520 }
2521
Samuel Antaof8b50122015-07-13 22:54:53 +00002522 // Check if this is a TLS variable. If TLS is not being supported, produce
2523 // the corresponding diagnostic.
2524 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2525 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2526 getLangOpts().OpenMPUseTLS &&
2527 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002528 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2529 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002530 Diag(ILoc, diag::err_omp_var_thread_local)
2531 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002532 bool IsDecl =
2533 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2534 Diag(VD->getLocation(),
2535 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2536 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002537 continue;
2538 }
2539
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002540 // Check if initial value of threadprivate variable reference variable with
2541 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002542 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002543 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002544 if (Checker.Visit(Init))
2545 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002546 }
2547
Alexey Bataeved09d242014-05-28 05:53:51 +00002548 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002549 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002550 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2551 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002552 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002553 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002554 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002555 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002556 if (!Vars.empty()) {
2557 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2558 Vars);
2559 D->setAccess(AS_public);
2560 }
2561 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002562}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002563
Alexey Bataev27ef9512019-03-20 20:14:22 +00002564static OMPAllocateDeclAttr::AllocatorTypeTy
2565getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2566 if (!Allocator)
2567 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2568 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2569 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002570 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002571 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002572 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002573 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002574 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2575 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2576 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002577 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002578 llvm::FoldingSetNodeID AEId, DAEId;
2579 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2580 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2581 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002582 AllocatorKindRes = AllocatorKind;
2583 break;
2584 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002585 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002586 return AllocatorKindRes;
2587}
2588
Alexey Bataeve106f252019-04-01 14:25:31 +00002589static bool checkPreviousOMPAllocateAttribute(
2590 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2591 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2592 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2593 return false;
2594 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2595 Expr *PrevAllocator = A->getAllocator();
2596 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2597 getAllocatorKind(S, Stack, PrevAllocator);
2598 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2599 if (AllocatorsMatch &&
2600 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2601 Allocator && PrevAllocator) {
2602 const Expr *AE = Allocator->IgnoreParenImpCasts();
2603 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2604 llvm::FoldingSetNodeID AEId, PAEId;
2605 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2606 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2607 AllocatorsMatch = AEId == PAEId;
2608 }
2609 if (!AllocatorsMatch) {
2610 SmallString<256> AllocatorBuffer;
2611 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2612 if (Allocator)
2613 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2614 SmallString<256> PrevAllocatorBuffer;
2615 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2616 if (PrevAllocator)
2617 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2618 S.getPrintingPolicy());
2619
2620 SourceLocation AllocatorLoc =
2621 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2622 SourceRange AllocatorRange =
2623 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2624 SourceLocation PrevAllocatorLoc =
2625 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2626 SourceRange PrevAllocatorRange =
2627 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2628 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2629 << (Allocator ? 1 : 0) << AllocatorStream.str()
2630 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2631 << AllocatorRange;
2632 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2633 << PrevAllocatorRange;
2634 return true;
2635 }
2636 return false;
2637}
2638
2639static void
2640applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2641 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2642 Expr *Allocator, SourceRange SR) {
2643 if (VD->hasAttr<OMPAllocateDeclAttr>())
2644 return;
2645 if (Allocator &&
2646 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2647 Allocator->isInstantiationDependent() ||
2648 Allocator->containsUnexpandedParameterPack()))
2649 return;
2650 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2651 Allocator, SR);
2652 VD->addAttr(A);
2653 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2654 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2655}
2656
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002657Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2658 SourceLocation Loc, ArrayRef<Expr *> VarList,
2659 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2660 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2661 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002662 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002663 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2664 // allocate directives that appear in a target region must specify an
2665 // allocator clause unless a requires directive with the dynamic_allocators
2666 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002667 if (LangOpts.OpenMPIsDevice &&
2668 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002669 targetDiag(Loc, diag::err_expected_allocator_clause);
2670 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002671 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002672 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002673 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2674 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002675 SmallVector<Expr *, 8> Vars;
2676 for (Expr *RefExpr : VarList) {
2677 auto *DE = cast<DeclRefExpr>(RefExpr);
2678 auto *VD = cast<VarDecl>(DE->getDecl());
2679
2680 // Check if this is a TLS variable or global register.
2681 if (VD->getTLSKind() != VarDecl::TLS_None ||
2682 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2683 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2684 !VD->isLocalVarDecl()))
2685 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002686
Alexey Bataev282555a2019-03-19 20:33:44 +00002687 // If the used several times in the allocate directive, the same allocator
2688 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002689 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2690 AllocatorKind, Allocator))
2691 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002692
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002693 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2694 // If a list item has a static storage type, the allocator expression in the
2695 // allocator clause must be a constant expression that evaluates to one of
2696 // the predefined memory allocator values.
2697 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002698 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002699 Diag(Allocator->getExprLoc(),
2700 diag::err_omp_expected_predefined_allocator)
2701 << Allocator->getSourceRange();
2702 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2703 VarDecl::DeclarationOnly;
2704 Diag(VD->getLocation(),
2705 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2706 << VD;
2707 continue;
2708 }
2709 }
2710
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002711 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002712 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2713 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002714 }
2715 if (Vars.empty())
2716 return nullptr;
2717 if (!Owner)
2718 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002719 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002720 D->setAccess(AS_public);
2721 Owner->addDecl(D);
2722 return DeclGroupPtrTy::make(DeclGroupRef(D));
2723}
2724
2725Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002726Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2727 ArrayRef<OMPClause *> ClauseList) {
2728 OMPRequiresDecl *D = nullptr;
2729 if (!CurContext->isFileContext()) {
2730 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2731 } else {
2732 D = CheckOMPRequiresDecl(Loc, ClauseList);
2733 if (D) {
2734 CurContext->addDecl(D);
2735 DSAStack->addRequiresDecl(D);
2736 }
2737 }
2738 return DeclGroupPtrTy::make(DeclGroupRef(D));
2739}
2740
2741OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2742 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002743 /// For target specific clauses, the requires directive cannot be
2744 /// specified after the handling of any of the target regions in the
2745 /// current compilation unit.
2746 ArrayRef<SourceLocation> TargetLocations =
2747 DSAStack->getEncounteredTargetLocs();
2748 if (!TargetLocations.empty()) {
2749 for (const OMPClause *CNew : ClauseList) {
2750 // Check if any of the requires clauses affect target regions.
2751 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2752 isa<OMPUnifiedAddressClause>(CNew) ||
2753 isa<OMPReverseOffloadClause>(CNew) ||
2754 isa<OMPDynamicAllocatorsClause>(CNew)) {
2755 Diag(Loc, diag::err_omp_target_before_requires)
2756 << getOpenMPClauseName(CNew->getClauseKind());
2757 for (SourceLocation TargetLoc : TargetLocations) {
2758 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2759 }
2760 }
2761 }
2762 }
2763
Kelvin Li1408f912018-09-26 04:28:39 +00002764 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2765 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2766 ClauseList);
2767 return nullptr;
2768}
2769
Alexey Bataeve3727102018-04-18 15:57:46 +00002770static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2771 const ValueDecl *D,
2772 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002773 bool IsLoopIterVar = false) {
2774 if (DVar.RefExpr) {
2775 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2776 << getOpenMPClauseName(DVar.CKind);
2777 return;
2778 }
2779 enum {
2780 PDSA_StaticMemberShared,
2781 PDSA_StaticLocalVarShared,
2782 PDSA_LoopIterVarPrivate,
2783 PDSA_LoopIterVarLinear,
2784 PDSA_LoopIterVarLastprivate,
2785 PDSA_ConstVarShared,
2786 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002787 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002788 PDSA_LocalVarPrivate,
2789 PDSA_Implicit
2790 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002791 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002792 auto ReportLoc = D->getLocation();
2793 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002794 if (IsLoopIterVar) {
2795 if (DVar.CKind == OMPC_private)
2796 Reason = PDSA_LoopIterVarPrivate;
2797 else if (DVar.CKind == OMPC_lastprivate)
2798 Reason = PDSA_LoopIterVarLastprivate;
2799 else
2800 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002801 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2802 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002803 Reason = PDSA_TaskVarFirstprivate;
2804 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002805 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002806 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002807 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002808 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002809 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002810 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002811 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002812 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002813 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002814 ReportHint = true;
2815 Reason = PDSA_LocalVarPrivate;
2816 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002817 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002818 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002819 << Reason << ReportHint
2820 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2821 } else if (DVar.ImplicitDSALoc.isValid()) {
2822 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2823 << getOpenMPClauseName(DVar.CKind);
2824 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002825}
2826
cchene06f3e02019-11-15 13:02:06 -05002827static OpenMPMapClauseKind
2828getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2829 bool IsAggregateOrDeclareTarget) {
2830 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2831 switch (M) {
2832 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2833 Kind = OMPC_MAP_alloc;
2834 break;
2835 case OMPC_DEFAULTMAP_MODIFIER_to:
2836 Kind = OMPC_MAP_to;
2837 break;
2838 case OMPC_DEFAULTMAP_MODIFIER_from:
2839 Kind = OMPC_MAP_from;
2840 break;
2841 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2842 Kind = OMPC_MAP_tofrom;
2843 break;
2844 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2845 case OMPC_DEFAULTMAP_MODIFIER_last:
2846 llvm_unreachable("Unexpected defaultmap implicit behavior");
2847 case OMPC_DEFAULTMAP_MODIFIER_none:
2848 case OMPC_DEFAULTMAP_MODIFIER_default:
2849 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2850 // IsAggregateOrDeclareTarget could be true if:
2851 // 1. the implicit behavior for aggregate is tofrom
2852 // 2. it's a declare target link
2853 if (IsAggregateOrDeclareTarget) {
2854 Kind = OMPC_MAP_tofrom;
2855 break;
2856 }
2857 llvm_unreachable("Unexpected defaultmap implicit behavior");
2858 }
2859 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2860 return Kind;
2861}
2862
Alexey Bataev758e55e2013-09-06 18:03:48 +00002863namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002864class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002865 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002866 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002867 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002868 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002869 CapturedStmt *CS = nullptr;
2870 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002871 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002872 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2873 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002874
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002875 void VisitSubCaptures(OMPExecutableDirective *S) {
2876 // Check implicitly captured variables.
2877 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2878 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002879 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002880 // Try to capture inner this->member references to generate correct mappings
2881 // and diagnostics.
2882 if (TryCaptureCXXThisMembers ||
2883 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2884 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2885 [](const CapturedStmt::Capture &C) {
2886 return C.capturesThis();
2887 }))) {
2888 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2889 TryCaptureCXXThisMembers = true;
2890 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2891 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2892 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002893 }
2894
Alexey Bataev758e55e2013-09-06 18:03:48 +00002895public:
2896 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002897 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2898 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2899 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002900 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002901 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002902 // Check the datasharing rules for the expressions in the clauses.
2903 if (!CS) {
2904 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2905 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2906 Visit(CED->getInit());
2907 return;
2908 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002909 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2910 // Do not analyze internal variables and do not enclose them into
2911 // implicit clauses.
2912 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002913 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002914 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002915 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002916 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002917
Alexey Bataeve3727102018-04-18 15:57:46 +00002918 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002919 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002920 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002921 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002922
Alexey Bataevafe50572017-10-06 17:00:28 +00002923 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002924 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002925 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002926 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002927 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2928 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002929 return;
2930
Alexey Bataeve3727102018-04-18 15:57:46 +00002931 SourceLocation ELoc = E->getExprLoc();
2932 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002933 // The default(none) clause requires that each variable that is referenced
2934 // in the construct, and does not have a predetermined data-sharing
2935 // attribute, must have its data-sharing attribute explicitly determined
2936 // by being listed in a data-sharing attribute clause.
2937 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002938 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002939 VarsWithInheritedDSA.count(VD) == 0) {
2940 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002941 return;
2942 }
2943
cchene06f3e02019-11-15 13:02:06 -05002944 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
2945 // If implicit-behavior is none, each variable referenced in the
2946 // construct that does not have a predetermined data-sharing attribute
2947 // and does not appear in a to or link clause on a declare target
2948 // directive must be listed in a data-mapping attribute clause, a
2949 // data-haring attribute clause (including a data-sharing attribute
2950 // clause on a combined construct where target. is one of the
2951 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002952 OpenMPDefaultmapClauseKind ClauseKind =
2953 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05002954 if (SemaRef.getLangOpts().OpenMP >= 50) {
2955 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
2956 OMPC_DEFAULTMAP_MODIFIER_none;
2957 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
2958 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
2959 // Only check for data-mapping attribute and is_device_ptr here
2960 // since we have already make sure that the declaration does not
2961 // have a data-sharing attribute above
2962 if (!Stack->checkMappableExprComponentListsForDecl(
2963 VD, /*CurrentRegionOnly=*/true,
2964 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
2965 MapExprComponents,
2966 OpenMPClauseKind) {
2967 auto MI = MapExprComponents.rbegin();
2968 auto ME = MapExprComponents.rend();
2969 return MI != ME && MI->getAssociatedDeclaration() == VD;
2970 })) {
2971 VarsWithInheritedDSA[VD] = E;
2972 return;
2973 }
2974 }
2975 }
2976
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002977 if (isOpenMPTargetExecutionDirective(DKind) &&
2978 !Stack->isLoopControlVariable(VD).first) {
2979 if (!Stack->checkMappableExprComponentListsForDecl(
2980 VD, /*CurrentRegionOnly=*/true,
2981 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2982 StackComponents,
2983 OpenMPClauseKind) {
2984 // Variable is used if it has been marked as an array, array
2985 // section or the variable iself.
2986 return StackComponents.size() == 1 ||
2987 std::all_of(
2988 std::next(StackComponents.rbegin()),
2989 StackComponents.rend(),
2990 [](const OMPClauseMappableExprCommon::
2991 MappableComponent &MC) {
2992 return MC.getAssociatedDeclaration() ==
2993 nullptr &&
2994 (isa<OMPArraySectionExpr>(
2995 MC.getAssociatedExpression()) ||
2996 isa<ArraySubscriptExpr>(
2997 MC.getAssociatedExpression()));
2998 });
2999 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003000 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003001 // By default lambdas are captured as firstprivates.
3002 if (const auto *RD =
3003 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003004 IsFirstprivate = RD->isLambda();
3005 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003006 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3007 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003008 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003009 } else {
3010 OpenMPDefaultmapClauseModifier M =
3011 Stack->getDefaultmapModifier(ClauseKind);
3012 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3013 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3014 ImplicitMap[Kind].emplace_back(E);
3015 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003016 return;
3017 }
3018 }
3019
Alexey Bataev758e55e2013-09-06 18:03:48 +00003020 // OpenMP [2.9.3.6, Restrictions, p.2]
3021 // A list item that appears in a reduction clause of the innermost
3022 // enclosing worksharing or parallel construct may not be accessed in an
3023 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003024 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003025 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3026 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003027 return isOpenMPParallelDirective(K) ||
3028 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3029 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003030 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003031 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003032 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003033 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003034 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003035 return;
3036 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003037
3038 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003039 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003040 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003041 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003042 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003043 return;
3044 }
3045
3046 // Store implicitly used globals with declare target link for parent
3047 // target.
3048 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3049 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3050 Stack->addToParentTargetRegionLinkGlobals(E);
3051 return;
3052 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003053 }
3054 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003055 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003056 if (E->isTypeDependent() || E->isValueDependent() ||
3057 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3058 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003059 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003060 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003061 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003062 if (!FD)
3063 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003064 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003065 // Check if the variable has explicit DSA set and stop analysis if it
3066 // so.
3067 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3068 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003069
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003070 if (isOpenMPTargetExecutionDirective(DKind) &&
3071 !Stack->isLoopControlVariable(FD).first &&
3072 !Stack->checkMappableExprComponentListsForDecl(
3073 FD, /*CurrentRegionOnly=*/true,
3074 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3075 StackComponents,
3076 OpenMPClauseKind) {
3077 return isa<CXXThisExpr>(
3078 cast<MemberExpr>(
3079 StackComponents.back().getAssociatedExpression())
3080 ->getBase()
3081 ->IgnoreParens());
3082 })) {
3083 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3084 // A bit-field cannot appear in a map clause.
3085 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003086 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003087 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003088
3089 // Check to see if the member expression is referencing a class that
3090 // has already been explicitly mapped
3091 if (Stack->isClassPreviouslyMapped(TE->getType()))
3092 return;
3093
cchene06f3e02019-11-15 13:02:06 -05003094 OpenMPDefaultmapClauseModifier Modifier =
3095 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3096 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3097 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3098 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003099 return;
3100 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003101
Alexey Bataeve3727102018-04-18 15:57:46 +00003102 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003103 // OpenMP [2.9.3.6, Restrictions, p.2]
3104 // A list item that appears in a reduction clause of the innermost
3105 // enclosing worksharing or parallel construct may not be accessed in
3106 // an explicit task.
3107 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003108 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3109 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003110 return isOpenMPParallelDirective(K) ||
3111 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3112 },
3113 /*FromParent=*/true);
3114 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3115 ErrorFound = true;
3116 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003117 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003118 return;
3119 }
3120
3121 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003122 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003123 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003124 !Stack->isLoopControlVariable(FD).first) {
3125 // Check if there is a captured expression for the current field in the
3126 // region. Do not mark it as firstprivate unless there is no captured
3127 // expression.
3128 // TODO: try to make it firstprivate.
3129 if (DVar.CKind != OMPC_unknown)
3130 ImplicitFirstprivate.push_back(E);
3131 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003132 return;
3133 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003134 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003135 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003136 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003137 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003138 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003139 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003140 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3141 if (!Stack->checkMappableExprComponentListsForDecl(
3142 VD, /*CurrentRegionOnly=*/true,
3143 [&CurComponents](
3144 OMPClauseMappableExprCommon::MappableExprComponentListRef
3145 StackComponents,
3146 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003147 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003148 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003149 for (const auto &SC : llvm::reverse(StackComponents)) {
3150 // Do both expressions have the same kind?
3151 if (CCI->getAssociatedExpression()->getStmtClass() !=
3152 SC.getAssociatedExpression()->getStmtClass())
3153 if (!(isa<OMPArraySectionExpr>(
3154 SC.getAssociatedExpression()) &&
3155 isa<ArraySubscriptExpr>(
3156 CCI->getAssociatedExpression())))
3157 return false;
3158
Alexey Bataeve3727102018-04-18 15:57:46 +00003159 const Decl *CCD = CCI->getAssociatedDeclaration();
3160 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003161 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3162 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3163 if (SCD != CCD)
3164 return false;
3165 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003166 if (CCI == CCE)
3167 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003168 }
3169 return true;
3170 })) {
3171 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003172 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003173 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003174 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003175 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003176 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003177 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003178 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003179 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003180 // for task|target directives.
3181 // Skip analysis of arguments of implicitly defined map clause for target
3182 // directives.
3183 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3184 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003185 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003186 if (CC)
3187 Visit(CC);
3188 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003189 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003190 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003191 // Check implicitly captured variables.
3192 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003193 }
3194 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003195 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003196 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003197 // Check implicitly captured variables in the task-based directives to
3198 // check if they must be firstprivatized.
3199 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003200 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003201 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003203
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003204 void visitSubCaptures(CapturedStmt *S) {
3205 for (const CapturedStmt::Capture &Cap : S->captures()) {
3206 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3207 continue;
3208 VarDecl *VD = Cap.getCapturedVar();
3209 // Do not try to map the variable if it or its sub-component was mapped
3210 // already.
3211 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3212 Stack->checkMappableExprComponentListsForDecl(
3213 VD, /*CurrentRegionOnly=*/true,
3214 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3215 OpenMPClauseKind) { return true; }))
3216 continue;
3217 DeclRefExpr *DRE = buildDeclRefExpr(
3218 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3219 Cap.getLocation(), /*RefersToCapture=*/true);
3220 Visit(DRE);
3221 }
3222 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003223 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003224 ArrayRef<Expr *> getImplicitFirstprivate() const {
3225 return ImplicitFirstprivate;
3226 }
cchene06f3e02019-11-15 13:02:06 -05003227 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3228 return ImplicitMap[Kind];
3229 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003230 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003231 return VarsWithInheritedDSA;
3232 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003233
Alexey Bataev7ff55242014-06-19 09:13:45 +00003234 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003235 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3236 // Process declare target link variables for the target directives.
3237 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3238 for (DeclRefExpr *E : Stack->getLinkGlobals())
3239 Visit(E);
3240 }
3241 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003242};
Alexey Bataeved09d242014-05-28 05:53:51 +00003243} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003244
Alexey Bataevbae9a792014-06-27 10:37:06 +00003245void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003246 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003247 case OMPD_parallel:
3248 case OMPD_parallel_for:
3249 case OMPD_parallel_for_simd:
3250 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003251 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003252 case OMPD_teams_distribute:
3253 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003254 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003255 QualType KmpInt32PtrTy =
3256 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003257 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003258 std::make_pair(".global_tid.", KmpInt32PtrTy),
3259 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3260 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003261 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003262 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3263 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003264 break;
3265 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003266 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003267 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003268 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003269 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003270 case OMPD_target_teams_distribute:
3271 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003272 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3273 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3274 QualType KmpInt32PtrTy =
3275 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3276 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003277 FunctionProtoType::ExtProtoInfo EPI;
3278 EPI.Variadic = true;
3279 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3280 Sema::CapturedParamNameType Params[] = {
3281 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003282 std::make_pair(".part_id.", KmpInt32PtrTy),
3283 std::make_pair(".privates.", VoidPtrTy),
3284 std::make_pair(
3285 ".copy_fn.",
3286 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003287 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3288 std::make_pair(StringRef(), QualType()) // __context with shared vars
3289 };
3290 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003291 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003292 // Mark this captured region as inlined, because we don't use outlined
3293 // function directly.
3294 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3295 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003296 Context, {}, AttributeCommonInfo::AS_Keyword,
3297 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003298 Sema::CapturedParamNameType ParamsTarget[] = {
3299 std::make_pair(StringRef(), QualType()) // __context with shared vars
3300 };
3301 // Start a captured region for 'target' with no implicit parameters.
3302 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003303 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003304 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003305 std::make_pair(".global_tid.", KmpInt32PtrTy),
3306 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3307 std::make_pair(StringRef(), QualType()) // __context with shared vars
3308 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003309 // Start a captured region for 'teams' or 'parallel'. Both regions have
3310 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003311 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003312 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003313 break;
3314 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003315 case OMPD_target:
3316 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003317 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3318 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3319 QualType KmpInt32PtrTy =
3320 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3321 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003322 FunctionProtoType::ExtProtoInfo EPI;
3323 EPI.Variadic = true;
3324 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3325 Sema::CapturedParamNameType Params[] = {
3326 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003327 std::make_pair(".part_id.", KmpInt32PtrTy),
3328 std::make_pair(".privates.", VoidPtrTy),
3329 std::make_pair(
3330 ".copy_fn.",
3331 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003332 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3333 std::make_pair(StringRef(), QualType()) // __context with shared vars
3334 };
3335 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003336 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003337 // Mark this captured region as inlined, because we don't use outlined
3338 // function directly.
3339 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3340 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003341 Context, {}, AttributeCommonInfo::AS_Keyword,
3342 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003343 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003344 std::make_pair(StringRef(), QualType()),
3345 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003346 break;
3347 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003348 case OMPD_simd:
3349 case OMPD_for:
3350 case OMPD_for_simd:
3351 case OMPD_sections:
3352 case OMPD_section:
3353 case OMPD_single:
3354 case OMPD_master:
3355 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003356 case OMPD_taskgroup:
3357 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003358 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003359 case OMPD_ordered:
3360 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003361 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003362 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003363 std::make_pair(StringRef(), QualType()) // __context with shared vars
3364 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003365 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3366 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003367 break;
3368 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003369 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003370 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3371 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3372 QualType KmpInt32PtrTy =
3373 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3374 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003375 FunctionProtoType::ExtProtoInfo EPI;
3376 EPI.Variadic = true;
3377 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003378 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003379 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003380 std::make_pair(".part_id.", KmpInt32PtrTy),
3381 std::make_pair(".privates.", VoidPtrTy),
3382 std::make_pair(
3383 ".copy_fn.",
3384 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003385 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003386 std::make_pair(StringRef(), QualType()) // __context with shared vars
3387 };
3388 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3389 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003390 // Mark this captured region as inlined, because we don't use outlined
3391 // function directly.
3392 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3393 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003394 Context, {}, AttributeCommonInfo::AS_Keyword,
3395 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003396 break;
3397 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003398 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003399 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003400 case OMPD_master_taskloop:
3401 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003402 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003403 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3404 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003405 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003406 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3407 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003408 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003409 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3410 .withConst();
3411 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3412 QualType KmpInt32PtrTy =
3413 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3414 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003415 FunctionProtoType::ExtProtoInfo EPI;
3416 EPI.Variadic = true;
3417 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003418 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003419 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003420 std::make_pair(".part_id.", KmpInt32PtrTy),
3421 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003422 std::make_pair(
3423 ".copy_fn.",
3424 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3425 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3426 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003427 std::make_pair(".ub.", KmpUInt64Ty),
3428 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003429 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003430 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003431 std::make_pair(StringRef(), QualType()) // __context with shared vars
3432 };
3433 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3434 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003435 // Mark this captured region as inlined, because we don't use outlined
3436 // function directly.
3437 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3438 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003439 Context, {}, AttributeCommonInfo::AS_Keyword,
3440 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003441 break;
3442 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003443 case OMPD_parallel_master_taskloop:
3444 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003445 QualType KmpInt32Ty =
3446 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3447 .withConst();
3448 QualType KmpUInt64Ty =
3449 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3450 .withConst();
3451 QualType KmpInt64Ty =
3452 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3453 .withConst();
3454 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3455 QualType KmpInt32PtrTy =
3456 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3457 Sema::CapturedParamNameType ParamsParallel[] = {
3458 std::make_pair(".global_tid.", KmpInt32PtrTy),
3459 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3460 std::make_pair(StringRef(), QualType()) // __context with shared vars
3461 };
3462 // Start a captured region for 'parallel'.
3463 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3464 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3465 QualType Args[] = {VoidPtrTy};
3466 FunctionProtoType::ExtProtoInfo EPI;
3467 EPI.Variadic = true;
3468 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3469 Sema::CapturedParamNameType Params[] = {
3470 std::make_pair(".global_tid.", KmpInt32Ty),
3471 std::make_pair(".part_id.", KmpInt32PtrTy),
3472 std::make_pair(".privates.", VoidPtrTy),
3473 std::make_pair(
3474 ".copy_fn.",
3475 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3476 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3477 std::make_pair(".lb.", KmpUInt64Ty),
3478 std::make_pair(".ub.", KmpUInt64Ty),
3479 std::make_pair(".st.", KmpInt64Ty),
3480 std::make_pair(".liter.", KmpInt32Ty),
3481 std::make_pair(".reductions.", VoidPtrTy),
3482 std::make_pair(StringRef(), QualType()) // __context with shared vars
3483 };
3484 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3485 Params, /*OpenMPCaptureLevel=*/2);
3486 // Mark this captured region as inlined, because we don't use outlined
3487 // function directly.
3488 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3489 AlwaysInlineAttr::CreateImplicit(
3490 Context, {}, AttributeCommonInfo::AS_Keyword,
3491 AlwaysInlineAttr::Keyword_forceinline));
3492 break;
3493 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003494 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003495 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003496 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003497 QualType KmpInt32PtrTy =
3498 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3499 Sema::CapturedParamNameType Params[] = {
3500 std::make_pair(".global_tid.", KmpInt32PtrTy),
3501 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003502 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3503 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003504 std::make_pair(StringRef(), QualType()) // __context with shared vars
3505 };
3506 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3507 Params);
3508 break;
3509 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003510 case OMPD_target_teams_distribute_parallel_for:
3511 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003512 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003513 QualType KmpInt32PtrTy =
3514 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003515 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003516
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003517 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003518 FunctionProtoType::ExtProtoInfo EPI;
3519 EPI.Variadic = true;
3520 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3521 Sema::CapturedParamNameType Params[] = {
3522 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003523 std::make_pair(".part_id.", KmpInt32PtrTy),
3524 std::make_pair(".privates.", VoidPtrTy),
3525 std::make_pair(
3526 ".copy_fn.",
3527 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003528 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3529 std::make_pair(StringRef(), QualType()) // __context with shared vars
3530 };
3531 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003532 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003533 // Mark this captured region as inlined, because we don't use outlined
3534 // function directly.
3535 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3536 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003537 Context, {}, AttributeCommonInfo::AS_Keyword,
3538 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003539 Sema::CapturedParamNameType ParamsTarget[] = {
3540 std::make_pair(StringRef(), QualType()) // __context with shared vars
3541 };
3542 // Start a captured region for 'target' with no implicit parameters.
3543 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003544 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003545
3546 Sema::CapturedParamNameType ParamsTeams[] = {
3547 std::make_pair(".global_tid.", KmpInt32PtrTy),
3548 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3549 std::make_pair(StringRef(), QualType()) // __context with shared vars
3550 };
3551 // Start a captured region for 'target' with no implicit parameters.
3552 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003553 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003554
3555 Sema::CapturedParamNameType ParamsParallel[] = {
3556 std::make_pair(".global_tid.", KmpInt32PtrTy),
3557 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003558 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3559 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003560 std::make_pair(StringRef(), QualType()) // __context with shared vars
3561 };
3562 // Start a captured region for 'teams' or 'parallel'. Both regions have
3563 // the same implicit parameters.
3564 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003565 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003566 break;
3567 }
3568
Alexey Bataev46506272017-12-05 17:41:34 +00003569 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003570 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003571 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003572 QualType KmpInt32PtrTy =
3573 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3574
3575 Sema::CapturedParamNameType ParamsTeams[] = {
3576 std::make_pair(".global_tid.", KmpInt32PtrTy),
3577 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3578 std::make_pair(StringRef(), QualType()) // __context with shared vars
3579 };
3580 // Start a captured region for 'target' with no implicit parameters.
3581 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003582 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003583
3584 Sema::CapturedParamNameType ParamsParallel[] = {
3585 std::make_pair(".global_tid.", KmpInt32PtrTy),
3586 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003587 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3588 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003589 std::make_pair(StringRef(), QualType()) // __context with shared vars
3590 };
3591 // Start a captured region for 'teams' or 'parallel'. Both regions have
3592 // the same implicit parameters.
3593 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003594 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003595 break;
3596 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003597 case OMPD_target_update:
3598 case OMPD_target_enter_data:
3599 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003600 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3601 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3602 QualType KmpInt32PtrTy =
3603 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3604 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003605 FunctionProtoType::ExtProtoInfo EPI;
3606 EPI.Variadic = true;
3607 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3608 Sema::CapturedParamNameType Params[] = {
3609 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003610 std::make_pair(".part_id.", KmpInt32PtrTy),
3611 std::make_pair(".privates.", VoidPtrTy),
3612 std::make_pair(
3613 ".copy_fn.",
3614 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003615 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3616 std::make_pair(StringRef(), QualType()) // __context with shared vars
3617 };
3618 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3619 Params);
3620 // Mark this captured region as inlined, because we don't use outlined
3621 // function directly.
3622 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3623 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003624 Context, {}, AttributeCommonInfo::AS_Keyword,
3625 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003626 break;
3627 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003628 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003629 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003630 case OMPD_taskyield:
3631 case OMPD_barrier:
3632 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003633 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003634 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003635 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003636 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003637 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003638 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003639 case OMPD_declare_target:
3640 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003641 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003642 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003643 llvm_unreachable("OpenMP Directive is not allowed");
3644 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003645 llvm_unreachable("Unknown OpenMP directive");
3646 }
3647}
3648
Alexey Bataev0e100032019-10-14 16:44:01 +00003649int Sema::getNumberOfConstructScopes(unsigned Level) const {
3650 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3651}
3652
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003653int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3654 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3655 getOpenMPCaptureRegions(CaptureRegions, DKind);
3656 return CaptureRegions.size();
3657}
3658
Alexey Bataev3392d762016-02-16 11:18:12 +00003659static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003660 Expr *CaptureExpr, bool WithInit,
3661 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003662 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003663 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003664 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003665 QualType Ty = Init->getType();
3666 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003667 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003668 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003669 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003670 Ty = C.getPointerType(Ty);
3671 ExprResult Res =
3672 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3673 if (!Res.isUsable())
3674 return nullptr;
3675 Init = Res.get();
3676 }
Alexey Bataev61205072016-03-02 04:57:40 +00003677 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003678 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003679 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003680 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003681 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003682 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003683 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003684 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003685 return CED;
3686}
3687
Alexey Bataev61205072016-03-02 04:57:40 +00003688static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3689 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003690 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003691 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003692 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003693 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3695 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003696 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003697 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003698}
3699
Alexey Bataev5a3af132016-03-29 08:58:54 +00003700static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003701 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003702 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003703 OMPCapturedExprDecl *CD = buildCaptureDecl(
3704 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3705 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003706 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3707 CaptureExpr->getExprLoc());
3708 }
3709 ExprResult Res = Ref;
3710 if (!S.getLangOpts().CPlusPlus &&
3711 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003712 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003713 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003714 if (!Res.isUsable())
3715 return ExprError();
3716 }
3717 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003718}
3719
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003720namespace {
3721// OpenMP directives parsed in this section are represented as a
3722// CapturedStatement with an associated statement. If a syntax error
3723// is detected during the parsing of the associated statement, the
3724// compiler must abort processing and close the CapturedStatement.
3725//
3726// Combined directives such as 'target parallel' have more than one
3727// nested CapturedStatements. This RAII ensures that we unwind out
3728// of all the nested CapturedStatements when an error is found.
3729class CaptureRegionUnwinderRAII {
3730private:
3731 Sema &S;
3732 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003733 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003734
3735public:
3736 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3737 OpenMPDirectiveKind DKind)
3738 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3739 ~CaptureRegionUnwinderRAII() {
3740 if (ErrorFound) {
3741 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3742 while (--ThisCaptureLevel >= 0)
3743 S.ActOnCapturedRegionError();
3744 }
3745 }
3746};
3747} // namespace
3748
Alexey Bataevb600ae32019-07-01 17:46:52 +00003749void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3750 // Capture variables captured by reference in lambdas for target-based
3751 // directives.
3752 if (!CurContext->isDependentContext() &&
3753 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3754 isOpenMPTargetDataManagementDirective(
3755 DSAStack->getCurrentDirective()))) {
3756 QualType Type = V->getType();
3757 if (const auto *RD = Type.getCanonicalType()
3758 .getNonReferenceType()
3759 ->getAsCXXRecordDecl()) {
3760 bool SavedForceCaptureByReferenceInTargetExecutable =
3761 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3762 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3763 /*V=*/true);
3764 if (RD->isLambda()) {
3765 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3766 FieldDecl *ThisCapture;
3767 RD->getCaptureFields(Captures, ThisCapture);
3768 for (const LambdaCapture &LC : RD->captures()) {
3769 if (LC.getCaptureKind() == LCK_ByRef) {
3770 VarDecl *VD = LC.getCapturedVar();
3771 DeclContext *VDC = VD->getDeclContext();
3772 if (!VDC->Encloses(CurContext))
3773 continue;
3774 MarkVariableReferenced(LC.getLocation(), VD);
3775 } else if (LC.getCaptureKind() == LCK_This) {
3776 QualType ThisTy = getCurrentThisType();
3777 if (!ThisTy.isNull() &&
3778 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3779 CheckCXXThisCapture(LC.getLocation());
3780 }
3781 }
3782 }
3783 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3784 SavedForceCaptureByReferenceInTargetExecutable);
3785 }
3786 }
3787}
3788
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003789StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3790 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003791 bool ErrorFound = false;
3792 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3793 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003794 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003795 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003796 return StmtError();
3797 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003798
Alexey Bataev2ba67042017-11-28 21:11:44 +00003799 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3800 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003801 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003802 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003803 SmallVector<const OMPLinearClause *, 4> LCs;
3804 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003805 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003806 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003807 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3808 Clause->getClauseKind() == OMPC_in_reduction) {
3809 // Capture taskgroup task_reduction descriptors inside the tasking regions
3810 // with the corresponding in_reduction items.
3811 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003812 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003813 if (E)
3814 MarkDeclarationsReferencedInExpr(E);
3815 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003816 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003817 Clause->getClauseKind() == OMPC_copyprivate ||
3818 (getLangOpts().OpenMPUseTLS &&
3819 getASTContext().getTargetInfo().isTLSSupported() &&
3820 Clause->getClauseKind() == OMPC_copyin)) {
3821 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003822 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003823 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003824 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003825 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003826 }
3827 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003828 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003829 } else if (CaptureRegions.size() > 1 ||
3830 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003831 if (auto *C = OMPClauseWithPreInit::get(Clause))
3832 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003833 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003834 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003835 MarkDeclarationsReferencedInExpr(E);
3836 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003837 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003838 if (Clause->getClauseKind() == OMPC_schedule)
3839 SC = cast<OMPScheduleClause>(Clause);
3840 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003841 OC = cast<OMPOrderedClause>(Clause);
3842 else if (Clause->getClauseKind() == OMPC_linear)
3843 LCs.push_back(cast<OMPLinearClause>(Clause));
3844 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003845 // OpenMP, 2.7.1 Loop Construct, Restrictions
3846 // The nonmonotonic modifier cannot be specified if an ordered clause is
3847 // specified.
3848 if (SC &&
3849 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3850 SC->getSecondScheduleModifier() ==
3851 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3852 OC) {
3853 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3854 ? SC->getFirstScheduleModifierLoc()
3855 : SC->getSecondScheduleModifierLoc(),
3856 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003857 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003858 ErrorFound = true;
3859 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003860 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003861 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003862 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003863 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003864 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003865 ErrorFound = true;
3866 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003867 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3868 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3869 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003870 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003871 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3872 ErrorFound = true;
3873 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003874 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003875 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003876 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003877 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003878 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003879 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003880 // Mark all variables in private list clauses as used in inner region.
3881 // Required for proper codegen of combined directives.
3882 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003883 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003884 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003885 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3886 // Find the particular capture region for the clause if the
3887 // directive is a combined one with multiple capture regions.
3888 // If the directive is not a combined one, the capture region
3889 // associated with the clause is OMPD_unknown and is generated
3890 // only once.
3891 if (CaptureRegion == ThisCaptureRegion ||
3892 CaptureRegion == OMPD_unknown) {
3893 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003894 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003895 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3896 }
3897 }
3898 }
3899 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003900 if (++CompletedRegions == CaptureRegions.size())
3901 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003902 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003903 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003904 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003905}
3906
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003907static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3908 OpenMPDirectiveKind CancelRegion,
3909 SourceLocation StartLoc) {
3910 // CancelRegion is only needed for cancel and cancellation_point.
3911 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3912 return false;
3913
3914 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3915 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3916 return false;
3917
3918 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3919 << getOpenMPDirectiveName(CancelRegion);
3920 return true;
3921}
3922
Alexey Bataeve3727102018-04-18 15:57:46 +00003923static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003924 OpenMPDirectiveKind CurrentRegion,
3925 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003926 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003927 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003928 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003929 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3930 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003931 bool NestingProhibited = false;
3932 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003933 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003934 enum {
3935 NoRecommend,
3936 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003937 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003938 ShouldBeInTargetRegion,
3939 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003940 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003941 if (isOpenMPSimdDirective(ParentRegion) &&
3942 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
3943 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
3944 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003945 // OpenMP [2.16, Nesting of Regions]
3946 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003947 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003948 // An ordered construct with the simd clause is the only OpenMP
3949 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003950 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003951 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3952 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003953 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
3954 // The only OpenMP constructs that can be encountered during execution of
3955 // a simd region are the atomic construct, the loop construct, the simd
3956 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00003957 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3958 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003959 : diag::warn_omp_nesting_simd)
3960 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00003961 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003962 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003963 if (ParentRegion == OMPD_atomic) {
3964 // OpenMP [2.16, Nesting of Regions]
3965 // OpenMP constructs may not be nested inside an atomic region.
3966 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3967 return true;
3968 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003969 if (CurrentRegion == OMPD_section) {
3970 // OpenMP [2.7.2, sections Construct, Restrictions]
3971 // Orphaned section directives are prohibited. That is, the section
3972 // directives must appear within the sections construct and must not be
3973 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003974 if (ParentRegion != OMPD_sections &&
3975 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003976 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3977 << (ParentRegion != OMPD_unknown)
3978 << getOpenMPDirectiveName(ParentRegion);
3979 return true;
3980 }
3981 return false;
3982 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003983 // Allow some constructs (except teams and cancellation constructs) to be
3984 // orphaned (they could be used in functions, called from OpenMP regions
3985 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003986 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003987 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3988 CurrentRegion != OMPD_cancellation_point &&
3989 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003990 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003991 if (CurrentRegion == OMPD_cancellation_point ||
3992 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003993 // OpenMP [2.16, Nesting of Regions]
3994 // A cancellation point construct for which construct-type-clause is
3995 // taskgroup must be nested inside a task construct. A cancellation
3996 // point construct for which construct-type-clause is not taskgroup must
3997 // be closely nested inside an OpenMP construct that matches the type
3998 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003999 // A cancel construct for which construct-type-clause is taskgroup must be
4000 // nested inside a task construct. A cancel construct for which
4001 // construct-type-clause is not taskgroup must be closely nested inside an
4002 // OpenMP construct that matches the type specified in
4003 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004004 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004005 !((CancelRegion == OMPD_parallel &&
4006 (ParentRegion == OMPD_parallel ||
4007 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004008 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004009 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004010 ParentRegion == OMPD_target_parallel_for ||
4011 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004012 ParentRegion == OMPD_teams_distribute_parallel_for ||
4013 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004014 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4015 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004016 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4017 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004018 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004019 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004020 // OpenMP [2.16, Nesting of Regions]
4021 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004022 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004023 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004024 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004025 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4026 // OpenMP [2.16, Nesting of Regions]
4027 // A critical region may not be nested (closely or otherwise) inside a
4028 // critical region with the same name. Note that this restriction is not
4029 // sufficient to prevent deadlock.
4030 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004031 bool DeadLock = Stack->hasDirective(
4032 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4033 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004034 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004035 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4036 PreviousCriticalLoc = Loc;
4037 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004038 }
4039 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004040 },
4041 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004042 if (DeadLock) {
4043 SemaRef.Diag(StartLoc,
4044 diag::err_omp_prohibited_region_critical_same_name)
4045 << CurrentName.getName();
4046 if (PreviousCriticalLoc.isValid())
4047 SemaRef.Diag(PreviousCriticalLoc,
4048 diag::note_omp_previous_critical_region);
4049 return true;
4050 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004051 } else if (CurrentRegion == OMPD_barrier) {
4052 // OpenMP [2.16, Nesting of Regions]
4053 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004054 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004055 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4056 isOpenMPTaskingDirective(ParentRegion) ||
4057 ParentRegion == OMPD_master ||
4058 ParentRegion == OMPD_critical ||
4059 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004060 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004061 !isOpenMPParallelDirective(CurrentRegion) &&
4062 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004063 // OpenMP [2.16, Nesting of Regions]
4064 // A worksharing region may not be closely nested inside a worksharing,
4065 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004066 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4067 isOpenMPTaskingDirective(ParentRegion) ||
4068 ParentRegion == OMPD_master ||
4069 ParentRegion == OMPD_critical ||
4070 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004071 Recommend = ShouldBeInParallelRegion;
4072 } else if (CurrentRegion == OMPD_ordered) {
4073 // OpenMP [2.16, Nesting of Regions]
4074 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004075 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004076 // An ordered region must be closely nested inside a loop region (or
4077 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004078 // OpenMP [2.8.1,simd Construct, Restrictions]
4079 // An ordered construct with the simd clause is the only OpenMP construct
4080 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004081 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004082 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004083 !(isOpenMPSimdDirective(ParentRegion) ||
4084 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004085 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004086 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004087 // OpenMP [2.16, Nesting of Regions]
4088 // If specified, a teams construct must be contained within a target
4089 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004090 NestingProhibited =
4091 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4092 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4093 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004094 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004095 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004096 }
Kelvin Libf594a52016-12-17 05:48:59 +00004097 if (!NestingProhibited &&
4098 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4099 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4100 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004101 // OpenMP [2.16, Nesting of Regions]
4102 // distribute, parallel, parallel sections, parallel workshare, and the
4103 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4104 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004105 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4106 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004107 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004108 }
David Majnemer9d168222016-08-05 17:44:54 +00004109 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004110 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004111 // OpenMP 4.5 [2.17 Nesting of Regions]
4112 // The region associated with the distribute construct must be strictly
4113 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004114 NestingProhibited =
4115 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004116 Recommend = ShouldBeInTeamsRegion;
4117 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004118 if (!NestingProhibited &&
4119 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4120 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4121 // OpenMP 4.5 [2.17 Nesting of Regions]
4122 // If a target, target update, target data, target enter data, or
4123 // target exit data construct is encountered during execution of a
4124 // target region, the behavior is unspecified.
4125 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004126 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004127 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004128 if (isOpenMPTargetExecutionDirective(K)) {
4129 OffendingRegion = K;
4130 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004131 }
4132 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004133 },
4134 false /* don't skip top directive */);
4135 CloseNesting = false;
4136 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004137 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004138 if (OrphanSeen) {
4139 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4140 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4141 } else {
4142 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4143 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4144 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4145 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004146 return true;
4147 }
4148 }
4149 return false;
4150}
4151
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004152static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4153 ArrayRef<OMPClause *> Clauses,
4154 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4155 bool ErrorFound = false;
4156 unsigned NamedModifiersNumber = 0;
4157 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
4158 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004159 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004160 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004161 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4162 // At most one if clause without a directive-name-modifier can appear on
4163 // the directive.
4164 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4165 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004166 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004167 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4168 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4169 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004170 } else if (CurNM != OMPD_unknown) {
4171 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004172 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004173 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004174 FoundNameModifiers[CurNM] = IC;
4175 if (CurNM == OMPD_unknown)
4176 continue;
4177 // Check if the specified name modifier is allowed for the current
4178 // directive.
4179 // At most one if clause with the particular directive-name-modifier can
4180 // appear on the directive.
4181 bool MatchFound = false;
4182 for (auto NM : AllowedNameModifiers) {
4183 if (CurNM == NM) {
4184 MatchFound = true;
4185 break;
4186 }
4187 }
4188 if (!MatchFound) {
4189 S.Diag(IC->getNameModifierLoc(),
4190 diag::err_omp_wrong_if_directive_name_modifier)
4191 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4192 ErrorFound = true;
4193 }
4194 }
4195 }
4196 // If any if clause on the directive includes a directive-name-modifier then
4197 // all if clauses on the directive must include a directive-name-modifier.
4198 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4199 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004200 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004201 diag::err_omp_no_more_if_clause);
4202 } else {
4203 std::string Values;
4204 std::string Sep(", ");
4205 unsigned AllowedCnt = 0;
4206 unsigned TotalAllowedNum =
4207 AllowedNameModifiers.size() - NamedModifiersNumber;
4208 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4209 ++Cnt) {
4210 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4211 if (!FoundNameModifiers[NM]) {
4212 Values += "'";
4213 Values += getOpenMPDirectiveName(NM);
4214 Values += "'";
4215 if (AllowedCnt + 2 == TotalAllowedNum)
4216 Values += " or ";
4217 else if (AllowedCnt + 1 != TotalAllowedNum)
4218 Values += Sep;
4219 ++AllowedCnt;
4220 }
4221 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004222 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004223 diag::err_omp_unnamed_if_clause)
4224 << (TotalAllowedNum > 1) << Values;
4225 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004226 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004227 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4228 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004229 ErrorFound = true;
4230 }
4231 return ErrorFound;
4232}
4233
Alexey Bataeve106f252019-04-01 14:25:31 +00004234static std::pair<ValueDecl *, bool>
4235getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4236 SourceRange &ERange, bool AllowArraySection = false) {
4237 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4238 RefExpr->containsUnexpandedParameterPack())
4239 return std::make_pair(nullptr, true);
4240
4241 // OpenMP [3.1, C/C++]
4242 // A list item is a variable name.
4243 // OpenMP [2.9.3.3, Restrictions, p.1]
4244 // A variable that is part of another variable (as an array or
4245 // structure element) cannot appear in a private clause.
4246 RefExpr = RefExpr->IgnoreParens();
4247 enum {
4248 NoArrayExpr = -1,
4249 ArraySubscript = 0,
4250 OMPArraySection = 1
4251 } IsArrayExpr = NoArrayExpr;
4252 if (AllowArraySection) {
4253 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4254 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4255 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4256 Base = TempASE->getBase()->IgnoreParenImpCasts();
4257 RefExpr = Base;
4258 IsArrayExpr = ArraySubscript;
4259 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4260 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4261 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4262 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4263 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4264 Base = TempASE->getBase()->IgnoreParenImpCasts();
4265 RefExpr = Base;
4266 IsArrayExpr = OMPArraySection;
4267 }
4268 }
4269 ELoc = RefExpr->getExprLoc();
4270 ERange = RefExpr->getSourceRange();
4271 RefExpr = RefExpr->IgnoreParenImpCasts();
4272 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4273 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4274 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4275 (S.getCurrentThisType().isNull() || !ME ||
4276 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4277 !isa<FieldDecl>(ME->getMemberDecl()))) {
4278 if (IsArrayExpr != NoArrayExpr) {
4279 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4280 << ERange;
4281 } else {
4282 S.Diag(ELoc,
4283 AllowArraySection
4284 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4285 : diag::err_omp_expected_var_name_member_expr)
4286 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4287 }
4288 return std::make_pair(nullptr, false);
4289 }
4290 return std::make_pair(
4291 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4292}
4293
4294static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004295 ArrayRef<OMPClause *> Clauses) {
4296 assert(!S.CurContext->isDependentContext() &&
4297 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004298 auto AllocateRange =
4299 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004300 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4301 DeclToCopy;
4302 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4303 return isOpenMPPrivate(C->getClauseKind());
4304 });
4305 for (OMPClause *Cl : PrivateRange) {
4306 MutableArrayRef<Expr *>::iterator I, It, Et;
4307 if (Cl->getClauseKind() == OMPC_private) {
4308 auto *PC = cast<OMPPrivateClause>(Cl);
4309 I = PC->private_copies().begin();
4310 It = PC->varlist_begin();
4311 Et = PC->varlist_end();
4312 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4313 auto *PC = cast<OMPFirstprivateClause>(Cl);
4314 I = PC->private_copies().begin();
4315 It = PC->varlist_begin();
4316 Et = PC->varlist_end();
4317 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4318 auto *PC = cast<OMPLastprivateClause>(Cl);
4319 I = PC->private_copies().begin();
4320 It = PC->varlist_begin();
4321 Et = PC->varlist_end();
4322 } else if (Cl->getClauseKind() == OMPC_linear) {
4323 auto *PC = cast<OMPLinearClause>(Cl);
4324 I = PC->privates().begin();
4325 It = PC->varlist_begin();
4326 Et = PC->varlist_end();
4327 } else if (Cl->getClauseKind() == OMPC_reduction) {
4328 auto *PC = cast<OMPReductionClause>(Cl);
4329 I = PC->privates().begin();
4330 It = PC->varlist_begin();
4331 Et = PC->varlist_end();
4332 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4333 auto *PC = cast<OMPTaskReductionClause>(Cl);
4334 I = PC->privates().begin();
4335 It = PC->varlist_begin();
4336 Et = PC->varlist_end();
4337 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4338 auto *PC = cast<OMPInReductionClause>(Cl);
4339 I = PC->privates().begin();
4340 It = PC->varlist_begin();
4341 Et = PC->varlist_end();
4342 } else {
4343 llvm_unreachable("Expected private clause.");
4344 }
4345 for (Expr *E : llvm::make_range(It, Et)) {
4346 if (!*I) {
4347 ++I;
4348 continue;
4349 }
4350 SourceLocation ELoc;
4351 SourceRange ERange;
4352 Expr *SimpleRefExpr = E;
4353 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4354 /*AllowArraySection=*/true);
4355 DeclToCopy.try_emplace(Res.first,
4356 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4357 ++I;
4358 }
4359 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004360 for (OMPClause *C : AllocateRange) {
4361 auto *AC = cast<OMPAllocateClause>(C);
4362 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4363 getAllocatorKind(S, Stack, AC->getAllocator());
4364 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4365 // For task, taskloop or target directives, allocation requests to memory
4366 // allocators with the trait access set to thread result in unspecified
4367 // behavior.
4368 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4369 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4370 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4371 S.Diag(AC->getAllocator()->getExprLoc(),
4372 diag::warn_omp_allocate_thread_on_task_target_directive)
4373 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004374 }
4375 for (Expr *E : AC->varlists()) {
4376 SourceLocation ELoc;
4377 SourceRange ERange;
4378 Expr *SimpleRefExpr = E;
4379 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4380 ValueDecl *VD = Res.first;
4381 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4382 if (!isOpenMPPrivate(Data.CKind)) {
4383 S.Diag(E->getExprLoc(),
4384 diag::err_omp_expected_private_copy_for_allocate);
4385 continue;
4386 }
4387 VarDecl *PrivateVD = DeclToCopy[VD];
4388 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4389 AllocatorKind, AC->getAllocator()))
4390 continue;
4391 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4392 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004393 }
4394 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004395}
4396
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004397StmtResult Sema::ActOnOpenMPExecutableDirective(
4398 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4399 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4400 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004401 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004402 // First check CancelRegion which is then used in checkNestingOfRegions.
4403 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4404 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004405 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004406 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004407
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004408 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004409 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004410 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004411 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004412 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004413 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4414
4415 // Check default data sharing attributes for referenced variables.
4416 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004417 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4418 Stmt *S = AStmt;
4419 while (--ThisCaptureLevel >= 0)
4420 S = cast<CapturedStmt>(S)->getCapturedStmt();
4421 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004422 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4423 !isOpenMPTaskingDirective(Kind)) {
4424 // Visit subcaptures to generate implicit clauses for captured vars.
4425 auto *CS = cast<CapturedStmt>(AStmt);
4426 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4427 getOpenMPCaptureRegions(CaptureRegions, Kind);
4428 // Ignore outer tasking regions for target directives.
4429 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4430 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4431 DSAChecker.visitSubCaptures(CS);
4432 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004433 if (DSAChecker.isErrorFound())
4434 return StmtError();
4435 // Generate list of implicitly defined firstprivate variables.
4436 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004437
Alexey Bataev88202be2017-07-27 13:20:36 +00004438 SmallVector<Expr *, 4> ImplicitFirstprivates(
4439 DSAChecker.getImplicitFirstprivate().begin(),
4440 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004441 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4442 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4443 ArrayRef<Expr *> ImplicitMap =
4444 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4445 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4446 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004447 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004448 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004449 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004450 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004451 if (E)
4452 ImplicitFirstprivates.emplace_back(E);
4453 }
4454 }
4455 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004456 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004457 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4458 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004459 ClausesWithImplicit.push_back(Implicit);
4460 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004461 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004462 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004463 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004464 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004465 }
cchene06f3e02019-11-15 13:02:06 -05004466 int ClauseKindCnt = -1;
4467 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4468 ++ClauseKindCnt;
4469 if (ImplicitMap.empty())
4470 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004471 CXXScopeSpec MapperIdScopeSpec;
4472 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004473 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004474 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004475 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4476 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4477 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004478 ClausesWithImplicit.emplace_back(Implicit);
4479 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004480 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004481 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004482 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004483 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004484 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004485 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004486
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004487 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004488 switch (Kind) {
4489 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004490 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4491 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004492 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004493 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004494 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004495 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4496 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004497 if (LangOpts.OpenMP >= 50)
4498 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004499 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004500 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004501 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4502 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004503 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004504 case OMPD_for_simd:
4505 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4506 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004507 if (LangOpts.OpenMP >= 50)
4508 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004509 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004510 case OMPD_sections:
4511 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4512 EndLoc);
4513 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004514 case OMPD_section:
4515 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004516 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004517 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4518 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004519 case OMPD_single:
4520 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4521 EndLoc);
4522 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004523 case OMPD_master:
4524 assert(ClausesWithImplicit.empty() &&
4525 "No clauses are allowed for 'omp master' directive");
4526 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4527 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004528 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004529 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4530 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004531 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004532 case OMPD_parallel_for:
4533 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4534 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004535 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004536 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004537 case OMPD_parallel_for_simd:
4538 Res = ActOnOpenMPParallelForSimdDirective(
4539 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004540 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004541 if (LangOpts.OpenMP >= 50)
4542 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004543 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004544 case OMPD_parallel_sections:
4545 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4546 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004547 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004548 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004549 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004550 Res =
4551 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004552 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004553 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004554 case OMPD_taskyield:
4555 assert(ClausesWithImplicit.empty() &&
4556 "No clauses are allowed for 'omp taskyield' directive");
4557 assert(AStmt == nullptr &&
4558 "No associated statement allowed for 'omp taskyield' directive");
4559 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4560 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004561 case OMPD_barrier:
4562 assert(ClausesWithImplicit.empty() &&
4563 "No clauses are allowed for 'omp barrier' directive");
4564 assert(AStmt == nullptr &&
4565 "No associated statement allowed for 'omp barrier' directive");
4566 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4567 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004568 case OMPD_taskwait:
4569 assert(ClausesWithImplicit.empty() &&
4570 "No clauses are allowed for 'omp taskwait' directive");
4571 assert(AStmt == nullptr &&
4572 "No associated statement allowed for 'omp taskwait' directive");
4573 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4574 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004575 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004576 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4577 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004578 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004579 case OMPD_flush:
4580 assert(AStmt == nullptr &&
4581 "No associated statement allowed for 'omp flush' directive");
4582 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4583 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004584 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004585 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4586 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004587 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004588 case OMPD_atomic:
4589 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4590 EndLoc);
4591 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004592 case OMPD_teams:
4593 Res =
4594 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4595 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004596 case OMPD_target:
4597 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4598 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004599 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004600 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004601 case OMPD_target_parallel:
4602 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4603 StartLoc, EndLoc);
4604 AllowedNameModifiers.push_back(OMPD_target);
4605 AllowedNameModifiers.push_back(OMPD_parallel);
4606 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004607 case OMPD_target_parallel_for:
4608 Res = ActOnOpenMPTargetParallelForDirective(
4609 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4610 AllowedNameModifiers.push_back(OMPD_target);
4611 AllowedNameModifiers.push_back(OMPD_parallel);
4612 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004613 case OMPD_cancellation_point:
4614 assert(ClausesWithImplicit.empty() &&
4615 "No clauses are allowed for 'omp cancellation point' directive");
4616 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4617 "cancellation point' directive");
4618 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4619 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004620 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004621 assert(AStmt == nullptr &&
4622 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004623 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4624 CancelRegion);
4625 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004626 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004627 case OMPD_target_data:
4628 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4629 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004630 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004631 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004632 case OMPD_target_enter_data:
4633 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004634 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004635 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4636 break;
Samuel Antao72590762016-01-19 20:04:50 +00004637 case OMPD_target_exit_data:
4638 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004639 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004640 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4641 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004642 case OMPD_taskloop:
4643 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4644 EndLoc, VarsWithInheritedDSA);
4645 AllowedNameModifiers.push_back(OMPD_taskloop);
4646 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004647 case OMPD_taskloop_simd:
4648 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4649 EndLoc, VarsWithInheritedDSA);
4650 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004651 if (LangOpts.OpenMP >= 50)
4652 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004653 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004654 case OMPD_master_taskloop:
4655 Res = ActOnOpenMPMasterTaskLoopDirective(
4656 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4657 AllowedNameModifiers.push_back(OMPD_taskloop);
4658 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004659 case OMPD_master_taskloop_simd:
4660 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4661 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4662 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004663 if (LangOpts.OpenMP >= 50)
4664 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004665 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004666 case OMPD_parallel_master_taskloop:
4667 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4668 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4669 AllowedNameModifiers.push_back(OMPD_taskloop);
4670 AllowedNameModifiers.push_back(OMPD_parallel);
4671 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004672 case OMPD_parallel_master_taskloop_simd:
4673 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4674 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4675 AllowedNameModifiers.push_back(OMPD_taskloop);
4676 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004677 if (LangOpts.OpenMP >= 50)
4678 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004679 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004680 case OMPD_distribute:
4681 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4682 EndLoc, VarsWithInheritedDSA);
4683 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004684 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004685 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4686 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004687 AllowedNameModifiers.push_back(OMPD_target_update);
4688 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004689 case OMPD_distribute_parallel_for:
4690 Res = ActOnOpenMPDistributeParallelForDirective(
4691 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4692 AllowedNameModifiers.push_back(OMPD_parallel);
4693 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004694 case OMPD_distribute_parallel_for_simd:
4695 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4696 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4697 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004698 if (LangOpts.OpenMP >= 50)
4699 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004700 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004701 case OMPD_distribute_simd:
4702 Res = ActOnOpenMPDistributeSimdDirective(
4703 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4704 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004705 case OMPD_target_parallel_for_simd:
4706 Res = ActOnOpenMPTargetParallelForSimdDirective(
4707 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4708 AllowedNameModifiers.push_back(OMPD_target);
4709 AllowedNameModifiers.push_back(OMPD_parallel);
4710 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004711 case OMPD_target_simd:
4712 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4713 EndLoc, VarsWithInheritedDSA);
4714 AllowedNameModifiers.push_back(OMPD_target);
4715 break;
Kelvin Li02532872016-08-05 14:37:37 +00004716 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004717 Res = ActOnOpenMPTeamsDistributeDirective(
4718 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004719 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004720 case OMPD_teams_distribute_simd:
4721 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4722 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4723 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004724 case OMPD_teams_distribute_parallel_for_simd:
4725 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4726 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4727 AllowedNameModifiers.push_back(OMPD_parallel);
4728 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004729 case OMPD_teams_distribute_parallel_for:
4730 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4731 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4732 AllowedNameModifiers.push_back(OMPD_parallel);
4733 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004734 case OMPD_target_teams:
4735 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4736 EndLoc);
4737 AllowedNameModifiers.push_back(OMPD_target);
4738 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004739 case OMPD_target_teams_distribute:
4740 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4741 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4742 AllowedNameModifiers.push_back(OMPD_target);
4743 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004744 case OMPD_target_teams_distribute_parallel_for:
4745 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4746 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4747 AllowedNameModifiers.push_back(OMPD_target);
4748 AllowedNameModifiers.push_back(OMPD_parallel);
4749 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004750 case OMPD_target_teams_distribute_parallel_for_simd:
4751 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4752 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4753 AllowedNameModifiers.push_back(OMPD_target);
4754 AllowedNameModifiers.push_back(OMPD_parallel);
4755 break;
Kelvin Lida681182017-01-10 18:08:18 +00004756 case OMPD_target_teams_distribute_simd:
4757 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4758 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4759 AllowedNameModifiers.push_back(OMPD_target);
4760 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004761 case OMPD_declare_target:
4762 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004763 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004764 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004765 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004766 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004767 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004768 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004769 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004770 llvm_unreachable("OpenMP Directive is not allowed");
4771 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004772 llvm_unreachable("Unknown OpenMP directive");
4773 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004774
Roman Lebedevb5700602019-03-20 16:32:36 +00004775 ErrorFound = Res.isInvalid() || ErrorFound;
4776
Alexey Bataev412254a2019-05-09 18:44:53 +00004777 // Check variables in the clauses if default(none) was specified.
4778 if (DSAStack->getDefaultDSA() == DSA_none) {
4779 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4780 for (OMPClause *C : Clauses) {
4781 switch (C->getClauseKind()) {
4782 case OMPC_num_threads:
4783 case OMPC_dist_schedule:
4784 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004785 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004786 break;
4787 continue;
4788 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004789 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004790 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4791 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004792 if (isOpenMPParallelDirective(Kind) &&
4793 isOpenMPTaskLoopDirective(Kind) &&
4794 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4795 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004796 continue;
4797 case OMPC_schedule:
4798 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004799 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004800 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004801 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004802 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004803 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004804 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004805 break;
4806 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004807 case OMPC_ordered:
4808 case OMPC_device:
4809 case OMPC_num_teams:
4810 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004811 case OMPC_hint:
4812 case OMPC_collapse:
4813 case OMPC_safelen:
4814 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004815 case OMPC_default:
4816 case OMPC_proc_bind:
4817 case OMPC_private:
4818 case OMPC_firstprivate:
4819 case OMPC_lastprivate:
4820 case OMPC_shared:
4821 case OMPC_reduction:
4822 case OMPC_task_reduction:
4823 case OMPC_in_reduction:
4824 case OMPC_linear:
4825 case OMPC_aligned:
4826 case OMPC_copyin:
4827 case OMPC_copyprivate:
4828 case OMPC_nowait:
4829 case OMPC_untied:
4830 case OMPC_mergeable:
4831 case OMPC_allocate:
4832 case OMPC_read:
4833 case OMPC_write:
4834 case OMPC_update:
4835 case OMPC_capture:
4836 case OMPC_seq_cst:
4837 case OMPC_depend:
4838 case OMPC_threads:
4839 case OMPC_simd:
4840 case OMPC_map:
4841 case OMPC_nogroup:
4842 case OMPC_defaultmap:
4843 case OMPC_to:
4844 case OMPC_from:
4845 case OMPC_use_device_ptr:
4846 case OMPC_is_device_ptr:
4847 continue;
4848 case OMPC_allocator:
4849 case OMPC_flush:
4850 case OMPC_threadprivate:
4851 case OMPC_uniform:
4852 case OMPC_unknown:
4853 case OMPC_unified_address:
4854 case OMPC_unified_shared_memory:
4855 case OMPC_reverse_offload:
4856 case OMPC_dynamic_allocators:
4857 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004858 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004859 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004860 llvm_unreachable("Unexpected clause");
4861 }
4862 for (Stmt *CC : C->children()) {
4863 if (CC)
4864 DSAChecker.Visit(CC);
4865 }
4866 }
4867 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4868 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4869 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004870 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004871 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4872 continue;
4873 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004874 if (DSAStack->getDefaultDSA() == DSA_none) {
4875 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4876 << P.first << P.second->getSourceRange();
4877 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4878 } else if (getLangOpts().OpenMP >= 50) {
4879 Diag(P.second->getExprLoc(),
4880 diag::err_omp_defaultmap_no_attr_for_variable)
4881 << P.first << P.second->getSourceRange();
4882 Diag(DSAStack->getDefaultDSALocation(),
4883 diag::note_omp_defaultmap_attr_none);
4884 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00004885 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004886
4887 if (!AllowedNameModifiers.empty())
4888 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4889 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004890
Alexey Bataeved09d242014-05-28 05:53:51 +00004891 if (ErrorFound)
4892 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004893
4894 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4895 Res.getAs<OMPExecutableDirective>()
4896 ->getStructuredBlock()
4897 ->setIsOMPStructuredBlock(true);
4898 }
4899
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004900 if (!CurContext->isDependentContext() &&
4901 isOpenMPTargetExecutionDirective(Kind) &&
4902 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4903 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4904 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4905 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4906 // Register target to DSA Stack.
4907 DSAStack->addTargetDirLocation(StartLoc);
4908 }
4909
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004910 return Res;
4911}
4912
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004913Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4914 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004915 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004916 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4917 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004918 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004919 assert(Linears.size() == LinModifiers.size());
4920 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004921 if (!DG || DG.get().isNull())
4922 return DeclGroupPtrTy();
4923
Alexey Bataevd158cf62019-09-13 20:18:17 +00004924 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004925 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004926 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4927 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004928 return DG;
4929 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004930 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004931 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4932 ADecl = FTD->getTemplatedDecl();
4933
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004934 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4935 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004936 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004937 return DeclGroupPtrTy();
4938 }
4939
Alexey Bataev2af33e32016-04-07 12:45:37 +00004940 // OpenMP [2.8.2, declare simd construct, Description]
4941 // The parameter of the simdlen clause must be a constant positive integer
4942 // expression.
4943 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004944 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004945 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004946 // OpenMP [2.8.2, declare simd construct, Description]
4947 // The special this pointer can be used as if was one of the arguments to the
4948 // function in any of the linear, aligned, or uniform clauses.
4949 // The uniform clause declares one or more arguments to have an invariant
4950 // value for all concurrent invocations of the function in the execution of a
4951 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004952 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4953 const Expr *UniformedLinearThis = nullptr;
4954 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004955 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004956 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4957 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004958 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4959 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004960 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004961 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004962 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004963 }
4964 if (isa<CXXThisExpr>(E)) {
4965 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004966 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004967 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004968 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4969 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004970 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004971 // OpenMP [2.8.2, declare simd construct, Description]
4972 // The aligned clause declares that the object to which each list item points
4973 // is aligned to the number of bytes expressed in the optional parameter of
4974 // the aligned clause.
4975 // The special this pointer can be used as if was one of the arguments to the
4976 // function in any of the linear, aligned, or uniform clauses.
4977 // The type of list items appearing in the aligned clause must be array,
4978 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004979 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4980 const Expr *AlignedThis = nullptr;
4981 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004982 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004983 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4984 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4985 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004986 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4987 FD->getParamDecl(PVD->getFunctionScopeIndex())
4988 ->getCanonicalDecl() == CanonPVD) {
4989 // OpenMP [2.8.1, simd construct, Restrictions]
4990 // A list-item cannot appear in more than one aligned clause.
4991 if (AlignedArgs.count(CanonPVD) > 0) {
4992 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4993 << 1 << E->getSourceRange();
4994 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4995 diag::note_omp_explicit_dsa)
4996 << getOpenMPClauseName(OMPC_aligned);
4997 continue;
4998 }
4999 AlignedArgs[CanonPVD] = E;
5000 QualType QTy = PVD->getType()
5001 .getNonReferenceType()
5002 .getUnqualifiedType()
5003 .getCanonicalType();
5004 const Type *Ty = QTy.getTypePtrOrNull();
5005 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5006 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5007 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5008 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5009 }
5010 continue;
5011 }
5012 }
5013 if (isa<CXXThisExpr>(E)) {
5014 if (AlignedThis) {
5015 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
5016 << 2 << E->getSourceRange();
5017 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5018 << getOpenMPClauseName(OMPC_aligned);
5019 }
5020 AlignedThis = E;
5021 continue;
5022 }
5023 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5024 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5025 }
5026 // The optional parameter of the aligned clause, alignment, must be a constant
5027 // positive integer expression. If no optional parameter is specified,
5028 // implementation-defined default alignments for SIMD instructions on the
5029 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005030 SmallVector<const Expr *, 4> NewAligns;
5031 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005032 ExprResult Align;
5033 if (E)
5034 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5035 NewAligns.push_back(Align.get());
5036 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005037 // OpenMP [2.8.2, declare simd construct, Description]
5038 // The linear clause declares one or more list items to be private to a SIMD
5039 // lane and to have a linear relationship with respect to the iteration space
5040 // of a loop.
5041 // The special this pointer can be used as if was one of the arguments to the
5042 // function in any of the linear, aligned, or uniform clauses.
5043 // When a linear-step expression is specified in a linear clause it must be
5044 // either a constant integer expression or an integer-typed parameter that is
5045 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005046 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005047 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5048 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005049 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005050 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5051 ++MI;
5052 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005053 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5054 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5055 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005056 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5057 FD->getParamDecl(PVD->getFunctionScopeIndex())
5058 ->getCanonicalDecl() == CanonPVD) {
5059 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5060 // A list-item cannot appear in more than one linear clause.
5061 if (LinearArgs.count(CanonPVD) > 0) {
5062 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5063 << getOpenMPClauseName(OMPC_linear)
5064 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5065 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5066 diag::note_omp_explicit_dsa)
5067 << getOpenMPClauseName(OMPC_linear);
5068 continue;
5069 }
5070 // Each argument can appear in at most one uniform or linear clause.
5071 if (UniformedArgs.count(CanonPVD) > 0) {
5072 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5073 << getOpenMPClauseName(OMPC_linear)
5074 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5075 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5076 diag::note_omp_explicit_dsa)
5077 << getOpenMPClauseName(OMPC_uniform);
5078 continue;
5079 }
5080 LinearArgs[CanonPVD] = E;
5081 if (E->isValueDependent() || E->isTypeDependent() ||
5082 E->isInstantiationDependent() ||
5083 E->containsUnexpandedParameterPack())
5084 continue;
5085 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5086 PVD->getOriginalType());
5087 continue;
5088 }
5089 }
5090 if (isa<CXXThisExpr>(E)) {
5091 if (UniformedLinearThis) {
5092 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5093 << getOpenMPClauseName(OMPC_linear)
5094 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5095 << E->getSourceRange();
5096 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5097 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5098 : OMPC_linear);
5099 continue;
5100 }
5101 UniformedLinearThis = E;
5102 if (E->isValueDependent() || E->isTypeDependent() ||
5103 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5104 continue;
5105 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5106 E->getType());
5107 continue;
5108 }
5109 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5110 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5111 }
5112 Expr *Step = nullptr;
5113 Expr *NewStep = nullptr;
5114 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005115 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005116 // Skip the same step expression, it was checked already.
5117 if (Step == E || !E) {
5118 NewSteps.push_back(E ? NewStep : nullptr);
5119 continue;
5120 }
5121 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005122 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5123 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5124 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005125 if (UniformedArgs.count(CanonPVD) == 0) {
5126 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5127 << Step->getSourceRange();
5128 } else if (E->isValueDependent() || E->isTypeDependent() ||
5129 E->isInstantiationDependent() ||
5130 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005131 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005132 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005133 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005134 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5135 << Step->getSourceRange();
5136 }
5137 continue;
5138 }
5139 NewStep = Step;
5140 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5141 !Step->isInstantiationDependent() &&
5142 !Step->containsUnexpandedParameterPack()) {
5143 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5144 .get();
5145 if (NewStep)
5146 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5147 }
5148 NewSteps.push_back(NewStep);
5149 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005150 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5151 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005152 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005153 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5154 const_cast<Expr **>(Linears.data()), Linears.size(),
5155 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5156 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005157 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005158 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005159}
5160
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005161Optional<std::pair<FunctionDecl *, Expr *>>
5162Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5163 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005164 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005165 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005166
5167 const int VariantId = 1;
5168 // Must be applied only to single decl.
5169 if (!DG.get().isSingleDecl()) {
5170 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5171 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005172 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005173 }
5174 Decl *ADecl = DG.get().getSingleDecl();
5175 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5176 ADecl = FTD->getTemplatedDecl();
5177
5178 // Decl must be a function.
5179 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5180 if (!FD) {
5181 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5182 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005183 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005184 }
5185
5186 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5187 return FD->hasAttrs() &&
5188 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5189 FD->hasAttr<TargetAttr>());
5190 };
5191 // OpenMP is not compatible with CPU-specific attributes.
5192 if (HasMultiVersionAttributes(FD)) {
5193 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5194 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005195 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005196 }
5197
5198 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005199 if (FD->isUsed(false))
5200 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005201 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005202
5203 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005204 const FunctionDecl *Definition;
5205 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5206 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005207 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5208 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005209
5210 // The VariantRef must point to function.
5211 if (!VariantRef) {
5212 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005213 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005214 }
5215
5216 // Do not check templates, wait until instantiation.
5217 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5218 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005219 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5220 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005221
5222 // Convert VariantRef expression to the type of the original function to
5223 // resolve possible conflicts.
5224 ExprResult VariantRefCast;
5225 if (LangOpts.CPlusPlus) {
5226 QualType FnPtrType;
5227 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5228 if (Method && !Method->isStatic()) {
5229 const Type *ClassType =
5230 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5231 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5232 ExprResult ER;
5233 {
5234 // Build adrr_of unary op to correctly handle type checks for member
5235 // functions.
5236 Sema::TentativeAnalysisScope Trap(*this);
5237 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5238 VariantRef);
5239 }
5240 if (!ER.isUsable()) {
5241 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5242 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005243 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005244 }
5245 VariantRef = ER.get();
5246 } else {
5247 FnPtrType = Context.getPointerType(FD->getType());
5248 }
5249 ImplicitConversionSequence ICS =
5250 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5251 /*SuppressUserConversions=*/false,
5252 /*AllowExplicit=*/false,
5253 /*InOverloadResolution=*/false,
5254 /*CStyle=*/false,
5255 /*AllowObjCWritebackConversion=*/false);
5256 if (ICS.isFailure()) {
5257 Diag(VariantRef->getExprLoc(),
5258 diag::err_omp_declare_variant_incompat_types)
5259 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005260 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005261 }
5262 VariantRefCast = PerformImplicitConversion(
5263 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5264 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005265 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005266 // Drop previously built artificial addr_of unary op for member functions.
5267 if (Method && !Method->isStatic()) {
5268 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5269 if (auto *UO = dyn_cast<UnaryOperator>(
5270 PossibleAddrOfVariantRef->IgnoreImplicit()))
5271 VariantRefCast = UO->getSubExpr();
5272 }
5273 } else {
5274 VariantRefCast = VariantRef;
5275 }
5276
5277 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5278 if (!ER.isUsable() ||
5279 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5280 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5281 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005282 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005283 }
5284
5285 // The VariantRef must point to function.
5286 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5287 if (!DRE) {
5288 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5289 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005290 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005291 }
5292 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5293 if (!NewFD) {
5294 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5295 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005296 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005297 }
5298
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005299 // Check if variant function is not marked with declare variant directive.
5300 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5301 Diag(VariantRef->getExprLoc(),
5302 diag::warn_omp_declare_variant_marked_as_declare_variant)
5303 << VariantRef->getSourceRange();
5304 SourceRange SR =
5305 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5306 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005307 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005308 }
5309
Alexey Bataevd158cf62019-09-13 20:18:17 +00005310 enum DoesntSupport {
5311 VirtFuncs = 1,
5312 Constructors = 3,
5313 Destructors = 4,
5314 DeletedFuncs = 5,
5315 DefaultedFuncs = 6,
5316 ConstexprFuncs = 7,
5317 ConstevalFuncs = 8,
5318 };
5319 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5320 if (CXXFD->isVirtual()) {
5321 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5322 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005323 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005324 }
5325
5326 if (isa<CXXConstructorDecl>(FD)) {
5327 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5328 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005329 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005330 }
5331
5332 if (isa<CXXDestructorDecl>(FD)) {
5333 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5334 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005335 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005336 }
5337 }
5338
5339 if (FD->isDeleted()) {
5340 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5341 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005342 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005343 }
5344
5345 if (FD->isDefaulted()) {
5346 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5347 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005348 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005349 }
5350
5351 if (FD->isConstexpr()) {
5352 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5353 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005354 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005355 }
5356
5357 // Check general compatibility.
5358 if (areMultiversionVariantFunctionsCompatible(
5359 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5360 PartialDiagnosticAt(
5361 SR.getBegin(),
5362 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5363 PartialDiagnosticAt(
5364 VariantRef->getExprLoc(),
5365 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5366 PartialDiagnosticAt(VariantRef->getExprLoc(),
5367 PDiag(diag::err_omp_declare_variant_diff)
5368 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005369 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5370 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005371 return None;
5372 return std::make_pair(FD, cast<Expr>(DRE));
5373}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005374
Alexey Bataev9ff34742019-09-25 19:43:37 +00005375void Sema::ActOnOpenMPDeclareVariantDirective(
5376 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005377 ArrayRef<OMPCtxSelectorData> Data) {
5378 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005379 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005380 SmallVector<Expr *, 4> CtxScores;
5381 SmallVector<unsigned, 4> CtxSets;
5382 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005383 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005384 bool IsError = false;
5385 for (const OMPCtxSelectorData &D : Data) {
5386 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5387 OpenMPContextSelectorKind Ctx = D.Ctx;
5388 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5389 return;
5390 Expr *Score = nullptr;
5391 if (D.Score.isUsable()) {
5392 Score = D.Score.get();
5393 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5394 !Score->isInstantiationDependent() &&
5395 !Score->containsUnexpandedParameterPack()) {
5396 Score =
5397 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5398 .get();
5399 if (Score)
5400 Score = VerifyIntegerConstantExpression(Score).get();
5401 }
5402 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005403 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5404 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5405 // 2^(l+2), respectively, where l is the number of traits in the construct
5406 // set.
5407 // TODO: implement correct logic for isa and arch traits.
5408 // TODO: take the construct context set into account when it is
5409 // implemented.
5410 int L = 0; // Currently set the number of traits in construct set to 0,
5411 // since the construct trait set in not supported yet.
5412 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5413 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5414 else
5415 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005416 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005417 switch (Ctx) {
5418 case OMP_CTX_vendor:
5419 assert(CtxSet == OMP_CTX_SET_implementation &&
5420 "Expected implementation context selector set.");
5421 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005422 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005423 case OMP_CTX_kind:
5424 assert(CtxSet == OMP_CTX_SET_device &&
5425 "Expected device context selector set.");
5426 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005427 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005428 case OMP_CTX_unknown:
5429 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005430 }
5431 IsError = IsError || !Score;
5432 CtxSets.push_back(CtxSet);
5433 Ctxs.push_back(Ctx);
5434 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005435 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005436 if (!IsError) {
5437 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5438 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5439 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005440 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5441 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005442 FD->addAttr(NewAttr);
5443 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005444}
5445
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005446void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5447 FunctionDecl *Func,
5448 bool MightBeOdrUse) {
5449 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5450
5451 if (!Func->isDependentContext() && Func->hasAttrs()) {
5452 for (OMPDeclareVariantAttr *A :
5453 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5454 // TODO: add checks for active OpenMP context where possible.
5455 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005456 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005457 auto *F = cast<FunctionDecl>(DRE->getDecl());
5458 if (!F->isDefined() && F->isTemplateInstantiation())
5459 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5460 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5461 }
5462 }
5463}
5464
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005465StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5466 Stmt *AStmt,
5467 SourceLocation StartLoc,
5468 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005469 if (!AStmt)
5470 return StmtError();
5471
Alexey Bataeve3727102018-04-18 15:57:46 +00005472 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005473 // 1.2.2 OpenMP Language Terminology
5474 // Structured block - An executable statement with a single entry at the
5475 // top and a single exit at the bottom.
5476 // The point of exit cannot be a branch out of the structured block.
5477 // longjmp() and throw() must not violate the entry/exit criteria.
5478 CS->getCapturedDecl()->setNothrow();
5479
Reid Kleckner87a31802018-03-12 21:43:02 +00005480 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005481
Alexey Bataev25e5b442015-09-15 12:52:43 +00005482 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5483 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005484}
5485
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005486namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005487/// Iteration space of a single for loop.
5488struct LoopIterationSpace final {
5489 /// True if the condition operator is the strict compare operator (<, > or
5490 /// !=).
5491 bool IsStrictCompare = false;
5492 /// Condition of the loop.
5493 Expr *PreCond = nullptr;
5494 /// This expression calculates the number of iterations in the loop.
5495 /// It is always possible to calculate it before starting the loop.
5496 Expr *NumIterations = nullptr;
5497 /// The loop counter variable.
5498 Expr *CounterVar = nullptr;
5499 /// Private loop counter variable.
5500 Expr *PrivateCounterVar = nullptr;
5501 /// This is initializer for the initial value of #CounterVar.
5502 Expr *CounterInit = nullptr;
5503 /// This is step for the #CounterVar used to generate its update:
5504 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5505 Expr *CounterStep = nullptr;
5506 /// Should step be subtracted?
5507 bool Subtract = false;
5508 /// Source range of the loop init.
5509 SourceRange InitSrcRange;
5510 /// Source range of the loop condition.
5511 SourceRange CondSrcRange;
5512 /// Source range of the loop increment.
5513 SourceRange IncSrcRange;
5514 /// Minimum value that can have the loop control variable. Used to support
5515 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5516 /// since only such variables can be used in non-loop invariant expressions.
5517 Expr *MinValue = nullptr;
5518 /// Maximum value that can have the loop control variable. Used to support
5519 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5520 /// since only such variables can be used in non-loop invariant expressions.
5521 Expr *MaxValue = nullptr;
5522 /// true, if the lower bound depends on the outer loop control var.
5523 bool IsNonRectangularLB = false;
5524 /// true, if the upper bound depends on the outer loop control var.
5525 bool IsNonRectangularUB = false;
5526 /// Index of the loop this loop depends on and forms non-rectangular loop
5527 /// nest.
5528 unsigned LoopDependentIdx = 0;
5529 /// Final condition for the non-rectangular loop nest support. It is used to
5530 /// check that the number of iterations for this particular counter must be
5531 /// finished.
5532 Expr *FinalCondition = nullptr;
5533};
5534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005535/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005536/// extracting iteration space of each loop in the loop nest, that will be used
5537/// for IR generation.
5538class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005539 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005540 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005541 /// Data-sharing stack.
5542 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005543 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005544 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005545 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005546 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005547 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005548 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005550 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005551 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005552 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005553 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005554 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005555 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005556 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005557 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005558 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005559 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005560 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005561 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005562 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005563 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005564 /// Var < UB
5565 /// Var <= UB
5566 /// UB > Var
5567 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005568 /// This will have no value when the condition is !=
5569 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005570 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005571 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005572 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005573 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005574 /// The outer loop counter this loop depends on (if any).
5575 const ValueDecl *DepDecl = nullptr;
5576 /// Contains number of loop (starts from 1) on which loop counter init
5577 /// expression of this loop depends on.
5578 Optional<unsigned> InitDependOnLC;
5579 /// Contains number of loop (starts from 1) on which loop counter condition
5580 /// expression of this loop depends on.
5581 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005582 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005583 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005584 /// Original condition required for checking of the exit condition for
5585 /// non-rectangular loop.
5586 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005587
5588public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005589 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5590 SourceLocation DefaultLoc)
5591 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5592 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005593 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005594 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005595 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005596 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005597 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005598 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005599 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005600 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005601 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005602 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005603 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005604 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005605 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005607 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005608 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005609 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005610 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005611 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005612 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005613 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005614 /// True, if the compare operator is strict (<, > or !=).
5615 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005616 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005617 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005618 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005619 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005620 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005621 Expr *
5622 buildPreCond(Scope *S, Expr *Cond,
5623 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005624 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005625 DeclRefExpr *
5626 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5627 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005628 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005629 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005630 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005631 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005632 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005633 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005634 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005635 /// Build loop data with counter value for depend clauses in ordered
5636 /// directives.
5637 Expr *
5638 buildOrderedLoopData(Scope *S, Expr *Counter,
5639 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5640 SourceLocation Loc, Expr *Inc = nullptr,
5641 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005642 /// Builds the minimum value for the loop counter.
5643 std::pair<Expr *, Expr *> buildMinMaxValues(
5644 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5645 /// Builds final condition for the non-rectangular loops.
5646 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005647 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005648 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005649 /// Returns true if the initializer forms non-rectangular loop.
5650 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5651 /// Returns true if the condition forms non-rectangular loop.
5652 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5653 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5654 unsigned getLoopDependentIdx() const {
5655 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5656 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005657
5658private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005659 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005660 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005661 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005662 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005663 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5664 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005665 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005666 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5667 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005669 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005670};
5671
Alexey Bataeve3727102018-04-18 15:57:46 +00005672bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005673 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005674 assert(!LB && !UB && !Step);
5675 return false;
5676 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005677 return LCDecl->getType()->isDependentType() ||
5678 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5679 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005680}
5681
Alexey Bataeve3727102018-04-18 15:57:46 +00005682bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005683 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005684 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005685 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005686 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005687 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005688 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005689 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005690 LCDecl = getCanonicalDecl(NewLCDecl);
5691 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005692 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5693 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005694 if ((Ctor->isCopyOrMoveConstructor() ||
5695 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5696 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005697 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005698 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005699 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005700 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005701 return false;
5702}
5703
Alexey Bataev316ccf62019-01-29 18:51:58 +00005704bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5705 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005706 bool StrictOp, SourceRange SR,
5707 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005708 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005709 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5710 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005711 if (!NewUB)
5712 return true;
5713 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005714 if (LessOp)
5715 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005716 TestIsStrictOp = StrictOp;
5717 ConditionSrcRange = SR;
5718 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005719 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005720 return false;
5721}
5722
Alexey Bataeve3727102018-04-18 15:57:46 +00005723bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005724 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005725 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005726 if (!NewStep)
5727 return true;
5728 if (!NewStep->isValueDependent()) {
5729 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005730 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005731 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5732 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005733 if (Val.isInvalid())
5734 return true;
5735 NewStep = Val.get();
5736
5737 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5738 // If test-expr is of form var relational-op b and relational-op is < or
5739 // <= then incr-expr must cause var to increase on each iteration of the
5740 // loop. If test-expr is of form var relational-op b and relational-op is
5741 // > or >= then incr-expr must cause var to decrease on each iteration of
5742 // the loop.
5743 // If test-expr is of form b relational-op var and relational-op is < or
5744 // <= then incr-expr must cause var to decrease on each iteration of the
5745 // loop. If test-expr is of form b relational-op var and relational-op is
5746 // > or >= then incr-expr must cause var to increase on each iteration of
5747 // the loop.
5748 llvm::APSInt Result;
5749 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5750 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5751 bool IsConstNeg =
5752 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005753 bool IsConstPos =
5754 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005755 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005756
5757 // != with increment is treated as <; != with decrement is treated as >
5758 if (!TestIsLessOp.hasValue())
5759 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005760 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005761 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005762 (IsConstNeg || (IsUnsigned && Subtract)) :
5763 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005764 SemaRef.Diag(NewStep->getExprLoc(),
5765 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005766 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005767 SemaRef.Diag(ConditionLoc,
5768 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005769 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005770 return true;
5771 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005772 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005773 NewStep =
5774 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5775 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005776 Subtract = !Subtract;
5777 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005778 }
5779
5780 Step = NewStep;
5781 SubtractStep = Subtract;
5782 return false;
5783}
5784
Alexey Bataev622af1d2019-04-24 19:58:30 +00005785namespace {
5786/// Checker for the non-rectangular loops. Checks if the initializer or
5787/// condition expression references loop counter variable.
5788class LoopCounterRefChecker final
5789 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5790 Sema &SemaRef;
5791 DSAStackTy &Stack;
5792 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005793 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005794 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005795 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005796 unsigned BaseLoopId = 0;
5797 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5798 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5799 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5800 << (IsInitializer ? 0 : 1);
5801 return false;
5802 }
5803 const auto &&Data = Stack.isLoopControlVariable(VD);
5804 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5805 // The type of the loop iterator on which we depend may not have a random
5806 // access iterator type.
5807 if (Data.first && VD->getType()->isRecordType()) {
5808 SmallString<128> Name;
5809 llvm::raw_svector_ostream OS(Name);
5810 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5811 /*Qualified=*/true);
5812 SemaRef.Diag(E->getExprLoc(),
5813 diag::err_omp_wrong_dependency_iterator_type)
5814 << OS.str();
5815 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5816 return false;
5817 }
5818 if (Data.first &&
5819 (DepDecl || (PrevDepDecl &&
5820 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5821 if (!DepDecl && PrevDepDecl)
5822 DepDecl = PrevDepDecl;
5823 SmallString<128> Name;
5824 llvm::raw_svector_ostream OS(Name);
5825 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5826 /*Qualified=*/true);
5827 SemaRef.Diag(E->getExprLoc(),
5828 diag::err_omp_invariant_or_linear_dependency)
5829 << OS.str();
5830 return false;
5831 }
5832 if (Data.first) {
5833 DepDecl = VD;
5834 BaseLoopId = Data.first;
5835 }
5836 return Data.first;
5837 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005838
5839public:
5840 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5841 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005842 if (isa<VarDecl>(VD))
5843 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005844 return false;
5845 }
5846 bool VisitMemberExpr(const MemberExpr *E) {
5847 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5848 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005849 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5850 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005851 }
5852 return false;
5853 }
5854 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005855 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005856 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005857 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005858 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005859 }
5860 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005861 const ValueDecl *CurLCDecl, bool IsInitializer,
5862 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005863 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005864 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5865 unsigned getBaseLoopId() const {
5866 assert(CurLCDecl && "Expected loop dependency.");
5867 return BaseLoopId;
5868 }
5869 const ValueDecl *getDepDecl() const {
5870 assert(CurLCDecl && "Expected loop dependency.");
5871 return DepDecl;
5872 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005873};
5874} // namespace
5875
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005876Optional<unsigned>
5877OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5878 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005879 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005880 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5881 DepDecl);
5882 if (LoopStmtChecker.Visit(S)) {
5883 DepDecl = LoopStmtChecker.getDepDecl();
5884 return LoopStmtChecker.getBaseLoopId();
5885 }
5886 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005887}
5888
Alexey Bataeve3727102018-04-18 15:57:46 +00005889bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005890 // Check init-expr for canonical loop form and save loop counter
5891 // variable - #Var and its initialization value - #LB.
5892 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5893 // var = lb
5894 // integer-type var = lb
5895 // random-access-iterator-type var = lb
5896 // pointer-type var = lb
5897 //
5898 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005899 if (EmitDiags) {
5900 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5901 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005902 return true;
5903 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005904 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5905 if (!ExprTemp->cleanupsHaveSideEffects())
5906 S = ExprTemp->getSubExpr();
5907
Alexander Musmana5f070a2014-10-01 06:03:56 +00005908 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005909 if (Expr *E = dyn_cast<Expr>(S))
5910 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005911 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005912 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005913 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005914 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5915 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5916 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005917 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5918 EmitDiags);
5919 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005920 }
5921 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5922 if (ME->isArrow() &&
5923 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005924 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5925 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005926 }
5927 }
David Majnemer9d168222016-08-05 17:44:54 +00005928 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005929 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005930 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005931 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005932 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005933 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005934 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005935 diag::ext_omp_loop_not_canonical_init)
5936 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005937 return setLCDeclAndLB(
5938 Var,
5939 buildDeclRefExpr(SemaRef, Var,
5940 Var->getType().getNonReferenceType(),
5941 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005942 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005943 }
5944 }
5945 }
David Majnemer9d168222016-08-05 17:44:54 +00005946 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005947 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005948 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005949 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005950 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5951 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005952 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5953 EmitDiags);
5954 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005955 }
5956 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5957 if (ME->isArrow() &&
5958 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005959 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5960 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005961 }
5962 }
5963 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005964
Alexey Bataeve3727102018-04-18 15:57:46 +00005965 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005966 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005967 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005968 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005969 << S->getSourceRange();
5970 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005971 return true;
5972}
5973
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005974/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005975/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005976static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005977 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005978 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005979 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005980 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005981 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005982 if ((Ctor->isCopyOrMoveConstructor() ||
5983 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5984 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005985 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005986 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5987 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005988 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005989 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005990 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005991 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5992 return getCanonicalDecl(ME->getMemberDecl());
5993 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005994}
5995
Alexey Bataeve3727102018-04-18 15:57:46 +00005996bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005997 // Check test-expr for canonical form, save upper-bound UB, flags for
5998 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005999 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006000 // var relational-op b
6001 // b relational-op var
6002 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006003 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006004 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006005 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6006 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006007 return true;
6008 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006009 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006010 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006011 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006012 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006013 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006014 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6015 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006016 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6017 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6018 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006019 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6020 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006021 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6022 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6023 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006024 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6025 return setUB(
6026 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6027 /*LessOp=*/llvm::None,
6028 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006029 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006030 if (CE->getNumArgs() == 2) {
6031 auto Op = CE->getOperator();
6032 switch (Op) {
6033 case OO_Greater:
6034 case OO_GreaterEqual:
6035 case OO_Less:
6036 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006037 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6038 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006039 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6040 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006041 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6042 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006043 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6044 CE->getOperatorLoc());
6045 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006046 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006047 if (IneqCondIsCanonical)
6048 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6049 : CE->getArg(0),
6050 /*LessOp=*/llvm::None,
6051 /*StrictOp=*/true, CE->getSourceRange(),
6052 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006053 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006054 default:
6055 break;
6056 }
6057 }
6058 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006059 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006060 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006061 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006062 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006063 return true;
6064}
6065
Alexey Bataeve3727102018-04-18 15:57:46 +00006066bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006067 // RHS of canonical loop form increment can be:
6068 // var + incr
6069 // incr + var
6070 // var - incr
6071 //
6072 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006073 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006074 if (BO->isAdditiveOp()) {
6075 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006076 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6077 return setStep(BO->getRHS(), !IsAdd);
6078 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6079 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006080 }
David Majnemer9d168222016-08-05 17:44:54 +00006081 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006082 bool IsAdd = CE->getOperator() == OO_Plus;
6083 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006084 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6085 return setStep(CE->getArg(1), !IsAdd);
6086 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6087 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006088 }
6089 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006090 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006091 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006092 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006093 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006094 return true;
6095}
6096
Alexey Bataeve3727102018-04-18 15:57:46 +00006097bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006098 // Check incr-expr for canonical loop form and return true if it
6099 // does not conform.
6100 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6101 // ++var
6102 // var++
6103 // --var
6104 // var--
6105 // var += incr
6106 // var -= incr
6107 // var = var + incr
6108 // var = incr + var
6109 // var = var - incr
6110 //
6111 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006112 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006113 return true;
6114 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006115 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6116 if (!ExprTemp->cleanupsHaveSideEffects())
6117 S = ExprTemp->getSubExpr();
6118
Alexander Musmana5f070a2014-10-01 06:03:56 +00006119 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006120 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006121 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006122 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006123 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6124 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006125 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006126 (UO->isDecrementOp() ? -1 : 1))
6127 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006128 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006129 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006130 switch (BO->getOpcode()) {
6131 case BO_AddAssign:
6132 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006133 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6134 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006135 break;
6136 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006137 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6138 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006139 break;
6140 default:
6141 break;
6142 }
David Majnemer9d168222016-08-05 17:44:54 +00006143 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006144 switch (CE->getOperator()) {
6145 case OO_PlusPlus:
6146 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006147 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6148 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006149 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006150 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006151 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6152 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006153 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006154 break;
6155 case OO_PlusEqual:
6156 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006157 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6158 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006159 break;
6160 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006161 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6162 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006163 break;
6164 default:
6165 break;
6166 }
6167 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006168 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006169 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006170 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006171 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006172 return true;
6173}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006174
Alexey Bataev5a3af132016-03-29 08:58:54 +00006175static ExprResult
6176tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006177 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006178 if (SemaRef.CurContext->isDependentContext())
6179 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006180 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6181 return SemaRef.PerformImplicitConversion(
6182 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6183 /*AllowExplicit=*/true);
6184 auto I = Captures.find(Capture);
6185 if (I != Captures.end())
6186 return buildCapture(SemaRef, Capture, I->second);
6187 DeclRefExpr *Ref = nullptr;
6188 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6189 Captures[Capture] = Ref;
6190 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006191}
6192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006193/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006194Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006195 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006196 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006197 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006198 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006199 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006200 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006201 Expr *LBVal = LB;
6202 Expr *UBVal = UB;
6203 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6204 // max(LB(MinVal), LB(MaxVal))
6205 if (InitDependOnLC) {
6206 const LoopIterationSpace &IS =
6207 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6208 InitDependOnLC.getValueOr(
6209 CondDependOnLC.getValueOr(0))];
6210 if (!IS.MinValue || !IS.MaxValue)
6211 return nullptr;
6212 // OuterVar = Min
6213 ExprResult MinValue =
6214 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6215 if (!MinValue.isUsable())
6216 return nullptr;
6217
6218 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6219 IS.CounterVar, MinValue.get());
6220 if (!LBMinVal.isUsable())
6221 return nullptr;
6222 // OuterVar = Min, LBVal
6223 LBMinVal =
6224 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6225 if (!LBMinVal.isUsable())
6226 return nullptr;
6227 // (OuterVar = Min, LBVal)
6228 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6229 if (!LBMinVal.isUsable())
6230 return nullptr;
6231
6232 // OuterVar = Max
6233 ExprResult MaxValue =
6234 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6235 if (!MaxValue.isUsable())
6236 return nullptr;
6237
6238 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6239 IS.CounterVar, MaxValue.get());
6240 if (!LBMaxVal.isUsable())
6241 return nullptr;
6242 // OuterVar = Max, LBVal
6243 LBMaxVal =
6244 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6245 if (!LBMaxVal.isUsable())
6246 return nullptr;
6247 // (OuterVar = Max, LBVal)
6248 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6249 if (!LBMaxVal.isUsable())
6250 return nullptr;
6251
6252 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6253 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6254 if (!LBMin || !LBMax)
6255 return nullptr;
6256 // LB(MinVal) < LB(MaxVal)
6257 ExprResult MinLessMaxRes =
6258 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6259 if (!MinLessMaxRes.isUsable())
6260 return nullptr;
6261 Expr *MinLessMax =
6262 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6263 if (!MinLessMax)
6264 return nullptr;
6265 if (TestIsLessOp.getValue()) {
6266 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6267 // LB(MaxVal))
6268 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6269 MinLessMax, LBMin, LBMax);
6270 if (!MinLB.isUsable())
6271 return nullptr;
6272 LBVal = MinLB.get();
6273 } else {
6274 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6275 // LB(MaxVal))
6276 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6277 MinLessMax, LBMax, LBMin);
6278 if (!MaxLB.isUsable())
6279 return nullptr;
6280 LBVal = MaxLB.get();
6281 }
6282 }
6283 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6284 // min(UB(MinVal), UB(MaxVal))
6285 if (CondDependOnLC) {
6286 const LoopIterationSpace &IS =
6287 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6288 InitDependOnLC.getValueOr(
6289 CondDependOnLC.getValueOr(0))];
6290 if (!IS.MinValue || !IS.MaxValue)
6291 return nullptr;
6292 // OuterVar = Min
6293 ExprResult MinValue =
6294 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6295 if (!MinValue.isUsable())
6296 return nullptr;
6297
6298 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6299 IS.CounterVar, MinValue.get());
6300 if (!UBMinVal.isUsable())
6301 return nullptr;
6302 // OuterVar = Min, UBVal
6303 UBMinVal =
6304 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6305 if (!UBMinVal.isUsable())
6306 return nullptr;
6307 // (OuterVar = Min, UBVal)
6308 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6309 if (!UBMinVal.isUsable())
6310 return nullptr;
6311
6312 // OuterVar = Max
6313 ExprResult MaxValue =
6314 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6315 if (!MaxValue.isUsable())
6316 return nullptr;
6317
6318 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6319 IS.CounterVar, MaxValue.get());
6320 if (!UBMaxVal.isUsable())
6321 return nullptr;
6322 // OuterVar = Max, UBVal
6323 UBMaxVal =
6324 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6325 if (!UBMaxVal.isUsable())
6326 return nullptr;
6327 // (OuterVar = Max, UBVal)
6328 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6329 if (!UBMaxVal.isUsable())
6330 return nullptr;
6331
6332 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6333 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6334 if (!UBMin || !UBMax)
6335 return nullptr;
6336 // UB(MinVal) > UB(MaxVal)
6337 ExprResult MinGreaterMaxRes =
6338 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6339 if (!MinGreaterMaxRes.isUsable())
6340 return nullptr;
6341 Expr *MinGreaterMax =
6342 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6343 if (!MinGreaterMax)
6344 return nullptr;
6345 if (TestIsLessOp.getValue()) {
6346 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6347 // UB(MaxVal))
6348 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6349 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6350 if (!MaxUB.isUsable())
6351 return nullptr;
6352 UBVal = MaxUB.get();
6353 } else {
6354 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6355 // UB(MaxVal))
6356 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6357 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6358 if (!MinUB.isUsable())
6359 return nullptr;
6360 UBVal = MinUB.get();
6361 }
6362 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006363 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006364 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6365 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006366 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6367 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006368 if (!Upper || !Lower)
6369 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006370
6371 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6372
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006373 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006374 // BuildBinOp already emitted error, this one is to point user to upper
6375 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006376 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006377 << Upper->getSourceRange() << Lower->getSourceRange();
6378 return nullptr;
6379 }
6380 }
6381
6382 if (!Diff.isUsable())
6383 return nullptr;
6384
6385 // Upper - Lower [- 1]
6386 if (TestIsStrictOp)
6387 Diff = SemaRef.BuildBinOp(
6388 S, DefaultLoc, BO_Sub, Diff.get(),
6389 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6390 if (!Diff.isUsable())
6391 return nullptr;
6392
6393 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006395 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006396 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006397 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006398 if (!Diff.isUsable())
6399 return nullptr;
6400
6401 // Parentheses (for dumping/debugging purposes only).
6402 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6403 if (!Diff.isUsable())
6404 return nullptr;
6405
6406 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006407 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006408 if (!Diff.isUsable())
6409 return nullptr;
6410
Alexander Musman174b3ca2014-10-06 11:16:29 +00006411 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006412 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006413 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006414 bool UseVarType = VarType->hasIntegerRepresentation() &&
6415 C.getTypeSize(Type) > C.getTypeSize(VarType);
6416 if (!Type->isIntegerType() || UseVarType) {
6417 unsigned NewSize =
6418 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6419 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6420 : Type->hasSignedIntegerRepresentation();
6421 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006422 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6423 Diff = SemaRef.PerformImplicitConversion(
6424 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6425 if (!Diff.isUsable())
6426 return nullptr;
6427 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006428 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006429 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006430 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6431 if (NewSize != C.getTypeSize(Type)) {
6432 if (NewSize < C.getTypeSize(Type)) {
6433 assert(NewSize == 64 && "incorrect loop var size");
6434 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6435 << InitSrcRange << ConditionSrcRange;
6436 }
6437 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006438 NewSize, Type->hasSignedIntegerRepresentation() ||
6439 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006440 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6441 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6442 Sema::AA_Converting, true);
6443 if (!Diff.isUsable())
6444 return nullptr;
6445 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006446 }
6447 }
6448
Alexander Musmana5f070a2014-10-01 06:03:56 +00006449 return Diff.get();
6450}
6451
Alexey Bataevf8be4762019-08-14 19:30:06 +00006452std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6453 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6454 // Do not build for iterators, they cannot be used in non-rectangular loop
6455 // nests.
6456 if (LCDecl->getType()->isRecordType())
6457 return std::make_pair(nullptr, nullptr);
6458 // If we subtract, the min is in the condition, otherwise the min is in the
6459 // init value.
6460 Expr *MinExpr = nullptr;
6461 Expr *MaxExpr = nullptr;
6462 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6463 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6464 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6465 : CondDependOnLC.hasValue();
6466 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6467 : InitDependOnLC.hasValue();
6468 Expr *Lower =
6469 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6470 Expr *Upper =
6471 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6472 if (!Upper || !Lower)
6473 return std::make_pair(nullptr, nullptr);
6474
6475 if (TestIsLessOp.getValue())
6476 MinExpr = Lower;
6477 else
6478 MaxExpr = Upper;
6479
6480 // Build minimum/maximum value based on number of iterations.
6481 ExprResult Diff;
6482 QualType VarType = LCDecl->getType().getNonReferenceType();
6483
6484 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6485 if (!Diff.isUsable())
6486 return std::make_pair(nullptr, nullptr);
6487
6488 // Upper - Lower [- 1]
6489 if (TestIsStrictOp)
6490 Diff = SemaRef.BuildBinOp(
6491 S, DefaultLoc, BO_Sub, Diff.get(),
6492 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6493 if (!Diff.isUsable())
6494 return std::make_pair(nullptr, nullptr);
6495
6496 // Upper - Lower [- 1] + Step
6497 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6498 if (!NewStep.isUsable())
6499 return std::make_pair(nullptr, nullptr);
6500
6501 // Parentheses (for dumping/debugging purposes only).
6502 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6503 if (!Diff.isUsable())
6504 return std::make_pair(nullptr, nullptr);
6505
6506 // (Upper - Lower [- 1]) / Step
6507 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6508 if (!Diff.isUsable())
6509 return std::make_pair(nullptr, nullptr);
6510
6511 // ((Upper - Lower [- 1]) / Step) * Step
6512 // Parentheses (for dumping/debugging purposes only).
6513 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6514 if (!Diff.isUsable())
6515 return std::make_pair(nullptr, nullptr);
6516
6517 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6518 if (!Diff.isUsable())
6519 return std::make_pair(nullptr, nullptr);
6520
6521 // Convert to the original type or ptrdiff_t, if original type is pointer.
6522 if (!VarType->isAnyPointerType() &&
6523 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6524 Diff = SemaRef.PerformImplicitConversion(
6525 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6526 } else if (VarType->isAnyPointerType() &&
6527 !SemaRef.Context.hasSameType(
6528 Diff.get()->getType(),
6529 SemaRef.Context.getUnsignedPointerDiffType())) {
6530 Diff = SemaRef.PerformImplicitConversion(
6531 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6532 Sema::AA_Converting, /*AllowExplicit=*/true);
6533 }
6534 if (!Diff.isUsable())
6535 return std::make_pair(nullptr, nullptr);
6536
6537 // Parentheses (for dumping/debugging purposes only).
6538 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6539 if (!Diff.isUsable())
6540 return std::make_pair(nullptr, nullptr);
6541
6542 if (TestIsLessOp.getValue()) {
6543 // MinExpr = Lower;
6544 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6545 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6546 if (!Diff.isUsable())
6547 return std::make_pair(nullptr, nullptr);
6548 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6549 if (!Diff.isUsable())
6550 return std::make_pair(nullptr, nullptr);
6551 MaxExpr = Diff.get();
6552 } else {
6553 // MaxExpr = Upper;
6554 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6555 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6556 if (!Diff.isUsable())
6557 return std::make_pair(nullptr, nullptr);
6558 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6559 if (!Diff.isUsable())
6560 return std::make_pair(nullptr, nullptr);
6561 MinExpr = Diff.get();
6562 }
6563
6564 return std::make_pair(MinExpr, MaxExpr);
6565}
6566
6567Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6568 if (InitDependOnLC || CondDependOnLC)
6569 return Condition;
6570 return nullptr;
6571}
6572
Alexey Bataeve3727102018-04-18 15:57:46 +00006573Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006574 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006575 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006576 // Do not build a precondition when the condition/initialization is dependent
6577 // to prevent pessimistic early loop exit.
6578 // TODO: this can be improved by calculating min/max values but not sure that
6579 // it will be very effective.
6580 if (CondDependOnLC || InitDependOnLC)
6581 return SemaRef.PerformImplicitConversion(
6582 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6583 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6584 /*AllowExplicit=*/true).get();
6585
Alexey Bataev62dbb972015-04-22 11:59:37 +00006586 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006587 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006588
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006589 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6590 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006591 if (!NewLB.isUsable() || !NewUB.isUsable())
6592 return nullptr;
6593
Alexey Bataeve3727102018-04-18 15:57:46 +00006594 ExprResult CondExpr =
6595 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006596 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006597 (TestIsStrictOp ? BO_LT : BO_LE) :
6598 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006599 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006600 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006601 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6602 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006603 CondExpr = SemaRef.PerformImplicitConversion(
6604 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6605 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006606 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006607
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006608 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006609 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6610}
6611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006612/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006613DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006614 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6615 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006616 auto *VD = dyn_cast<VarDecl>(LCDecl);
6617 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006618 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6619 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006620 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006621 const DSAStackTy::DSAVarData Data =
6622 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006623 // If the loop control decl is explicitly marked as private, do not mark it
6624 // as captured again.
6625 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6626 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006627 return Ref;
6628 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006629 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006630}
6631
Alexey Bataeve3727102018-04-18 15:57:46 +00006632Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006633 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006634 QualType Type = LCDecl->getType().getNonReferenceType();
6635 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006636 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6637 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6638 isa<VarDecl>(LCDecl)
6639 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6640 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006641 if (PrivateVar->isInvalidDecl())
6642 return nullptr;
6643 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6644 }
6645 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006646}
6647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006648/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006649Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006650
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006651/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006652Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006653
Alexey Bataevf138fda2018-08-13 19:04:24 +00006654Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6655 Scope *S, Expr *Counter,
6656 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6657 Expr *Inc, OverloadedOperatorKind OOK) {
6658 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6659 if (!Cnt)
6660 return nullptr;
6661 if (Inc) {
6662 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6663 "Expected only + or - operations for depend clauses.");
6664 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6665 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6666 if (!Cnt)
6667 return nullptr;
6668 }
6669 ExprResult Diff;
6670 QualType VarType = LCDecl->getType().getNonReferenceType();
6671 if (VarType->isIntegerType() || VarType->isPointerType() ||
6672 SemaRef.getLangOpts().CPlusPlus) {
6673 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006674 Expr *Upper = TestIsLessOp.getValue()
6675 ? Cnt
6676 : tryBuildCapture(SemaRef, UB, Captures).get();
6677 Expr *Lower = TestIsLessOp.getValue()
6678 ? tryBuildCapture(SemaRef, LB, Captures).get()
6679 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006680 if (!Upper || !Lower)
6681 return nullptr;
6682
6683 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6684
6685 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6686 // BuildBinOp already emitted error, this one is to point user to upper
6687 // and lower bound, and to tell what is passed to 'operator-'.
6688 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6689 << Upper->getSourceRange() << Lower->getSourceRange();
6690 return nullptr;
6691 }
6692 }
6693
6694 if (!Diff.isUsable())
6695 return nullptr;
6696
6697 // Parentheses (for dumping/debugging purposes only).
6698 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6699 if (!Diff.isUsable())
6700 return nullptr;
6701
6702 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6703 if (!NewStep.isUsable())
6704 return nullptr;
6705 // (Upper - Lower) / Step
6706 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6707 if (!Diff.isUsable())
6708 return nullptr;
6709
6710 return Diff.get();
6711}
Alexey Bataev23b69422014-06-18 07:08:49 +00006712} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006713
Alexey Bataev9c821032015-04-30 04:23:23 +00006714void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6715 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6716 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006717 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6718 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006719 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006720 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006721 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006722 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6723 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006724 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006725 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006726 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006727 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006728 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006729 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006730 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6731 /*WithInit=*/false);
6732 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006733 }
6734 }
6735 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006736 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6737 if (LD != D->getCanonicalDecl()) {
6738 DSAStack->resetPossibleLoopCounter();
6739 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6740 MarkDeclarationsReferencedInExpr(
6741 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6742 Var->getType().getNonLValueExprType(Context),
6743 ForLoc, /*RefersToCapture=*/true));
6744 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006745 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6746 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6747 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6748 // associated for-loop of a simd construct with just one associated
6749 // for-loop may be listed in a linear clause with a constant-linear-step
6750 // that is the increment of the associated for-loop. The loop iteration
6751 // variable(s) in the associated for-loop(s) of a for or parallel for
6752 // construct may be listed in a private or lastprivate clause.
6753 DSAStackTy::DSAVarData DVar =
6754 DSAStack->getTopDSA(D, /*FromParent=*/false);
6755 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6756 // is declared in the loop and it is predetermined as a private.
6757 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6758 OpenMPClauseKind PredeterminedCKind =
6759 isOpenMPSimdDirective(DKind)
6760 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6761 : OMPC_private;
6762 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6763 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6764 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6765 DVar.CKind != OMPC_private))) ||
6766 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006767 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006768 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006769 isOpenMPDistributeDirective(DKind)) &&
6770 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6771 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6772 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6773 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6774 << getOpenMPClauseName(DVar.CKind)
6775 << getOpenMPDirectiveName(DKind)
6776 << getOpenMPClauseName(PredeterminedCKind);
6777 if (DVar.RefExpr == nullptr)
6778 DVar.CKind = PredeterminedCKind;
6779 reportOriginalDsa(*this, DSAStack, D, DVar,
6780 /*IsLoopIterVar=*/true);
6781 } else if (LoopDeclRefExpr) {
6782 // Make the loop iteration variable private (for worksharing
6783 // constructs), linear (for simd directives with the only one
6784 // associated loop) or lastprivate (for simd directives with several
6785 // collapsed or ordered loops).
6786 if (DVar.CKind == OMPC_unknown)
6787 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6788 PrivateRef);
6789 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006790 }
6791 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006792 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006793 }
6794}
6795
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006796/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006797/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006798static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006799 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6800 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006801 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6802 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006803 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006804 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006805 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006806 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006807 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006808 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006809 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006810 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6811 // Ranged for is supported only in OpenMP 5.0.
6812 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006813 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006814 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006815 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006816 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006817 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006818 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6819 SemaRef.Diag(DSA.getConstructLoc(),
6820 diag::note_omp_collapse_ordered_expr)
6821 << 2 << CollapseLoopCountExpr->getSourceRange()
6822 << OrderedLoopCountExpr->getSourceRange();
6823 else if (CollapseLoopCountExpr)
6824 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6825 diag::note_omp_collapse_ordered_expr)
6826 << 0 << CollapseLoopCountExpr->getSourceRange();
6827 else
6828 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6829 diag::note_omp_collapse_ordered_expr)
6830 << 1 << OrderedLoopCountExpr->getSourceRange();
6831 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006832 return true;
6833 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006834 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6835 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006836
Alexey Bataevbef93a92019-10-07 18:54:57 +00006837 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6838 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006839
6840 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006841 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006842 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006843 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006844
6845 bool HasErrors = false;
6846
6847 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006848 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006849 // OpenMP [2.6, Canonical Loop Form]
6850 // Var is one of the following:
6851 // A variable of signed or unsigned integer type.
6852 // For C++, a variable of a random access iterator type.
6853 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006854 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006855 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6856 !VarType->isPointerType() &&
6857 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006858 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006859 << SemaRef.getLangOpts().CPlusPlus;
6860 HasErrors = true;
6861 }
6862
6863 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6864 // a Construct
6865 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6866 // parallel for construct is (are) private.
6867 // The loop iteration variable in the associated for-loop of a simd
6868 // construct with just one associated for-loop is linear with a
6869 // constant-linear-step that is the increment of the associated for-loop.
6870 // Exclude loop var from the list of variables with implicitly defined data
6871 // sharing attributes.
6872 VarsWithImplicitDSA.erase(LCDecl);
6873
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006874 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6875
6876 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006877 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006878
6879 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006880 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006881 }
6882
Alexey Bataeve3727102018-04-18 15:57:46 +00006883 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006884 return HasErrors;
6885
Alexander Musmana5f070a2014-10-01 06:03:56 +00006886 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006887 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6888 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006889 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6890 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6891 (isOpenMPWorksharingDirective(DKind) ||
6892 isOpenMPTaskLoopDirective(DKind) ||
6893 isOpenMPDistributeDirective(DKind)),
6894 Captures);
6895 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6896 ISC.buildCounterVar(Captures, DSA);
6897 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6898 ISC.buildPrivateCounterVar();
6899 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6900 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6901 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6902 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6903 ISC.getConditionSrcRange();
6904 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6905 ISC.getIncrementSrcRange();
6906 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6907 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6908 ISC.isStrictTestOp();
6909 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6910 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6911 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6912 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6913 ISC.buildFinalCondition(DSA.getCurScope());
6914 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6915 ISC.doesInitDependOnLC();
6916 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6917 ISC.doesCondDependOnLC();
6918 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6919 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006920
Alexey Bataevf8be4762019-08-14 19:30:06 +00006921 HasErrors |=
6922 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6923 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6924 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6925 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6926 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6927 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006928 if (!HasErrors && DSA.isOrderedRegion()) {
6929 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6930 if (CurrentNestedLoopCount <
6931 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6932 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006933 CurrentNestedLoopCount,
6934 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006935 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006936 CurrentNestedLoopCount,
6937 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006938 }
6939 }
6940 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6941 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6942 // Erroneous case - clause has some problems.
6943 continue;
6944 }
6945 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6946 Pair.second.size() <= CurrentNestedLoopCount) {
6947 // Erroneous case - clause has some problems.
6948 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6949 continue;
6950 }
6951 Expr *CntValue;
6952 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6953 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006954 DSA.getCurScope(),
6955 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006956 Pair.first->getDependencyLoc());
6957 else
6958 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006959 DSA.getCurScope(),
6960 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006961 Pair.first->getDependencyLoc(),
6962 Pair.second[CurrentNestedLoopCount].first,
6963 Pair.second[CurrentNestedLoopCount].second);
6964 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6965 }
6966 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006967
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006968 return HasErrors;
6969}
6970
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006971/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006972static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006973buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006974 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006975 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006976 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006977 ExprResult NewStart = IsNonRectangularLB
6978 ? Start.get()
6979 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006980 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006981 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006982 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006983 VarRef.get()->getType())) {
6984 NewStart = SemaRef.PerformImplicitConversion(
6985 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6986 /*AllowExplicit=*/true);
6987 if (!NewStart.isUsable())
6988 return ExprError();
6989 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006990
Alexey Bataeve3727102018-04-18 15:57:46 +00006991 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006992 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6993 return Init;
6994}
6995
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006996/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006997static ExprResult buildCounterUpdate(
6998 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6999 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007000 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007001 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007002 // Add parentheses (for debugging purposes only).
7003 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7004 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7005 !Step.isUsable())
7006 return ExprError();
7007
Alexey Bataev5a3af132016-03-29 08:58:54 +00007008 ExprResult NewStep = Step;
7009 if (Captures)
7010 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007011 if (NewStep.isInvalid())
7012 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007013 ExprResult Update =
7014 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007015 if (!Update.isUsable())
7016 return ExprError();
7017
Alexey Bataevc0214e02016-02-16 12:13:49 +00007018 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7019 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007020 if (!Start.isUsable())
7021 return ExprError();
7022 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7023 if (!NewStart.isUsable())
7024 return ExprError();
7025 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007026 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007027 if (NewStart.isInvalid())
7028 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007029
Alexey Bataevc0214e02016-02-16 12:13:49 +00007030 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7031 ExprResult SavedUpdate = Update;
7032 ExprResult UpdateVal;
7033 if (VarRef.get()->getType()->isOverloadableType() ||
7034 NewStart.get()->getType()->isOverloadableType() ||
7035 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007036 Sema::TentativeAnalysisScope Trap(SemaRef);
7037
Alexey Bataevc0214e02016-02-16 12:13:49 +00007038 Update =
7039 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7040 if (Update.isUsable()) {
7041 UpdateVal =
7042 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7043 VarRef.get(), SavedUpdate.get());
7044 if (UpdateVal.isUsable()) {
7045 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7046 UpdateVal.get());
7047 }
7048 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007049 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007050
Alexey Bataevc0214e02016-02-16 12:13:49 +00007051 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7052 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7053 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7054 NewStart.get(), SavedUpdate.get());
7055 if (!Update.isUsable())
7056 return ExprError();
7057
Alexey Bataev11481f52016-02-17 10:29:05 +00007058 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7059 VarRef.get()->getType())) {
7060 Update = SemaRef.PerformImplicitConversion(
7061 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7062 if (!Update.isUsable())
7063 return ExprError();
7064 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007065
7066 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7067 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007068 return Update;
7069}
7070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007071/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007072/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007073static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007074 if (E == nullptr)
7075 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007076 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007077 QualType OldType = E->getType();
7078 unsigned HasBits = C.getTypeSize(OldType);
7079 if (HasBits >= Bits)
7080 return ExprResult(E);
7081 // OK to convert to signed, because new type has more bits than old.
7082 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7083 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7084 true);
7085}
7086
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007087/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007088/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007089static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007090 if (E == nullptr)
7091 return false;
7092 llvm::APSInt Result;
7093 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7094 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7095 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007096}
7097
Alexey Bataev5a3af132016-03-29 08:58:54 +00007098/// Build preinits statement for the given declarations.
7099static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007100 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007101 if (!PreInits.empty()) {
7102 return new (Context) DeclStmt(
7103 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7104 SourceLocation(), SourceLocation());
7105 }
7106 return nullptr;
7107}
7108
7109/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007110static Stmt *
7111buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007112 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007113 if (!Captures.empty()) {
7114 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007115 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007116 PreInits.push_back(Pair.second->getDecl());
7117 return buildPreInits(Context, PreInits);
7118 }
7119 return nullptr;
7120}
7121
7122/// Build postupdate expression for the given list of postupdates expressions.
7123static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7124 Expr *PostUpdate = nullptr;
7125 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007126 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007127 Expr *ConvE = S.BuildCStyleCastExpr(
7128 E->getExprLoc(),
7129 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7130 E->getExprLoc(), E)
7131 .get();
7132 PostUpdate = PostUpdate
7133 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7134 PostUpdate, ConvE)
7135 .get()
7136 : ConvE;
7137 }
7138 }
7139 return PostUpdate;
7140}
7141
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007142/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007143/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7144/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007145static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007146checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007147 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7148 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007149 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007150 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007151 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007152 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007153 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007154 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007155 if (!CollapseLoopCountExpr->isValueDependent() &&
7156 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007157 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007158 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007159 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007160 return 1;
7161 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007162 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007163 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007164 if (OrderedLoopCountExpr) {
7165 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007166 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007167 if (!OrderedLoopCountExpr->isValueDependent() &&
7168 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7169 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007170 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007171 if (Result.getLimitedValue() < NestedLoopCount) {
7172 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7173 diag::err_omp_wrong_ordered_loop_count)
7174 << OrderedLoopCountExpr->getSourceRange();
7175 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7176 diag::note_collapse_loop_count)
7177 << CollapseLoopCountExpr->getSourceRange();
7178 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007179 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007180 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007181 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007182 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007183 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007184 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007185 // This is helper routine for loop directives (e.g., 'for', 'simd',
7186 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007187 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007188 SmallVector<LoopIterationSpace, 4> IterSpaces(
7189 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007190 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007191 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007192 if (checkOpenMPIterationSpace(
7193 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7194 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007195 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007196 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007197 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007198 // OpenMP [2.8.1, simd construct, Restrictions]
7199 // All loops associated with the construct must be perfectly nested; that
7200 // is, there must be no intervening code nor any OpenMP directive between
7201 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007202 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7203 CurStmt = For->getBody();
7204 } else {
7205 assert(isa<CXXForRangeStmt>(CurStmt) &&
7206 "Expected canonical for or range-based for loops.");
7207 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7208 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007209 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7210 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007211 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007212 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7213 if (checkOpenMPIterationSpace(
7214 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7215 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007216 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007217 return 0;
7218 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7219 // Handle initialization of captured loop iterator variables.
7220 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7221 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7222 Captures[DRE] = DRE;
7223 }
7224 }
7225 // Move on to the next nested for loop, or to the loop body.
7226 // OpenMP [2.8.1, simd construct, Restrictions]
7227 // All loops associated with the construct must be perfectly nested; that
7228 // is, there must be no intervening code nor any OpenMP directive between
7229 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007230 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7231 CurStmt = For->getBody();
7232 } else {
7233 assert(isa<CXXForRangeStmt>(CurStmt) &&
7234 "Expected canonical for or range-based for loops.");
7235 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7236 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007237 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7238 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007239 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007240
Alexander Musmana5f070a2014-10-01 06:03:56 +00007241 Built.clear(/* size */ NestedLoopCount);
7242
7243 if (SemaRef.CurContext->isDependentContext())
7244 return NestedLoopCount;
7245
7246 // An example of what is generated for the following code:
7247 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007248 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007249 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007250 // for (k = 0; k < NK; ++k)
7251 // for (j = J0; j < NJ; j+=2) {
7252 // <loop body>
7253 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007254 //
7255 // We generate the code below.
7256 // Note: the loop body may be outlined in CodeGen.
7257 // Note: some counters may be C++ classes, operator- is used to find number of
7258 // iterations and operator+= to calculate counter value.
7259 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7260 // or i64 is currently supported).
7261 //
7262 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7263 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7264 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7265 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7266 // // similar updates for vars in clauses (e.g. 'linear')
7267 // <loop body (using local i and j)>
7268 // }
7269 // i = NI; // assign final values of counters
7270 // j = NJ;
7271 //
7272
7273 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7274 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007275 // Precondition tests if there is at least one iteration (all conditions are
7276 // true).
7277 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007278 Expr *N0 = IterSpaces[0].NumIterations;
7279 ExprResult LastIteration32 =
7280 widenIterationCount(/*Bits=*/32,
7281 SemaRef
7282 .PerformImplicitConversion(
7283 N0->IgnoreImpCasts(), N0->getType(),
7284 Sema::AA_Converting, /*AllowExplicit=*/true)
7285 .get(),
7286 SemaRef);
7287 ExprResult LastIteration64 = widenIterationCount(
7288 /*Bits=*/64,
7289 SemaRef
7290 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7291 Sema::AA_Converting,
7292 /*AllowExplicit=*/true)
7293 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007294 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007295
7296 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7297 return NestedLoopCount;
7298
Alexey Bataeve3727102018-04-18 15:57:46 +00007299 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007300 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7301
7302 Scope *CurScope = DSA.getCurScope();
7303 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007304 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007305 PreCond =
7306 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7307 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007308 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007309 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007310 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007311 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7312 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007313 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007314 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007315 SemaRef
7316 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7317 Sema::AA_Converting,
7318 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007319 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007320 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007321 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007322 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007323 SemaRef
7324 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7325 Sema::AA_Converting,
7326 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007327 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007328 }
7329
7330 // Choose either the 32-bit or 64-bit version.
7331 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007332 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7333 (LastIteration32.isUsable() &&
7334 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7335 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7336 fitsInto(
7337 /*Bits=*/32,
7338 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7339 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007340 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007341 QualType VType = LastIteration.get()->getType();
7342 QualType RealVType = VType;
7343 QualType StrideVType = VType;
7344 if (isOpenMPTaskLoopDirective(DKind)) {
7345 VType =
7346 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7347 StrideVType =
7348 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7349 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007350
7351 if (!LastIteration.isUsable())
7352 return 0;
7353
7354 // Save the number of iterations.
7355 ExprResult NumIterations = LastIteration;
7356 {
7357 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007358 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7359 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007360 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7361 if (!LastIteration.isUsable())
7362 return 0;
7363 }
7364
7365 // Calculate the last iteration number beforehand instead of doing this on
7366 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7367 llvm::APSInt Result;
7368 bool IsConstant =
7369 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7370 ExprResult CalcLastIteration;
7371 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007372 ExprResult SaveRef =
7373 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007374 LastIteration = SaveRef;
7375
7376 // Prepare SaveRef + 1.
7377 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007378 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007379 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7380 if (!NumIterations.isUsable())
7381 return 0;
7382 }
7383
7384 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7385
David Majnemer9d168222016-08-05 17:44:54 +00007386 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007387 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007388 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7389 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007390 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007391 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7392 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007393 SemaRef.AddInitializerToDecl(LBDecl,
7394 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7395 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007396
7397 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007398 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7399 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007400 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007401 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007402
7403 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7404 // This will be used to implement clause 'lastprivate'.
7405 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007406 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7407 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007408 SemaRef.AddInitializerToDecl(ILDecl,
7409 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7410 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007411
7412 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007413 VarDecl *STDecl =
7414 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7415 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007416 SemaRef.AddInitializerToDecl(STDecl,
7417 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7418 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007419
7420 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007421 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007422 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7423 UB.get(), LastIteration.get());
7424 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007425 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7426 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007427 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7428 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007429 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007430
7431 // If we have a combined directive that combines 'distribute', 'for' or
7432 // 'simd' we need to be able to access the bounds of the schedule of the
7433 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7434 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7435 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007436 // Lower bound variable, initialized with zero.
7437 VarDecl *CombLBDecl =
7438 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7439 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7440 SemaRef.AddInitializerToDecl(
7441 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7442 /*DirectInit*/ false);
7443
7444 // Upper bound variable, initialized with last iteration number.
7445 VarDecl *CombUBDecl =
7446 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7447 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7448 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7449 /*DirectInit*/ false);
7450
7451 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7452 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7453 ExprResult CombCondOp =
7454 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7455 LastIteration.get(), CombUB.get());
7456 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7457 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007458 CombEUB =
7459 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007460
Alexey Bataeve3727102018-04-18 15:57:46 +00007461 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007462 // We expect to have at least 2 more parameters than the 'parallel'
7463 // directive does - the lower and upper bounds of the previous schedule.
7464 assert(CD->getNumParams() >= 4 &&
7465 "Unexpected number of parameters in loop combined directive");
7466
7467 // Set the proper type for the bounds given what we learned from the
7468 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007469 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7470 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007471
7472 // Previous lower and upper bounds are obtained from the region
7473 // parameters.
7474 PrevLB =
7475 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7476 PrevUB =
7477 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7478 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007479 }
7480
7481 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007482 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007483 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007484 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007485 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7486 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007487 Expr *RHS =
7488 (isOpenMPWorksharingDirective(DKind) ||
7489 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7490 ? LB.get()
7491 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007492 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007493 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007494
7495 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7496 Expr *CombRHS =
7497 (isOpenMPWorksharingDirective(DKind) ||
7498 isOpenMPTaskLoopDirective(DKind) ||
7499 isOpenMPDistributeDirective(DKind))
7500 ? CombLB.get()
7501 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7502 CombInit =
7503 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007504 CombInit =
7505 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007506 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007507 }
7508
Alexey Bataev316ccf62019-01-29 18:51:58 +00007509 bool UseStrictCompare =
7510 RealVType->hasUnsignedIntegerRepresentation() &&
7511 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7512 return LIS.IsStrictCompare;
7513 });
7514 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7515 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007516 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007517 Expr *BoundUB = UB.get();
7518 if (UseStrictCompare) {
7519 BoundUB =
7520 SemaRef
7521 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7522 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7523 .get();
7524 BoundUB =
7525 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7526 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007527 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007528 (isOpenMPWorksharingDirective(DKind) ||
7529 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007530 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7531 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7532 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007533 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7534 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007535 ExprResult CombDistCond;
7536 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007537 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7538 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007539 }
7540
Carlo Bertolliffafe102017-04-20 00:39:39 +00007541 ExprResult CombCond;
7542 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007543 Expr *BoundCombUB = CombUB.get();
7544 if (UseStrictCompare) {
7545 BoundCombUB =
7546 SemaRef
7547 .BuildBinOp(
7548 CurScope, CondLoc, BO_Add, BoundCombUB,
7549 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7550 .get();
7551 BoundCombUB =
7552 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7553 .get();
7554 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007555 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007556 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7557 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007558 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007559 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007560 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007561 ExprResult Inc =
7562 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7563 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7564 if (!Inc.isUsable())
7565 return 0;
7566 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007567 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007568 if (!Inc.isUsable())
7569 return 0;
7570
7571 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7572 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007573 // In combined construct, add combined version that use CombLB and CombUB
7574 // base variables for the update
7575 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007576 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7577 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007578 // LB + ST
7579 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7580 if (!NextLB.isUsable())
7581 return 0;
7582 // LB = LB + ST
7583 NextLB =
7584 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007585 NextLB =
7586 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007587 if (!NextLB.isUsable())
7588 return 0;
7589 // UB + ST
7590 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7591 if (!NextUB.isUsable())
7592 return 0;
7593 // UB = UB + ST
7594 NextUB =
7595 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007596 NextUB =
7597 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007598 if (!NextUB.isUsable())
7599 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007600 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7601 CombNextLB =
7602 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7603 if (!NextLB.isUsable())
7604 return 0;
7605 // LB = LB + ST
7606 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7607 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007608 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7609 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007610 if (!CombNextLB.isUsable())
7611 return 0;
7612 // UB + ST
7613 CombNextUB =
7614 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7615 if (!CombNextUB.isUsable())
7616 return 0;
7617 // UB = UB + ST
7618 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7619 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007620 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7621 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007622 if (!CombNextUB.isUsable())
7623 return 0;
7624 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007625 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007626
Carlo Bertolliffafe102017-04-20 00:39:39 +00007627 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007628 // directive with for as IV = IV + ST; ensure upper bound expression based
7629 // on PrevUB instead of NumIterations - used to implement 'for' when found
7630 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007631 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007632 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007633 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007634 DistCond = SemaRef.BuildBinOp(
7635 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007636 assert(DistCond.isUsable() && "distribute cond expr was not built");
7637
7638 DistInc =
7639 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7640 assert(DistInc.isUsable() && "distribute inc expr was not built");
7641 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7642 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007643 DistInc =
7644 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007645 assert(DistInc.isUsable() && "distribute inc expr was not built");
7646
7647 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7648 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007649 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007650 ExprResult IsUBGreater =
7651 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7652 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7653 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7654 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7655 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007656 PrevEUB =
7657 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007658
Alexey Bataev316ccf62019-01-29 18:51:58 +00007659 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7660 // parallel for is in combination with a distribute directive with
7661 // schedule(static, 1)
7662 Expr *BoundPrevUB = PrevUB.get();
7663 if (UseStrictCompare) {
7664 BoundPrevUB =
7665 SemaRef
7666 .BuildBinOp(
7667 CurScope, CondLoc, BO_Add, BoundPrevUB,
7668 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7669 .get();
7670 BoundPrevUB =
7671 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7672 .get();
7673 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007674 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007675 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7676 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007677 }
7678
Alexander Musmana5f070a2014-10-01 06:03:56 +00007679 // Build updates and final values of the loop counters.
7680 bool HasErrors = false;
7681 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007682 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007683 Built.Updates.resize(NestedLoopCount);
7684 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007685 Built.DependentCounters.resize(NestedLoopCount);
7686 Built.DependentInits.resize(NestedLoopCount);
7687 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007688 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007689 // We implement the following algorithm for obtaining the
7690 // original loop iteration variable values based on the
7691 // value of the collapsed loop iteration variable IV.
7692 //
7693 // Let n+1 be the number of collapsed loops in the nest.
7694 // Iteration variables (I0, I1, .... In)
7695 // Iteration counts (N0, N1, ... Nn)
7696 //
7697 // Acc = IV;
7698 //
7699 // To compute Ik for loop k, 0 <= k <= n, generate:
7700 // Prod = N(k+1) * N(k+2) * ... * Nn;
7701 // Ik = Acc / Prod;
7702 // Acc -= Ik * Prod;
7703 //
7704 ExprResult Acc = IV;
7705 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007706 LoopIterationSpace &IS = IterSpaces[Cnt];
7707 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007708 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007709
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007710 // Compute prod
7711 ExprResult Prod =
7712 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7713 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7714 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7715 IterSpaces[K].NumIterations);
7716
7717 // Iter = Acc / Prod
7718 // If there is at least one more inner loop to avoid
7719 // multiplication by 1.
7720 if (Cnt + 1 < NestedLoopCount)
7721 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7722 Acc.get(), Prod.get());
7723 else
7724 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007725 if (!Iter.isUsable()) {
7726 HasErrors = true;
7727 break;
7728 }
7729
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007730 // Update Acc:
7731 // Acc -= Iter * Prod
7732 // Check if there is at least one more inner loop to avoid
7733 // multiplication by 1.
7734 if (Cnt + 1 < NestedLoopCount)
7735 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7736 Iter.get(), Prod.get());
7737 else
7738 Prod = Iter;
7739 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7740 Acc.get(), Prod.get());
7741
Alexey Bataev39f915b82015-05-08 10:41:21 +00007742 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007743 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007744 DeclRefExpr *CounterVar = buildDeclRefExpr(
7745 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7746 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007747 ExprResult Init =
7748 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7749 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007750 if (!Init.isUsable()) {
7751 HasErrors = true;
7752 break;
7753 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007754 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007755 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007756 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007757 if (!Update.isUsable()) {
7758 HasErrors = true;
7759 break;
7760 }
7761
7762 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007763 ExprResult Final =
7764 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7765 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7766 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007767 if (!Final.isUsable()) {
7768 HasErrors = true;
7769 break;
7770 }
7771
Alexander Musmana5f070a2014-10-01 06:03:56 +00007772 if (!Update.isUsable() || !Final.isUsable()) {
7773 HasErrors = true;
7774 break;
7775 }
7776 // Save results
7777 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007778 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007779 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007780 Built.Updates[Cnt] = Update.get();
7781 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007782 Built.DependentCounters[Cnt] = nullptr;
7783 Built.DependentInits[Cnt] = nullptr;
7784 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007785 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007786 Built.DependentCounters[Cnt] =
7787 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7788 Built.DependentInits[Cnt] =
7789 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7790 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7791 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007792 }
7793 }
7794
7795 if (HasErrors)
7796 return 0;
7797
7798 // Save results
7799 Built.IterationVarRef = IV.get();
7800 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007801 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007802 Built.CalcLastIteration = SemaRef
7803 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007804 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007805 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007806 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007807 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007808 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007809 Built.Init = Init.get();
7810 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007811 Built.LB = LB.get();
7812 Built.UB = UB.get();
7813 Built.IL = IL.get();
7814 Built.ST = ST.get();
7815 Built.EUB = EUB.get();
7816 Built.NLB = NextLB.get();
7817 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007818 Built.PrevLB = PrevLB.get();
7819 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007820 Built.DistInc = DistInc.get();
7821 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007822 Built.DistCombinedFields.LB = CombLB.get();
7823 Built.DistCombinedFields.UB = CombUB.get();
7824 Built.DistCombinedFields.EUB = CombEUB.get();
7825 Built.DistCombinedFields.Init = CombInit.get();
7826 Built.DistCombinedFields.Cond = CombCond.get();
7827 Built.DistCombinedFields.NLB = CombNextLB.get();
7828 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007829 Built.DistCombinedFields.DistCond = CombDistCond.get();
7830 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007831
Alexey Bataevabfc0692014-06-25 06:52:00 +00007832 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007833}
7834
Alexey Bataev10e775f2015-07-30 11:36:16 +00007835static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007836 auto CollapseClauses =
7837 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7838 if (CollapseClauses.begin() != CollapseClauses.end())
7839 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007840 return nullptr;
7841}
7842
Alexey Bataev10e775f2015-07-30 11:36:16 +00007843static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007844 auto OrderedClauses =
7845 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7846 if (OrderedClauses.begin() != OrderedClauses.end())
7847 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007848 return nullptr;
7849}
7850
Kelvin Lic5609492016-07-15 04:39:07 +00007851static bool checkSimdlenSafelenSpecified(Sema &S,
7852 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007853 const OMPSafelenClause *Safelen = nullptr;
7854 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007855
Alexey Bataeve3727102018-04-18 15:57:46 +00007856 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007857 if (Clause->getClauseKind() == OMPC_safelen)
7858 Safelen = cast<OMPSafelenClause>(Clause);
7859 else if (Clause->getClauseKind() == OMPC_simdlen)
7860 Simdlen = cast<OMPSimdlenClause>(Clause);
7861 if (Safelen && Simdlen)
7862 break;
7863 }
7864
7865 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007866 const Expr *SimdlenLength = Simdlen->getSimdlen();
7867 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007868 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7869 SimdlenLength->isInstantiationDependent() ||
7870 SimdlenLength->containsUnexpandedParameterPack())
7871 return false;
7872 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7873 SafelenLength->isInstantiationDependent() ||
7874 SafelenLength->containsUnexpandedParameterPack())
7875 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007876 Expr::EvalResult SimdlenResult, SafelenResult;
7877 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7878 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7879 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7880 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007881 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7882 // If both simdlen and safelen clauses are specified, the value of the
7883 // simdlen parameter must be less than or equal to the value of the safelen
7884 // parameter.
7885 if (SimdlenRes > SafelenRes) {
7886 S.Diag(SimdlenLength->getExprLoc(),
7887 diag::err_omp_wrong_simdlen_safelen_values)
7888 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7889 return true;
7890 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007891 }
7892 return false;
7893}
7894
Alexey Bataeve3727102018-04-18 15:57:46 +00007895StmtResult
7896Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7897 SourceLocation StartLoc, SourceLocation EndLoc,
7898 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007899 if (!AStmt)
7900 return StmtError();
7901
7902 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007903 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007904 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7905 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007906 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007907 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7908 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007909 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007910 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007911
Alexander Musmana5f070a2014-10-01 06:03:56 +00007912 assert((CurContext->isDependentContext() || B.builtAll()) &&
7913 "omp simd loop exprs were not built");
7914
Alexander Musman3276a272015-03-21 10:12:56 +00007915 if (!CurContext->isDependentContext()) {
7916 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007917 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007918 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007920 B.NumIterations, *this, CurScope,
7921 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007922 return StmtError();
7923 }
7924 }
7925
Kelvin Lic5609492016-07-15 04:39:07 +00007926 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007927 return StmtError();
7928
Reid Kleckner87a31802018-03-12 21:43:02 +00007929 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007930 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7931 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007932}
7933
Alexey Bataeve3727102018-04-18 15:57:46 +00007934StmtResult
7935Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7936 SourceLocation StartLoc, SourceLocation EndLoc,
7937 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007938 if (!AStmt)
7939 return StmtError();
7940
7941 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007942 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007943 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7944 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007945 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007946 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7947 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007948 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007949 return StmtError();
7950
Alexander Musmana5f070a2014-10-01 06:03:56 +00007951 assert((CurContext->isDependentContext() || B.builtAll()) &&
7952 "omp for loop exprs were not built");
7953
Alexey Bataev54acd402015-08-04 11:18:19 +00007954 if (!CurContext->isDependentContext()) {
7955 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007956 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007957 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007958 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007959 B.NumIterations, *this, CurScope,
7960 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007961 return StmtError();
7962 }
7963 }
7964
Reid Kleckner87a31802018-03-12 21:43:02 +00007965 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007966 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007967 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007968}
7969
Alexander Musmanf82886e2014-09-18 05:12:34 +00007970StmtResult Sema::ActOnOpenMPForSimdDirective(
7971 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007972 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007973 if (!AStmt)
7974 return StmtError();
7975
7976 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007977 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007978 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7979 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007980 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007982 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7983 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007984 if (NestedLoopCount == 0)
7985 return StmtError();
7986
Alexander Musmanc6388682014-12-15 07:07:06 +00007987 assert((CurContext->isDependentContext() || B.builtAll()) &&
7988 "omp for simd loop exprs were not built");
7989
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007990 if (!CurContext->isDependentContext()) {
7991 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007992 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007993 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007994 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007995 B.NumIterations, *this, CurScope,
7996 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007997 return StmtError();
7998 }
7999 }
8000
Kelvin Lic5609492016-07-15 04:39:07 +00008001 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008002 return StmtError();
8003
Reid Kleckner87a31802018-03-12 21:43:02 +00008004 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008005 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8006 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008007}
8008
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008009StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8010 Stmt *AStmt,
8011 SourceLocation StartLoc,
8012 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008013 if (!AStmt)
8014 return StmtError();
8015
8016 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008017 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008018 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008019 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008020 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008021 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008022 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008023 return StmtError();
8024 // All associated statements must be '#pragma omp section' except for
8025 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008026 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008027 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8028 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008029 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008030 diag::err_omp_sections_substmt_not_section);
8031 return StmtError();
8032 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008033 cast<OMPSectionDirective>(SectionStmt)
8034 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008035 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008036 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008037 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008038 return StmtError();
8039 }
8040
Reid Kleckner87a31802018-03-12 21:43:02 +00008041 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008042
Alexey Bataev25e5b442015-09-15 12:52:43 +00008043 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8044 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008045}
8046
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008047StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8048 SourceLocation StartLoc,
8049 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008050 if (!AStmt)
8051 return StmtError();
8052
8053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008054
Reid Kleckner87a31802018-03-12 21:43:02 +00008055 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008056 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008057
Alexey Bataev25e5b442015-09-15 12:52:43 +00008058 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8059 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008060}
8061
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008062StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8063 Stmt *AStmt,
8064 SourceLocation StartLoc,
8065 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008066 if (!AStmt)
8067 return StmtError();
8068
8069 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008070
Reid Kleckner87a31802018-03-12 21:43:02 +00008071 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008072
Alexey Bataev3255bf32015-01-19 05:20:46 +00008073 // OpenMP [2.7.3, single Construct, Restrictions]
8074 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008075 const OMPClause *Nowait = nullptr;
8076 const OMPClause *Copyprivate = nullptr;
8077 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008078 if (Clause->getClauseKind() == OMPC_nowait)
8079 Nowait = Clause;
8080 else if (Clause->getClauseKind() == OMPC_copyprivate)
8081 Copyprivate = Clause;
8082 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008083 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008084 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008085 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008086 return StmtError();
8087 }
8088 }
8089
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008090 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8091}
8092
Alexander Musman80c22892014-07-17 08:54:58 +00008093StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8094 SourceLocation StartLoc,
8095 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008096 if (!AStmt)
8097 return StmtError();
8098
8099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008100
Reid Kleckner87a31802018-03-12 21:43:02 +00008101 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008102
8103 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8104}
8105
Alexey Bataev28c75412015-12-15 08:19:24 +00008106StmtResult Sema::ActOnOpenMPCriticalDirective(
8107 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8108 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008109 if (!AStmt)
8110 return StmtError();
8111
8112 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008113
Alexey Bataev28c75412015-12-15 08:19:24 +00008114 bool ErrorFound = false;
8115 llvm::APSInt Hint;
8116 SourceLocation HintLoc;
8117 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008118 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008119 if (C->getClauseKind() == OMPC_hint) {
8120 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008121 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008122 ErrorFound = true;
8123 }
8124 Expr *E = cast<OMPHintClause>(C)->getHint();
8125 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008126 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008127 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008128 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008129 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008130 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008131 }
8132 }
8133 }
8134 if (ErrorFound)
8135 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008136 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008137 if (Pair.first && DirName.getName() && !DependentHint) {
8138 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8139 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008140 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008141 Diag(HintLoc, diag::note_omp_critical_hint_here)
8142 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008143 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008144 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008145 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008146 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008147 << 1
8148 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8149 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008150 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008151 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008152 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008153 }
8154 }
8155
Reid Kleckner87a31802018-03-12 21:43:02 +00008156 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008157
Alexey Bataev28c75412015-12-15 08:19:24 +00008158 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8159 Clauses, AStmt);
8160 if (!Pair.first && DirName.getName() && !DependentHint)
8161 DSAStack->addCriticalWithHint(Dir, Hint);
8162 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008163}
8164
Alexey Bataev4acb8592014-07-07 13:01:15 +00008165StmtResult Sema::ActOnOpenMPParallelForDirective(
8166 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008167 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008168 if (!AStmt)
8169 return StmtError();
8170
Alexey Bataeve3727102018-04-18 15:57:46 +00008171 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008172 // 1.2.2 OpenMP Language Terminology
8173 // Structured block - An executable statement with a single entry at the
8174 // top and a single exit at the bottom.
8175 // The point of exit cannot be a branch out of the structured block.
8176 // longjmp() and throw() must not violate the entry/exit criteria.
8177 CS->getCapturedDecl()->setNothrow();
8178
Alexander Musmanc6388682014-12-15 07:07:06 +00008179 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008180 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8181 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008182 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008183 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008184 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8185 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008186 if (NestedLoopCount == 0)
8187 return StmtError();
8188
Alexander Musmana5f070a2014-10-01 06:03:56 +00008189 assert((CurContext->isDependentContext() || B.builtAll()) &&
8190 "omp parallel for loop exprs were not built");
8191
Alexey Bataev54acd402015-08-04 11:18:19 +00008192 if (!CurContext->isDependentContext()) {
8193 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008194 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008195 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008196 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008197 B.NumIterations, *this, CurScope,
8198 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008199 return StmtError();
8200 }
8201 }
8202
Reid Kleckner87a31802018-03-12 21:43:02 +00008203 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008204 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008205 NestedLoopCount, Clauses, AStmt, B,
8206 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008207}
8208
Alexander Musmane4e893b2014-09-23 09:33:00 +00008209StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008212 if (!AStmt)
8213 return StmtError();
8214
Alexey Bataeve3727102018-04-18 15:57:46 +00008215 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008216 // 1.2.2 OpenMP Language Terminology
8217 // Structured block - An executable statement with a single entry at the
8218 // top and a single exit at the bottom.
8219 // The point of exit cannot be a branch out of the structured block.
8220 // longjmp() and throw() must not violate the entry/exit criteria.
8221 CS->getCapturedDecl()->setNothrow();
8222
Alexander Musmanc6388682014-12-15 07:07:06 +00008223 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008224 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8225 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008226 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008227 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008228 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8229 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008230 if (NestedLoopCount == 0)
8231 return StmtError();
8232
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008233 if (!CurContext->isDependentContext()) {
8234 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008235 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008236 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008237 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008238 B.NumIterations, *this, CurScope,
8239 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008240 return StmtError();
8241 }
8242 }
8243
Kelvin Lic5609492016-07-15 04:39:07 +00008244 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008245 return StmtError();
8246
Reid Kleckner87a31802018-03-12 21:43:02 +00008247 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008248 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008249 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008250}
8251
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008252StmtResult
8253Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8254 Stmt *AStmt, SourceLocation StartLoc,
8255 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008256 if (!AStmt)
8257 return StmtError();
8258
8259 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008260 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008261 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008262 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008263 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008264 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008265 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008266 return StmtError();
8267 // All associated statements must be '#pragma omp section' except for
8268 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008269 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008270 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8271 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008272 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008273 diag::err_omp_parallel_sections_substmt_not_section);
8274 return StmtError();
8275 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008276 cast<OMPSectionDirective>(SectionStmt)
8277 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008278 }
8279 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008280 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008281 diag::err_omp_parallel_sections_not_compound_stmt);
8282 return StmtError();
8283 }
8284
Reid Kleckner87a31802018-03-12 21:43:02 +00008285 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008286
Alexey Bataev25e5b442015-09-15 12:52:43 +00008287 return OMPParallelSectionsDirective::Create(
8288 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008289}
8290
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008291StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8292 Stmt *AStmt, SourceLocation StartLoc,
8293 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008294 if (!AStmt)
8295 return StmtError();
8296
David Majnemer9d168222016-08-05 17:44:54 +00008297 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008298 // 1.2.2 OpenMP Language Terminology
8299 // Structured block - An executable statement with a single entry at the
8300 // top and a single exit at the bottom.
8301 // The point of exit cannot be a branch out of the structured block.
8302 // longjmp() and throw() must not violate the entry/exit criteria.
8303 CS->getCapturedDecl()->setNothrow();
8304
Reid Kleckner87a31802018-03-12 21:43:02 +00008305 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008306
Alexey Bataev25e5b442015-09-15 12:52:43 +00008307 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8308 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008309}
8310
Alexey Bataev68446b72014-07-18 07:47:19 +00008311StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8312 SourceLocation EndLoc) {
8313 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8314}
8315
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008316StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8317 SourceLocation EndLoc) {
8318 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8319}
8320
Alexey Bataev2df347a2014-07-18 10:17:07 +00008321StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8322 SourceLocation EndLoc) {
8323 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8324}
8325
Alexey Bataev169d96a2017-07-18 20:17:46 +00008326StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8327 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008328 SourceLocation StartLoc,
8329 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008330 if (!AStmt)
8331 return StmtError();
8332
8333 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008334
Reid Kleckner87a31802018-03-12 21:43:02 +00008335 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008336
Alexey Bataev169d96a2017-07-18 20:17:46 +00008337 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008338 AStmt,
8339 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008340}
8341
Alexey Bataev6125da92014-07-21 11:26:11 +00008342StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8343 SourceLocation StartLoc,
8344 SourceLocation EndLoc) {
8345 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8346 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8347}
8348
Alexey Bataev346265e2015-09-25 10:37:12 +00008349StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8350 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008351 SourceLocation StartLoc,
8352 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008353 const OMPClause *DependFound = nullptr;
8354 const OMPClause *DependSourceClause = nullptr;
8355 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008356 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008357 const OMPThreadsClause *TC = nullptr;
8358 const OMPSIMDClause *SC = nullptr;
8359 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008360 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8361 DependFound = C;
8362 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8363 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008364 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008365 << getOpenMPDirectiveName(OMPD_ordered)
8366 << getOpenMPClauseName(OMPC_depend) << 2;
8367 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008368 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008369 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008370 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008371 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008372 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008373 << 0;
8374 ErrorFound = true;
8375 }
8376 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8377 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008378 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008379 << 1;
8380 ErrorFound = true;
8381 }
8382 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008383 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008385 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008386 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008387 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008388 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008389 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008390 if (!ErrorFound && !SC &&
8391 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008392 // OpenMP [2.8.1,simd Construct, Restrictions]
8393 // An ordered construct with the simd clause is the only OpenMP construct
8394 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008395 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8396 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008397 ErrorFound = true;
8398 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008399 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008400 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8401 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008402 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008403 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008404 diag::err_omp_ordered_directive_without_param);
8405 ErrorFound = true;
8406 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008407 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008408 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008409 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8410 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008411 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008412 ErrorFound = true;
8413 }
8414 }
8415 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008416 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008417
8418 if (AStmt) {
8419 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8420
Reid Kleckner87a31802018-03-12 21:43:02 +00008421 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008422 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008423
8424 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008425}
8426
Alexey Bataev1d160b12015-03-13 12:27:31 +00008427namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008428/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008429/// construct.
8430class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008431 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008432 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008433 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008434 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008435 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008436 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008437 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008438 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008439 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008440 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008441 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008442 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008443 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008444 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008445 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008446 /// expression.
8447 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008448 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008449 /// part.
8450 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008451 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008452 NoError
8453 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008454 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008455 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008456 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008457 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008458 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008459 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008460 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008461 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008462 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008463 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8464 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8465 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008466 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008467 /// important for non-associative operations.
8468 bool IsXLHSInRHSPart;
8469 BinaryOperatorKind Op;
8470 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008471 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008472 /// if it is a prefix unary operation.
8473 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008474
8475public:
8476 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008477 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008478 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008479 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008480 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008481 /// expression. If DiagId and NoteId == 0, then only check is performed
8482 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008483 /// \param DiagId Diagnostic which should be emitted if error is found.
8484 /// \param NoteId Diagnostic note for the main error message.
8485 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008486 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008487 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008488 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008489 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008490 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008491 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008492 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8493 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8494 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008495 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008496 /// false otherwise.
8497 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008499 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008500 /// if it is a prefix unary operation.
8501 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8502
Alexey Bataev1d160b12015-03-13 12:27:31 +00008503private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008504 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8505 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008506};
8507} // namespace
8508
8509bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8510 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8511 ExprAnalysisErrorCode ErrorFound = NoError;
8512 SourceLocation ErrorLoc, NoteLoc;
8513 SourceRange ErrorRange, NoteRange;
8514 // Allowed constructs are:
8515 // x = x binop expr;
8516 // x = expr binop x;
8517 if (AtomicBinOp->getOpcode() == BO_Assign) {
8518 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008519 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008520 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8521 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8522 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8523 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008524 Op = AtomicInnerBinOp->getOpcode();
8525 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008526 Expr *LHS = AtomicInnerBinOp->getLHS();
8527 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008528 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8529 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8530 /*Canonical=*/true);
8531 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8532 /*Canonical=*/true);
8533 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8534 /*Canonical=*/true);
8535 if (XId == LHSId) {
8536 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008537 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008538 } else if (XId == RHSId) {
8539 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008540 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008541 } else {
8542 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8543 ErrorRange = AtomicInnerBinOp->getSourceRange();
8544 NoteLoc = X->getExprLoc();
8545 NoteRange = X->getSourceRange();
8546 ErrorFound = NotAnUpdateExpression;
8547 }
8548 } else {
8549 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8550 ErrorRange = AtomicInnerBinOp->getSourceRange();
8551 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8552 NoteRange = SourceRange(NoteLoc, NoteLoc);
8553 ErrorFound = NotABinaryOperator;
8554 }
8555 } else {
8556 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8557 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8558 ErrorFound = NotABinaryExpression;
8559 }
8560 } else {
8561 ErrorLoc = AtomicBinOp->getExprLoc();
8562 ErrorRange = AtomicBinOp->getSourceRange();
8563 NoteLoc = AtomicBinOp->getOperatorLoc();
8564 NoteRange = SourceRange(NoteLoc, NoteLoc);
8565 ErrorFound = NotAnAssignmentOp;
8566 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008567 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008568 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8569 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8570 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008571 }
8572 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008573 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008574 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008575}
8576
8577bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8578 unsigned NoteId) {
8579 ExprAnalysisErrorCode ErrorFound = NoError;
8580 SourceLocation ErrorLoc, NoteLoc;
8581 SourceRange ErrorRange, NoteRange;
8582 // Allowed constructs are:
8583 // x++;
8584 // x--;
8585 // ++x;
8586 // --x;
8587 // x binop= expr;
8588 // x = x binop expr;
8589 // x = expr binop x;
8590 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8591 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8592 if (AtomicBody->getType()->isScalarType() ||
8593 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008594 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008595 AtomicBody->IgnoreParenImpCasts())) {
8596 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008597 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008598 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008599 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008600 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008601 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008602 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008603 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8604 AtomicBody->IgnoreParenImpCasts())) {
8605 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008606 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008607 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008608 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008609 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008610 // Check for Unary Operation
8611 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008612 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008613 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8614 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008615 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008616 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8617 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008618 } else {
8619 ErrorFound = NotAnUnaryIncDecExpression;
8620 ErrorLoc = AtomicUnaryOp->getExprLoc();
8621 ErrorRange = AtomicUnaryOp->getSourceRange();
8622 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8623 NoteRange = SourceRange(NoteLoc, NoteLoc);
8624 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008625 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008626 ErrorFound = NotABinaryOrUnaryExpression;
8627 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8628 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8629 }
8630 } else {
8631 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008632 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008633 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8634 }
8635 } else {
8636 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008637 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008638 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8639 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008640 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008641 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8642 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8643 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008644 }
8645 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008646 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008647 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008648 // Build an update expression of form 'OpaqueValueExpr(x) binop
8649 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8650 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8651 auto *OVEX = new (SemaRef.getASTContext())
8652 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8653 auto *OVEExpr = new (SemaRef.getASTContext())
8654 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008655 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008656 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8657 IsXLHSInRHSPart ? OVEExpr : OVEX);
8658 if (Update.isInvalid())
8659 return true;
8660 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8661 Sema::AA_Casting);
8662 if (Update.isInvalid())
8663 return true;
8664 UpdateExpr = Update.get();
8665 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008666 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008667}
8668
Alexey Bataev0162e452014-07-22 10:10:35 +00008669StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8670 Stmt *AStmt,
8671 SourceLocation StartLoc,
8672 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008673 if (!AStmt)
8674 return StmtError();
8675
David Majnemer9d168222016-08-05 17:44:54 +00008676 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008677 // 1.2.2 OpenMP Language Terminology
8678 // Structured block - An executable statement with a single entry at the
8679 // top and a single exit at the bottom.
8680 // The point of exit cannot be a branch out of the structured block.
8681 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008682 OpenMPClauseKind AtomicKind = OMPC_unknown;
8683 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008684 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008685 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008686 C->getClauseKind() == OMPC_update ||
8687 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008688 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008689 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008690 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008691 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8692 << getOpenMPClauseName(AtomicKind);
8693 } else {
8694 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008695 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008696 }
8697 }
8698 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008699
Alexey Bataeve3727102018-04-18 15:57:46 +00008700 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008701 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8702 Body = EWC->getSubExpr();
8703
Alexey Bataev62cec442014-11-18 10:14:22 +00008704 Expr *X = nullptr;
8705 Expr *V = nullptr;
8706 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008707 Expr *UE = nullptr;
8708 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008709 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008710 // OpenMP [2.12.6, atomic Construct]
8711 // In the next expressions:
8712 // * x and v (as applicable) are both l-value expressions with scalar type.
8713 // * During the execution of an atomic region, multiple syntactic
8714 // occurrences of x must designate the same storage location.
8715 // * Neither of v and expr (as applicable) may access the storage location
8716 // designated by x.
8717 // * Neither of x and expr (as applicable) may access the storage location
8718 // designated by v.
8719 // * expr is an expression with scalar type.
8720 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8721 // * binop, binop=, ++, and -- are not overloaded operators.
8722 // * The expression x binop expr must be numerically equivalent to x binop
8723 // (expr). This requirement is satisfied if the operators in expr have
8724 // precedence greater than binop, or by using parentheses around expr or
8725 // subexpressions of expr.
8726 // * The expression expr binop x must be numerically equivalent to (expr)
8727 // binop x. This requirement is satisfied if the operators in expr have
8728 // precedence equal to or greater than binop, or by using parentheses around
8729 // expr or subexpressions of expr.
8730 // * For forms that allow multiple occurrences of x, the number of times
8731 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008732 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008733 enum {
8734 NotAnExpression,
8735 NotAnAssignmentOp,
8736 NotAScalarType,
8737 NotAnLValue,
8738 NoError
8739 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008740 SourceLocation ErrorLoc, NoteLoc;
8741 SourceRange ErrorRange, NoteRange;
8742 // If clause is read:
8743 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008744 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8745 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008746 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8747 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8748 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8749 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8750 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8751 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8752 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008753 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008754 ErrorFound = NotAnLValue;
8755 ErrorLoc = AtomicBinOp->getExprLoc();
8756 ErrorRange = AtomicBinOp->getSourceRange();
8757 NoteLoc = NotLValueExpr->getExprLoc();
8758 NoteRange = NotLValueExpr->getSourceRange();
8759 }
8760 } else if (!X->isInstantiationDependent() ||
8761 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008762 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008763 (X->isInstantiationDependent() || X->getType()->isScalarType())
8764 ? V
8765 : X;
8766 ErrorFound = NotAScalarType;
8767 ErrorLoc = AtomicBinOp->getExprLoc();
8768 ErrorRange = AtomicBinOp->getSourceRange();
8769 NoteLoc = NotScalarExpr->getExprLoc();
8770 NoteRange = NotScalarExpr->getSourceRange();
8771 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008772 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008773 ErrorFound = NotAnAssignmentOp;
8774 ErrorLoc = AtomicBody->getExprLoc();
8775 ErrorRange = AtomicBody->getSourceRange();
8776 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8777 : AtomicBody->getExprLoc();
8778 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8779 : AtomicBody->getSourceRange();
8780 }
8781 } else {
8782 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008783 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008784 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008785 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008786 if (ErrorFound != NoError) {
8787 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8788 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008789 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8790 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008791 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008792 }
8793 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008794 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008795 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008796 enum {
8797 NotAnExpression,
8798 NotAnAssignmentOp,
8799 NotAScalarType,
8800 NotAnLValue,
8801 NoError
8802 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008803 SourceLocation ErrorLoc, NoteLoc;
8804 SourceRange ErrorRange, NoteRange;
8805 // If clause is write:
8806 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008807 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8808 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008809 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8810 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008811 X = AtomicBinOp->getLHS();
8812 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008813 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8814 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8815 if (!X->isLValue()) {
8816 ErrorFound = NotAnLValue;
8817 ErrorLoc = AtomicBinOp->getExprLoc();
8818 ErrorRange = AtomicBinOp->getSourceRange();
8819 NoteLoc = X->getExprLoc();
8820 NoteRange = X->getSourceRange();
8821 }
8822 } else if (!X->isInstantiationDependent() ||
8823 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008824 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008825 (X->isInstantiationDependent() || X->getType()->isScalarType())
8826 ? E
8827 : X;
8828 ErrorFound = NotAScalarType;
8829 ErrorLoc = AtomicBinOp->getExprLoc();
8830 ErrorRange = AtomicBinOp->getSourceRange();
8831 NoteLoc = NotScalarExpr->getExprLoc();
8832 NoteRange = NotScalarExpr->getSourceRange();
8833 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008834 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008835 ErrorFound = NotAnAssignmentOp;
8836 ErrorLoc = AtomicBody->getExprLoc();
8837 ErrorRange = AtomicBody->getSourceRange();
8838 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8839 : AtomicBody->getExprLoc();
8840 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8841 : AtomicBody->getSourceRange();
8842 }
8843 } else {
8844 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008845 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008846 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008847 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008848 if (ErrorFound != NoError) {
8849 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8850 << ErrorRange;
8851 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8852 << NoteRange;
8853 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008854 }
8855 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008856 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008857 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008858 // If clause is update:
8859 // x++;
8860 // x--;
8861 // ++x;
8862 // --x;
8863 // x binop= expr;
8864 // x = x binop expr;
8865 // x = expr binop x;
8866 OpenMPAtomicUpdateChecker Checker(*this);
8867 if (Checker.checkStatement(
8868 Body, (AtomicKind == OMPC_update)
8869 ? diag::err_omp_atomic_update_not_expression_statement
8870 : diag::err_omp_atomic_not_expression_statement,
8871 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008872 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008873 if (!CurContext->isDependentContext()) {
8874 E = Checker.getExpr();
8875 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008876 UE = Checker.getUpdateExpr();
8877 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008878 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008879 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008880 enum {
8881 NotAnAssignmentOp,
8882 NotACompoundStatement,
8883 NotTwoSubstatements,
8884 NotASpecificExpression,
8885 NoError
8886 } ErrorFound = NoError;
8887 SourceLocation ErrorLoc, NoteLoc;
8888 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008889 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008890 // If clause is a capture:
8891 // v = x++;
8892 // v = x--;
8893 // v = ++x;
8894 // v = --x;
8895 // v = x binop= expr;
8896 // v = x = x binop expr;
8897 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008898 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008899 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8900 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8901 V = AtomicBinOp->getLHS();
8902 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8903 OpenMPAtomicUpdateChecker Checker(*this);
8904 if (Checker.checkStatement(
8905 Body, diag::err_omp_atomic_capture_not_expression_statement,
8906 diag::note_omp_atomic_update))
8907 return StmtError();
8908 E = Checker.getExpr();
8909 X = Checker.getX();
8910 UE = Checker.getUpdateExpr();
8911 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8912 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008913 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008914 ErrorLoc = AtomicBody->getExprLoc();
8915 ErrorRange = AtomicBody->getSourceRange();
8916 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8917 : AtomicBody->getExprLoc();
8918 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8919 : AtomicBody->getSourceRange();
8920 ErrorFound = NotAnAssignmentOp;
8921 }
8922 if (ErrorFound != NoError) {
8923 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8924 << ErrorRange;
8925 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8926 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008927 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008928 if (CurContext->isDependentContext())
8929 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008930 } else {
8931 // If clause is a capture:
8932 // { v = x; x = expr; }
8933 // { v = x; x++; }
8934 // { v = x; x--; }
8935 // { v = x; ++x; }
8936 // { v = x; --x; }
8937 // { v = x; x binop= expr; }
8938 // { v = x; x = x binop expr; }
8939 // { v = x; x = expr binop x; }
8940 // { x++; v = x; }
8941 // { x--; v = x; }
8942 // { ++x; v = x; }
8943 // { --x; v = x; }
8944 // { x binop= expr; v = x; }
8945 // { x = x binop expr; v = x; }
8946 // { x = expr binop x; v = x; }
8947 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8948 // Check that this is { expr1; expr2; }
8949 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008950 Stmt *First = CS->body_front();
8951 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008952 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8953 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8954 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8955 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8956 // Need to find what subexpression is 'v' and what is 'x'.
8957 OpenMPAtomicUpdateChecker Checker(*this);
8958 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8959 BinaryOperator *BinOp = nullptr;
8960 if (IsUpdateExprFound) {
8961 BinOp = dyn_cast<BinaryOperator>(First);
8962 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8963 }
8964 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8965 // { v = x; x++; }
8966 // { v = x; x--; }
8967 // { v = x; ++x; }
8968 // { v = x; --x; }
8969 // { v = x; x binop= expr; }
8970 // { v = x; x = x binop expr; }
8971 // { v = x; x = expr binop x; }
8972 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008973 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008974 llvm::FoldingSetNodeID XId, PossibleXId;
8975 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8976 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8977 IsUpdateExprFound = XId == PossibleXId;
8978 if (IsUpdateExprFound) {
8979 V = BinOp->getLHS();
8980 X = Checker.getX();
8981 E = Checker.getExpr();
8982 UE = Checker.getUpdateExpr();
8983 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008984 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008985 }
8986 }
8987 if (!IsUpdateExprFound) {
8988 IsUpdateExprFound = !Checker.checkStatement(First);
8989 BinOp = nullptr;
8990 if (IsUpdateExprFound) {
8991 BinOp = dyn_cast<BinaryOperator>(Second);
8992 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8993 }
8994 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8995 // { x++; v = x; }
8996 // { x--; v = x; }
8997 // { ++x; v = x; }
8998 // { --x; v = x; }
8999 // { x binop= expr; v = x; }
9000 // { x = x binop expr; v = x; }
9001 // { x = expr binop x; v = x; }
9002 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009003 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009004 llvm::FoldingSetNodeID XId, PossibleXId;
9005 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9006 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9007 IsUpdateExprFound = XId == PossibleXId;
9008 if (IsUpdateExprFound) {
9009 V = BinOp->getLHS();
9010 X = Checker.getX();
9011 E = Checker.getExpr();
9012 UE = Checker.getUpdateExpr();
9013 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009014 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009015 }
9016 }
9017 }
9018 if (!IsUpdateExprFound) {
9019 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009020 auto *FirstExpr = dyn_cast<Expr>(First);
9021 auto *SecondExpr = dyn_cast<Expr>(Second);
9022 if (!FirstExpr || !SecondExpr ||
9023 !(FirstExpr->isInstantiationDependent() ||
9024 SecondExpr->isInstantiationDependent())) {
9025 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9026 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009027 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009028 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009029 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009030 NoteRange = ErrorRange = FirstBinOp
9031 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009032 : SourceRange(ErrorLoc, ErrorLoc);
9033 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009034 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9035 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9036 ErrorFound = NotAnAssignmentOp;
9037 NoteLoc = ErrorLoc = SecondBinOp
9038 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009039 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009040 NoteRange = ErrorRange =
9041 SecondBinOp ? SecondBinOp->getSourceRange()
9042 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009043 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009044 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009045 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009046 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009047 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9048 llvm::FoldingSetNodeID X1Id, X2Id;
9049 PossibleXRHSInFirst->Profile(X1Id, Context,
9050 /*Canonical=*/true);
9051 PossibleXLHSInSecond->Profile(X2Id, Context,
9052 /*Canonical=*/true);
9053 IsUpdateExprFound = X1Id == X2Id;
9054 if (IsUpdateExprFound) {
9055 V = FirstBinOp->getLHS();
9056 X = SecondBinOp->getLHS();
9057 E = SecondBinOp->getRHS();
9058 UE = nullptr;
9059 IsXLHSInRHSPart = false;
9060 IsPostfixUpdate = true;
9061 } else {
9062 ErrorFound = NotASpecificExpression;
9063 ErrorLoc = FirstBinOp->getExprLoc();
9064 ErrorRange = FirstBinOp->getSourceRange();
9065 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9066 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9067 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009068 }
9069 }
9070 }
9071 }
9072 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009073 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009074 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009075 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009076 ErrorFound = NotTwoSubstatements;
9077 }
9078 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009079 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009080 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009081 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009082 ErrorFound = NotACompoundStatement;
9083 }
9084 if (ErrorFound != NoError) {
9085 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9086 << ErrorRange;
9087 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9088 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009089 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009090 if (CurContext->isDependentContext())
9091 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009092 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009093 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009094
Reid Kleckner87a31802018-03-12 21:43:02 +00009095 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009096
Alexey Bataev62cec442014-11-18 10:14:22 +00009097 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009098 X, V, E, UE, IsXLHSInRHSPart,
9099 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009100}
9101
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009102StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9103 Stmt *AStmt,
9104 SourceLocation StartLoc,
9105 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009106 if (!AStmt)
9107 return StmtError();
9108
Alexey Bataeve3727102018-04-18 15:57:46 +00009109 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009110 // 1.2.2 OpenMP Language Terminology
9111 // Structured block - An executable statement with a single entry at the
9112 // top and a single exit at the bottom.
9113 // The point of exit cannot be a branch out of the structured block.
9114 // longjmp() and throw() must not violate the entry/exit criteria.
9115 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009116 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9117 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9118 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9119 // 1.2.2 OpenMP Language Terminology
9120 // Structured block - An executable statement with a single entry at the
9121 // top and a single exit at the bottom.
9122 // The point of exit cannot be a branch out of the structured block.
9123 // longjmp() and throw() must not violate the entry/exit criteria.
9124 CS->getCapturedDecl()->setNothrow();
9125 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009126
Alexey Bataev13314bf2014-10-09 04:18:56 +00009127 // OpenMP [2.16, Nesting of Regions]
9128 // If specified, a teams construct must be contained within a target
9129 // construct. That target construct must contain no statements or directives
9130 // outside of the teams construct.
9131 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009132 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009133 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009134 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009135 auto I = CS->body_begin();
9136 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009137 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009138 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9139 OMPTeamsFound) {
9140
Alexey Bataev13314bf2014-10-09 04:18:56 +00009141 OMPTeamsFound = false;
9142 break;
9143 }
9144 ++I;
9145 }
9146 assert(I != CS->body_end() && "Not found statement");
9147 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009148 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009149 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009150 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009151 }
9152 if (!OMPTeamsFound) {
9153 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9154 Diag(DSAStack->getInnerTeamsRegionLoc(),
9155 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009156 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009157 << isa<OMPExecutableDirective>(S);
9158 return StmtError();
9159 }
9160 }
9161
Reid Kleckner87a31802018-03-12 21:43:02 +00009162 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009163
9164 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9165}
9166
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009167StmtResult
9168Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9169 Stmt *AStmt, SourceLocation StartLoc,
9170 SourceLocation EndLoc) {
9171 if (!AStmt)
9172 return StmtError();
9173
Alexey Bataeve3727102018-04-18 15:57:46 +00009174 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009175 // 1.2.2 OpenMP Language Terminology
9176 // Structured block - An executable statement with a single entry at the
9177 // top and a single exit at the bottom.
9178 // The point of exit cannot be a branch out of the structured block.
9179 // longjmp() and throw() must not violate the entry/exit criteria.
9180 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009181 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9182 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9183 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9184 // 1.2.2 OpenMP Language Terminology
9185 // Structured block - An executable statement with a single entry at the
9186 // top and a single exit at the bottom.
9187 // The point of exit cannot be a branch out of the structured block.
9188 // longjmp() and throw() must not violate the entry/exit criteria.
9189 CS->getCapturedDecl()->setNothrow();
9190 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009191
Reid Kleckner87a31802018-03-12 21:43:02 +00009192 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009193
9194 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9195 AStmt);
9196}
9197
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009198StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9199 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009200 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009201 if (!AStmt)
9202 return StmtError();
9203
Alexey Bataeve3727102018-04-18 15:57:46 +00009204 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009205 // 1.2.2 OpenMP Language Terminology
9206 // Structured block - An executable statement with a single entry at the
9207 // top and a single exit at the bottom.
9208 // The point of exit cannot be a branch out of the structured block.
9209 // longjmp() and throw() must not violate the entry/exit criteria.
9210 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009211 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9212 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9213 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9214 // 1.2.2 OpenMP Language Terminology
9215 // Structured block - An executable statement with a single entry at the
9216 // top and a single exit at the bottom.
9217 // The point of exit cannot be a branch out of the structured block.
9218 // longjmp() and throw() must not violate the entry/exit criteria.
9219 CS->getCapturedDecl()->setNothrow();
9220 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009221
9222 OMPLoopDirective::HelperExprs B;
9223 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9224 // define the nested loops number.
9225 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009226 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009227 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009228 VarsWithImplicitDSA, B);
9229 if (NestedLoopCount == 0)
9230 return StmtError();
9231
9232 assert((CurContext->isDependentContext() || B.builtAll()) &&
9233 "omp target parallel for loop exprs were not built");
9234
9235 if (!CurContext->isDependentContext()) {
9236 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009237 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009238 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009239 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009240 B.NumIterations, *this, CurScope,
9241 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009242 return StmtError();
9243 }
9244 }
9245
Reid Kleckner87a31802018-03-12 21:43:02 +00009246 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009247 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9248 NestedLoopCount, Clauses, AStmt,
9249 B, DSAStack->isCancelRegion());
9250}
9251
Alexey Bataev95b64a92017-05-30 16:00:04 +00009252/// Check for existence of a map clause in the list of clauses.
9253static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9254 const OpenMPClauseKind K) {
9255 return llvm::any_of(
9256 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9257}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009258
Alexey Bataev95b64a92017-05-30 16:00:04 +00009259template <typename... Params>
9260static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9261 const Params... ClauseTypes) {
9262 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009263}
9264
Michael Wong65f367f2015-07-21 13:44:28 +00009265StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9266 Stmt *AStmt,
9267 SourceLocation StartLoc,
9268 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009269 if (!AStmt)
9270 return StmtError();
9271
9272 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9273
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009274 // OpenMP [2.10.1, Restrictions, p. 97]
9275 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009276 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9277 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9278 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009279 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009280 return StmtError();
9281 }
9282
Reid Kleckner87a31802018-03-12 21:43:02 +00009283 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009284
9285 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9286 AStmt);
9287}
9288
Samuel Antaodf67fc42016-01-19 19:15:56 +00009289StmtResult
9290Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9291 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009292 SourceLocation EndLoc, Stmt *AStmt) {
9293 if (!AStmt)
9294 return StmtError();
9295
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009297 // 1.2.2 OpenMP Language Terminology
9298 // Structured block - An executable statement with a single entry at the
9299 // top and a single exit at the bottom.
9300 // The point of exit cannot be a branch out of the structured block.
9301 // longjmp() and throw() must not violate the entry/exit criteria.
9302 CS->getCapturedDecl()->setNothrow();
9303 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9304 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9305 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9306 // 1.2.2 OpenMP Language Terminology
9307 // Structured block - An executable statement with a single entry at the
9308 // top and a single exit at the bottom.
9309 // The point of exit cannot be a branch out of the structured block.
9310 // longjmp() and throw() must not violate the entry/exit criteria.
9311 CS->getCapturedDecl()->setNothrow();
9312 }
9313
Samuel Antaodf67fc42016-01-19 19:15:56 +00009314 // OpenMP [2.10.2, Restrictions, p. 99]
9315 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009316 if (!hasClauses(Clauses, OMPC_map)) {
9317 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9318 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009319 return StmtError();
9320 }
9321
Alexey Bataev7828b252017-11-21 17:08:48 +00009322 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9323 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009324}
9325
Samuel Antao72590762016-01-19 20:04:50 +00009326StmtResult
9327Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9328 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009329 SourceLocation EndLoc, Stmt *AStmt) {
9330 if (!AStmt)
9331 return StmtError();
9332
Alexey Bataeve3727102018-04-18 15:57:46 +00009333 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009334 // 1.2.2 OpenMP Language Terminology
9335 // Structured block - An executable statement with a single entry at the
9336 // top and a single exit at the bottom.
9337 // The point of exit cannot be a branch out of the structured block.
9338 // longjmp() and throw() must not violate the entry/exit criteria.
9339 CS->getCapturedDecl()->setNothrow();
9340 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9341 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9342 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9343 // 1.2.2 OpenMP Language Terminology
9344 // Structured block - An executable statement with a single entry at the
9345 // top and a single exit at the bottom.
9346 // The point of exit cannot be a branch out of the structured block.
9347 // longjmp() and throw() must not violate the entry/exit criteria.
9348 CS->getCapturedDecl()->setNothrow();
9349 }
9350
Samuel Antao72590762016-01-19 20:04:50 +00009351 // OpenMP [2.10.3, Restrictions, p. 102]
9352 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009353 if (!hasClauses(Clauses, OMPC_map)) {
9354 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9355 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009356 return StmtError();
9357 }
9358
Alexey Bataev7828b252017-11-21 17:08:48 +00009359 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9360 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009361}
9362
Samuel Antao686c70c2016-05-26 17:30:50 +00009363StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9364 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009365 SourceLocation EndLoc,
9366 Stmt *AStmt) {
9367 if (!AStmt)
9368 return StmtError();
9369
Alexey Bataeve3727102018-04-18 15:57:46 +00009370 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009371 // 1.2.2 OpenMP Language Terminology
9372 // Structured block - An executable statement with a single entry at the
9373 // top and a single exit at the bottom.
9374 // The point of exit cannot be a branch out of the structured block.
9375 // longjmp() and throw() must not violate the entry/exit criteria.
9376 CS->getCapturedDecl()->setNothrow();
9377 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9378 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9379 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9380 // 1.2.2 OpenMP Language Terminology
9381 // Structured block - An executable statement with a single entry at the
9382 // top and a single exit at the bottom.
9383 // The point of exit cannot be a branch out of the structured block.
9384 // longjmp() and throw() must not violate the entry/exit criteria.
9385 CS->getCapturedDecl()->setNothrow();
9386 }
9387
Alexey Bataev95b64a92017-05-30 16:00:04 +00009388 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009389 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9390 return StmtError();
9391 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009392 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9393 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009394}
9395
Alexey Bataev13314bf2014-10-09 04:18:56 +00009396StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9397 Stmt *AStmt, SourceLocation StartLoc,
9398 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009399 if (!AStmt)
9400 return StmtError();
9401
Alexey Bataeve3727102018-04-18 15:57:46 +00009402 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009403 // 1.2.2 OpenMP Language Terminology
9404 // Structured block - An executable statement with a single entry at the
9405 // top and a single exit at the bottom.
9406 // The point of exit cannot be a branch out of the structured block.
9407 // longjmp() and throw() must not violate the entry/exit criteria.
9408 CS->getCapturedDecl()->setNothrow();
9409
Reid Kleckner87a31802018-03-12 21:43:02 +00009410 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009411
Alexey Bataevceabd412017-11-30 18:01:54 +00009412 DSAStack->setParentTeamsRegionLoc(StartLoc);
9413
Alexey Bataev13314bf2014-10-09 04:18:56 +00009414 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9415}
9416
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009417StmtResult
9418Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9419 SourceLocation EndLoc,
9420 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009421 if (DSAStack->isParentNowaitRegion()) {
9422 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9423 return StmtError();
9424 }
9425 if (DSAStack->isParentOrderedRegion()) {
9426 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9427 return StmtError();
9428 }
9429 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9430 CancelRegion);
9431}
9432
Alexey Bataev87933c72015-09-18 08:07:34 +00009433StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9434 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009435 SourceLocation EndLoc,
9436 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009437 if (DSAStack->isParentNowaitRegion()) {
9438 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9439 return StmtError();
9440 }
9441 if (DSAStack->isParentOrderedRegion()) {
9442 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9443 return StmtError();
9444 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009445 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009446 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9447 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009448}
9449
Alexey Bataev382967a2015-12-08 12:06:20 +00009450static bool checkGrainsizeNumTasksClauses(Sema &S,
9451 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009452 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009453 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009454 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009455 if (C->getClauseKind() == OMPC_grainsize ||
9456 C->getClauseKind() == OMPC_num_tasks) {
9457 if (!PrevClause)
9458 PrevClause = C;
9459 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009460 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009461 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9462 << getOpenMPClauseName(C->getClauseKind())
9463 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009464 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009465 diag::note_omp_previous_grainsize_num_tasks)
9466 << getOpenMPClauseName(PrevClause->getClauseKind());
9467 ErrorFound = true;
9468 }
9469 }
9470 }
9471 return ErrorFound;
9472}
9473
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009474static bool checkReductionClauseWithNogroup(Sema &S,
9475 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009476 const OMPClause *ReductionClause = nullptr;
9477 const OMPClause *NogroupClause = nullptr;
9478 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009479 if (C->getClauseKind() == OMPC_reduction) {
9480 ReductionClause = C;
9481 if (NogroupClause)
9482 break;
9483 continue;
9484 }
9485 if (C->getClauseKind() == OMPC_nogroup) {
9486 NogroupClause = C;
9487 if (ReductionClause)
9488 break;
9489 continue;
9490 }
9491 }
9492 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009493 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9494 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009495 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009496 return true;
9497 }
9498 return false;
9499}
9500
Alexey Bataev49f6e782015-12-01 04:18:41 +00009501StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9502 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009503 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009504 if (!AStmt)
9505 return StmtError();
9506
9507 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9508 OMPLoopDirective::HelperExprs B;
9509 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9510 // define the nested loops number.
9511 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009512 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009513 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009514 VarsWithImplicitDSA, B);
9515 if (NestedLoopCount == 0)
9516 return StmtError();
9517
9518 assert((CurContext->isDependentContext() || B.builtAll()) &&
9519 "omp for loop exprs were not built");
9520
Alexey Bataev382967a2015-12-08 12:06:20 +00009521 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9522 // The grainsize clause and num_tasks clause are mutually exclusive and may
9523 // not appear on the same taskloop directive.
9524 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9525 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009526 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9527 // If a reduction clause is present on the taskloop directive, the nogroup
9528 // clause must not be specified.
9529 if (checkReductionClauseWithNogroup(*this, Clauses))
9530 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009531
Reid Kleckner87a31802018-03-12 21:43:02 +00009532 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009533 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9534 NestedLoopCount, Clauses, AStmt, B);
9535}
9536
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009537StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9538 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009539 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009540 if (!AStmt)
9541 return StmtError();
9542
9543 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9544 OMPLoopDirective::HelperExprs B;
9545 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9546 // define the nested loops number.
9547 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009548 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009549 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9550 VarsWithImplicitDSA, B);
9551 if (NestedLoopCount == 0)
9552 return StmtError();
9553
9554 assert((CurContext->isDependentContext() || B.builtAll()) &&
9555 "omp for loop exprs were not built");
9556
Alexey Bataev5a3af132016-03-29 08:58:54 +00009557 if (!CurContext->isDependentContext()) {
9558 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009559 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009560 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009561 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009562 B.NumIterations, *this, CurScope,
9563 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009564 return StmtError();
9565 }
9566 }
9567
Alexey Bataev382967a2015-12-08 12:06:20 +00009568 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9569 // The grainsize clause and num_tasks clause are mutually exclusive and may
9570 // not appear on the same taskloop directive.
9571 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9572 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009573 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9574 // If a reduction clause is present on the taskloop directive, the nogroup
9575 // clause must not be specified.
9576 if (checkReductionClauseWithNogroup(*this, Clauses))
9577 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009578 if (checkSimdlenSafelenSpecified(*this, Clauses))
9579 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009580
Reid Kleckner87a31802018-03-12 21:43:02 +00009581 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009582 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9583 NestedLoopCount, Clauses, AStmt, B);
9584}
9585
Alexey Bataev60e51c42019-10-10 20:13:02 +00009586StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9588 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9589 if (!AStmt)
9590 return StmtError();
9591
9592 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9593 OMPLoopDirective::HelperExprs B;
9594 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9595 // define the nested loops number.
9596 unsigned NestedLoopCount =
9597 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9598 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9599 VarsWithImplicitDSA, B);
9600 if (NestedLoopCount == 0)
9601 return StmtError();
9602
9603 assert((CurContext->isDependentContext() || B.builtAll()) &&
9604 "omp for loop exprs were not built");
9605
9606 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9607 // The grainsize clause and num_tasks clause are mutually exclusive and may
9608 // not appear on the same taskloop directive.
9609 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9610 return StmtError();
9611 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9612 // If a reduction clause is present on the taskloop directive, the nogroup
9613 // clause must not be specified.
9614 if (checkReductionClauseWithNogroup(*this, Clauses))
9615 return StmtError();
9616
9617 setFunctionHasBranchProtectedScope();
9618 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9619 NestedLoopCount, Clauses, AStmt, B);
9620}
9621
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009622StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9623 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9624 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9625 if (!AStmt)
9626 return StmtError();
9627
9628 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9629 OMPLoopDirective::HelperExprs B;
9630 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9631 // define the nested loops number.
9632 unsigned NestedLoopCount =
9633 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9634 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9635 VarsWithImplicitDSA, B);
9636 if (NestedLoopCount == 0)
9637 return StmtError();
9638
9639 assert((CurContext->isDependentContext() || B.builtAll()) &&
9640 "omp for loop exprs were not built");
9641
9642 if (!CurContext->isDependentContext()) {
9643 // Finalize the clauses that need pre-built expressions for CodeGen.
9644 for (OMPClause *C : Clauses) {
9645 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9646 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9647 B.NumIterations, *this, CurScope,
9648 DSAStack))
9649 return StmtError();
9650 }
9651 }
9652
9653 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9654 // The grainsize clause and num_tasks clause are mutually exclusive and may
9655 // not appear on the same taskloop directive.
9656 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9657 return StmtError();
9658 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9659 // If a reduction clause is present on the taskloop directive, the nogroup
9660 // clause must not be specified.
9661 if (checkReductionClauseWithNogroup(*this, Clauses))
9662 return StmtError();
9663 if (checkSimdlenSafelenSpecified(*this, Clauses))
9664 return StmtError();
9665
9666 setFunctionHasBranchProtectedScope();
9667 return OMPMasterTaskLoopSimdDirective::Create(
9668 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9669}
9670
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009671StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9673 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9674 if (!AStmt)
9675 return StmtError();
9676
9677 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9678 auto *CS = cast<CapturedStmt>(AStmt);
9679 // 1.2.2 OpenMP Language Terminology
9680 // Structured block - An executable statement with a single entry at the
9681 // top and a single exit at the bottom.
9682 // The point of exit cannot be a branch out of the structured block.
9683 // longjmp() and throw() must not violate the entry/exit criteria.
9684 CS->getCapturedDecl()->setNothrow();
9685 for (int ThisCaptureLevel =
9686 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9687 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9688 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9689 // 1.2.2 OpenMP Language Terminology
9690 // Structured block - An executable statement with a single entry at the
9691 // top and a single exit at the bottom.
9692 // The point of exit cannot be a branch out of the structured block.
9693 // longjmp() and throw() must not violate the entry/exit criteria.
9694 CS->getCapturedDecl()->setNothrow();
9695 }
9696
9697 OMPLoopDirective::HelperExprs B;
9698 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9699 // define the nested loops number.
9700 unsigned NestedLoopCount = checkOpenMPLoop(
9701 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9702 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9703 VarsWithImplicitDSA, B);
9704 if (NestedLoopCount == 0)
9705 return StmtError();
9706
9707 assert((CurContext->isDependentContext() || B.builtAll()) &&
9708 "omp for loop exprs were not built");
9709
9710 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9711 // The grainsize clause and num_tasks clause are mutually exclusive and may
9712 // not appear on the same taskloop directive.
9713 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9714 return StmtError();
9715 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9716 // If a reduction clause is present on the taskloop directive, the nogroup
9717 // clause must not be specified.
9718 if (checkReductionClauseWithNogroup(*this, Clauses))
9719 return StmtError();
9720
9721 setFunctionHasBranchProtectedScope();
9722 return OMPParallelMasterTaskLoopDirective::Create(
9723 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9724}
9725
Alexey Bataev14a388f2019-10-25 10:27:13 -04009726StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9727 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9728 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9729 if (!AStmt)
9730 return StmtError();
9731
9732 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9733 auto *CS = cast<CapturedStmt>(AStmt);
9734 // 1.2.2 OpenMP Language Terminology
9735 // Structured block - An executable statement with a single entry at the
9736 // top and a single exit at the bottom.
9737 // The point of exit cannot be a branch out of the structured block.
9738 // longjmp() and throw() must not violate the entry/exit criteria.
9739 CS->getCapturedDecl()->setNothrow();
9740 for (int ThisCaptureLevel =
9741 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9742 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9743 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9744 // 1.2.2 OpenMP Language Terminology
9745 // Structured block - An executable statement with a single entry at the
9746 // top and a single exit at the bottom.
9747 // The point of exit cannot be a branch out of the structured block.
9748 // longjmp() and throw() must not violate the entry/exit criteria.
9749 CS->getCapturedDecl()->setNothrow();
9750 }
9751
9752 OMPLoopDirective::HelperExprs B;
9753 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9754 // define the nested loops number.
9755 unsigned NestedLoopCount = checkOpenMPLoop(
9756 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9757 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9758 VarsWithImplicitDSA, B);
9759 if (NestedLoopCount == 0)
9760 return StmtError();
9761
9762 assert((CurContext->isDependentContext() || B.builtAll()) &&
9763 "omp for loop exprs were not built");
9764
9765 if (!CurContext->isDependentContext()) {
9766 // Finalize the clauses that need pre-built expressions for CodeGen.
9767 for (OMPClause *C : Clauses) {
9768 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9769 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9770 B.NumIterations, *this, CurScope,
9771 DSAStack))
9772 return StmtError();
9773 }
9774 }
9775
9776 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9777 // The grainsize clause and num_tasks clause are mutually exclusive and may
9778 // not appear on the same taskloop directive.
9779 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9780 return StmtError();
9781 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9782 // If a reduction clause is present on the taskloop directive, the nogroup
9783 // clause must not be specified.
9784 if (checkReductionClauseWithNogroup(*this, Clauses))
9785 return StmtError();
9786 if (checkSimdlenSafelenSpecified(*this, Clauses))
9787 return StmtError();
9788
9789 setFunctionHasBranchProtectedScope();
9790 return OMPParallelMasterTaskLoopSimdDirective::Create(
9791 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9792}
9793
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009794StmtResult Sema::ActOnOpenMPDistributeDirective(
9795 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009796 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009797 if (!AStmt)
9798 return StmtError();
9799
9800 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9801 OMPLoopDirective::HelperExprs B;
9802 // In presence of clause 'collapse' with number of loops, it will
9803 // define the nested loops number.
9804 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009805 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009806 nullptr /*ordered not a clause on distribute*/, AStmt,
9807 *this, *DSAStack, VarsWithImplicitDSA, B);
9808 if (NestedLoopCount == 0)
9809 return StmtError();
9810
9811 assert((CurContext->isDependentContext() || B.builtAll()) &&
9812 "omp for loop exprs were not built");
9813
Reid Kleckner87a31802018-03-12 21:43:02 +00009814 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009815 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9816 NestedLoopCount, Clauses, AStmt, B);
9817}
9818
Carlo Bertolli9925f152016-06-27 14:55:37 +00009819StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9820 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009821 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009822 if (!AStmt)
9823 return StmtError();
9824
Alexey Bataeve3727102018-04-18 15:57:46 +00009825 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009826 // 1.2.2 OpenMP Language Terminology
9827 // Structured block - An executable statement with a single entry at the
9828 // top and a single exit at the bottom.
9829 // The point of exit cannot be a branch out of the structured block.
9830 // longjmp() and throw() must not violate the entry/exit criteria.
9831 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009832 for (int ThisCaptureLevel =
9833 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9834 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9835 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9836 // 1.2.2 OpenMP Language Terminology
9837 // Structured block - An executable statement with a single entry at the
9838 // top and a single exit at the bottom.
9839 // The point of exit cannot be a branch out of the structured block.
9840 // longjmp() and throw() must not violate the entry/exit criteria.
9841 CS->getCapturedDecl()->setNothrow();
9842 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009843
9844 OMPLoopDirective::HelperExprs B;
9845 // In presence of clause 'collapse' with number of loops, it will
9846 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009847 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009848 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009849 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009850 VarsWithImplicitDSA, B);
9851 if (NestedLoopCount == 0)
9852 return StmtError();
9853
9854 assert((CurContext->isDependentContext() || B.builtAll()) &&
9855 "omp for loop exprs were not built");
9856
Reid Kleckner87a31802018-03-12 21:43:02 +00009857 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009858 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009859 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9860 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009861}
9862
Kelvin Li4a39add2016-07-05 05:00:15 +00009863StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9864 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009865 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009866 if (!AStmt)
9867 return StmtError();
9868
Alexey Bataeve3727102018-04-18 15:57:46 +00009869 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009870 // 1.2.2 OpenMP Language Terminology
9871 // Structured block - An executable statement with a single entry at the
9872 // top and a single exit at the bottom.
9873 // The point of exit cannot be a branch out of the structured block.
9874 // longjmp() and throw() must not violate the entry/exit criteria.
9875 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009876 for (int ThisCaptureLevel =
9877 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9878 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9879 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9880 // 1.2.2 OpenMP Language Terminology
9881 // Structured block - An executable statement with a single entry at the
9882 // top and a single exit at the bottom.
9883 // The point of exit cannot be a branch out of the structured block.
9884 // longjmp() and throw() must not violate the entry/exit criteria.
9885 CS->getCapturedDecl()->setNothrow();
9886 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009887
9888 OMPLoopDirective::HelperExprs B;
9889 // In presence of clause 'collapse' with number of loops, it will
9890 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009891 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009892 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009893 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009894 VarsWithImplicitDSA, B);
9895 if (NestedLoopCount == 0)
9896 return StmtError();
9897
9898 assert((CurContext->isDependentContext() || B.builtAll()) &&
9899 "omp for loop exprs were not built");
9900
Alexey Bataev438388c2017-11-22 18:34:02 +00009901 if (!CurContext->isDependentContext()) {
9902 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009903 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009904 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9905 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9906 B.NumIterations, *this, CurScope,
9907 DSAStack))
9908 return StmtError();
9909 }
9910 }
9911
Kelvin Lic5609492016-07-15 04:39:07 +00009912 if (checkSimdlenSafelenSpecified(*this, Clauses))
9913 return StmtError();
9914
Reid Kleckner87a31802018-03-12 21:43:02 +00009915 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009916 return OMPDistributeParallelForSimdDirective::Create(
9917 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9918}
9919
Kelvin Li787f3fc2016-07-06 04:45:38 +00009920StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9921 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009922 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009923 if (!AStmt)
9924 return StmtError();
9925
Alexey Bataeve3727102018-04-18 15:57:46 +00009926 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009927 // 1.2.2 OpenMP Language Terminology
9928 // Structured block - An executable statement with a single entry at the
9929 // top and a single exit at the bottom.
9930 // The point of exit cannot be a branch out of the structured block.
9931 // longjmp() and throw() must not violate the entry/exit criteria.
9932 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009933 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9934 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9935 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9936 // 1.2.2 OpenMP Language Terminology
9937 // Structured block - An executable statement with a single entry at the
9938 // top and a single exit at the bottom.
9939 // The point of exit cannot be a branch out of the structured block.
9940 // longjmp() and throw() must not violate the entry/exit criteria.
9941 CS->getCapturedDecl()->setNothrow();
9942 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009943
9944 OMPLoopDirective::HelperExprs B;
9945 // In presence of clause 'collapse' with number of loops, it will
9946 // define the nested loops number.
9947 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009948 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009949 nullptr /*ordered not a clause on distribute*/, CS, *this,
9950 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009951 if (NestedLoopCount == 0)
9952 return StmtError();
9953
9954 assert((CurContext->isDependentContext() || B.builtAll()) &&
9955 "omp for loop exprs were not built");
9956
Alexey Bataev438388c2017-11-22 18:34:02 +00009957 if (!CurContext->isDependentContext()) {
9958 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009959 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009960 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9961 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9962 B.NumIterations, *this, CurScope,
9963 DSAStack))
9964 return StmtError();
9965 }
9966 }
9967
Kelvin Lic5609492016-07-15 04:39:07 +00009968 if (checkSimdlenSafelenSpecified(*this, Clauses))
9969 return StmtError();
9970
Reid Kleckner87a31802018-03-12 21:43:02 +00009971 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009972 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9973 NestedLoopCount, Clauses, AStmt, B);
9974}
9975
Kelvin Lia579b912016-07-14 02:54:56 +00009976StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9977 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009978 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009979 if (!AStmt)
9980 return StmtError();
9981
Alexey Bataeve3727102018-04-18 15:57:46 +00009982 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009983 // 1.2.2 OpenMP Language Terminology
9984 // Structured block - An executable statement with a single entry at the
9985 // top and a single exit at the bottom.
9986 // The point of exit cannot be a branch out of the structured block.
9987 // longjmp() and throw() must not violate the entry/exit criteria.
9988 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009989 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9990 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9991 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9992 // 1.2.2 OpenMP Language Terminology
9993 // Structured block - An executable statement with a single entry at the
9994 // top and a single exit at the bottom.
9995 // The point of exit cannot be a branch out of the structured block.
9996 // longjmp() and throw() must not violate the entry/exit criteria.
9997 CS->getCapturedDecl()->setNothrow();
9998 }
Kelvin Lia579b912016-07-14 02:54:56 +00009999
10000 OMPLoopDirective::HelperExprs B;
10001 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10002 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010003 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010004 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010005 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010006 VarsWithImplicitDSA, B);
10007 if (NestedLoopCount == 0)
10008 return StmtError();
10009
10010 assert((CurContext->isDependentContext() || B.builtAll()) &&
10011 "omp target parallel for simd loop exprs were not built");
10012
10013 if (!CurContext->isDependentContext()) {
10014 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010015 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010016 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010017 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10018 B.NumIterations, *this, CurScope,
10019 DSAStack))
10020 return StmtError();
10021 }
10022 }
Kelvin Lic5609492016-07-15 04:39:07 +000010023 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010024 return StmtError();
10025
Reid Kleckner87a31802018-03-12 21:43:02 +000010026 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010027 return OMPTargetParallelForSimdDirective::Create(
10028 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10029}
10030
Kelvin Li986330c2016-07-20 22:57:10 +000010031StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10032 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010033 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010034 if (!AStmt)
10035 return StmtError();
10036
Alexey Bataeve3727102018-04-18 15:57:46 +000010037 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010038 // 1.2.2 OpenMP Language Terminology
10039 // Structured block - An executable statement with a single entry at the
10040 // top and a single exit at the bottom.
10041 // The point of exit cannot be a branch out of the structured block.
10042 // longjmp() and throw() must not violate the entry/exit criteria.
10043 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010044 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10045 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10046 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10047 // 1.2.2 OpenMP Language Terminology
10048 // Structured block - An executable statement with a single entry at the
10049 // top and a single exit at the bottom.
10050 // The point of exit cannot be a branch out of the structured block.
10051 // longjmp() and throw() must not violate the entry/exit criteria.
10052 CS->getCapturedDecl()->setNothrow();
10053 }
10054
Kelvin Li986330c2016-07-20 22:57:10 +000010055 OMPLoopDirective::HelperExprs B;
10056 // In presence of clause 'collapse' with number of loops, it will define the
10057 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010058 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010059 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010060 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010061 VarsWithImplicitDSA, B);
10062 if (NestedLoopCount == 0)
10063 return StmtError();
10064
10065 assert((CurContext->isDependentContext() || B.builtAll()) &&
10066 "omp target simd loop exprs were not built");
10067
10068 if (!CurContext->isDependentContext()) {
10069 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010070 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010071 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010072 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10073 B.NumIterations, *this, CurScope,
10074 DSAStack))
10075 return StmtError();
10076 }
10077 }
10078
10079 if (checkSimdlenSafelenSpecified(*this, Clauses))
10080 return StmtError();
10081
Reid Kleckner87a31802018-03-12 21:43:02 +000010082 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010083 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10084 NestedLoopCount, Clauses, AStmt, B);
10085}
10086
Kelvin Li02532872016-08-05 14:37:37 +000010087StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10088 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010089 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010090 if (!AStmt)
10091 return StmtError();
10092
Alexey Bataeve3727102018-04-18 15:57:46 +000010093 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010094 // 1.2.2 OpenMP Language Terminology
10095 // Structured block - An executable statement with a single entry at the
10096 // top and a single exit at the bottom.
10097 // The point of exit cannot be a branch out of the structured block.
10098 // longjmp() and throw() must not violate the entry/exit criteria.
10099 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010100 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10101 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10102 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10103 // 1.2.2 OpenMP Language Terminology
10104 // Structured block - An executable statement with a single entry at the
10105 // top and a single exit at the bottom.
10106 // The point of exit cannot be a branch out of the structured block.
10107 // longjmp() and throw() must not violate the entry/exit criteria.
10108 CS->getCapturedDecl()->setNothrow();
10109 }
Kelvin Li02532872016-08-05 14:37:37 +000010110
10111 OMPLoopDirective::HelperExprs B;
10112 // In presence of clause 'collapse' with number of loops, it will
10113 // define the nested loops number.
10114 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010115 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010116 nullptr /*ordered not a clause on distribute*/, CS, *this,
10117 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010118 if (NestedLoopCount == 0)
10119 return StmtError();
10120
10121 assert((CurContext->isDependentContext() || B.builtAll()) &&
10122 "omp teams distribute loop exprs were not built");
10123
Reid Kleckner87a31802018-03-12 21:43:02 +000010124 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010125
10126 DSAStack->setParentTeamsRegionLoc(StartLoc);
10127
David Majnemer9d168222016-08-05 17:44:54 +000010128 return OMPTeamsDistributeDirective::Create(
10129 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010130}
10131
Kelvin Li4e325f72016-10-25 12:50:55 +000010132StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10133 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010134 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010135 if (!AStmt)
10136 return StmtError();
10137
Alexey Bataeve3727102018-04-18 15:57:46 +000010138 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010139 // 1.2.2 OpenMP Language Terminology
10140 // Structured block - An executable statement with a single entry at the
10141 // top and a single exit at the bottom.
10142 // The point of exit cannot be a branch out of the structured block.
10143 // longjmp() and throw() must not violate the entry/exit criteria.
10144 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010145 for (int ThisCaptureLevel =
10146 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10147 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10148 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10149 // 1.2.2 OpenMP Language Terminology
10150 // Structured block - An executable statement with a single entry at the
10151 // top and a single exit at the bottom.
10152 // The point of exit cannot be a branch out of the structured block.
10153 // longjmp() and throw() must not violate the entry/exit criteria.
10154 CS->getCapturedDecl()->setNothrow();
10155 }
10156
Kelvin Li4e325f72016-10-25 12:50:55 +000010157
10158 OMPLoopDirective::HelperExprs B;
10159 // In presence of clause 'collapse' with number of loops, it will
10160 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010161 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010162 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010163 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010164 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010165
10166 if (NestedLoopCount == 0)
10167 return StmtError();
10168
10169 assert((CurContext->isDependentContext() || B.builtAll()) &&
10170 "omp teams distribute simd loop exprs were not built");
10171
10172 if (!CurContext->isDependentContext()) {
10173 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010174 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010175 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10176 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10177 B.NumIterations, *this, CurScope,
10178 DSAStack))
10179 return StmtError();
10180 }
10181 }
10182
10183 if (checkSimdlenSafelenSpecified(*this, Clauses))
10184 return StmtError();
10185
Reid Kleckner87a31802018-03-12 21:43:02 +000010186 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010187
10188 DSAStack->setParentTeamsRegionLoc(StartLoc);
10189
Kelvin Li4e325f72016-10-25 12:50:55 +000010190 return OMPTeamsDistributeSimdDirective::Create(
10191 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10192}
10193
Kelvin Li579e41c2016-11-30 23:51:03 +000010194StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10195 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010196 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010197 if (!AStmt)
10198 return StmtError();
10199
Alexey Bataeve3727102018-04-18 15:57:46 +000010200 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010201 // 1.2.2 OpenMP Language Terminology
10202 // Structured block - An executable statement with a single entry at the
10203 // top and a single exit at the bottom.
10204 // The point of exit cannot be a branch out of the structured block.
10205 // longjmp() and throw() must not violate the entry/exit criteria.
10206 CS->getCapturedDecl()->setNothrow();
10207
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010208 for (int ThisCaptureLevel =
10209 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10210 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10211 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10212 // 1.2.2 OpenMP Language Terminology
10213 // Structured block - An executable statement with a single entry at the
10214 // top and a single exit at the bottom.
10215 // The point of exit cannot be a branch out of the structured block.
10216 // longjmp() and throw() must not violate the entry/exit criteria.
10217 CS->getCapturedDecl()->setNothrow();
10218 }
10219
Kelvin Li579e41c2016-11-30 23:51:03 +000010220 OMPLoopDirective::HelperExprs B;
10221 // In presence of clause 'collapse' with number of loops, it will
10222 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010223 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010224 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010225 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010226 VarsWithImplicitDSA, B);
10227
10228 if (NestedLoopCount == 0)
10229 return StmtError();
10230
10231 assert((CurContext->isDependentContext() || B.builtAll()) &&
10232 "omp for loop exprs were not built");
10233
10234 if (!CurContext->isDependentContext()) {
10235 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010236 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010237 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10238 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10239 B.NumIterations, *this, CurScope,
10240 DSAStack))
10241 return StmtError();
10242 }
10243 }
10244
10245 if (checkSimdlenSafelenSpecified(*this, Clauses))
10246 return StmtError();
10247
Reid Kleckner87a31802018-03-12 21:43:02 +000010248 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010249
10250 DSAStack->setParentTeamsRegionLoc(StartLoc);
10251
Kelvin Li579e41c2016-11-30 23:51:03 +000010252 return OMPTeamsDistributeParallelForSimdDirective::Create(
10253 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10254}
10255
Kelvin Li7ade93f2016-12-09 03:24:30 +000010256StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10257 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010258 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010259 if (!AStmt)
10260 return StmtError();
10261
Alexey Bataeve3727102018-04-18 15:57:46 +000010262 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010263 // 1.2.2 OpenMP Language Terminology
10264 // Structured block - An executable statement with a single entry at the
10265 // top and a single exit at the bottom.
10266 // The point of exit cannot be a branch out of the structured block.
10267 // longjmp() and throw() must not violate the entry/exit criteria.
10268 CS->getCapturedDecl()->setNothrow();
10269
Carlo Bertolli62fae152017-11-20 20:46:39 +000010270 for (int ThisCaptureLevel =
10271 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10272 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10273 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10274 // 1.2.2 OpenMP Language Terminology
10275 // Structured block - An executable statement with a single entry at the
10276 // top and a single exit at the bottom.
10277 // The point of exit cannot be a branch out of the structured block.
10278 // longjmp() and throw() must not violate the entry/exit criteria.
10279 CS->getCapturedDecl()->setNothrow();
10280 }
10281
Kelvin Li7ade93f2016-12-09 03:24:30 +000010282 OMPLoopDirective::HelperExprs B;
10283 // In presence of clause 'collapse' with number of loops, it will
10284 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010285 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010286 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010287 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010288 VarsWithImplicitDSA, B);
10289
10290 if (NestedLoopCount == 0)
10291 return StmtError();
10292
10293 assert((CurContext->isDependentContext() || B.builtAll()) &&
10294 "omp for loop exprs were not built");
10295
Reid Kleckner87a31802018-03-12 21:43:02 +000010296 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010297
10298 DSAStack->setParentTeamsRegionLoc(StartLoc);
10299
Kelvin Li7ade93f2016-12-09 03:24:30 +000010300 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010301 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10302 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010303}
10304
Kelvin Libf594a52016-12-17 05:48:59 +000010305StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10306 Stmt *AStmt,
10307 SourceLocation StartLoc,
10308 SourceLocation EndLoc) {
10309 if (!AStmt)
10310 return StmtError();
10311
Alexey Bataeve3727102018-04-18 15:57:46 +000010312 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010313 // 1.2.2 OpenMP Language Terminology
10314 // Structured block - An executable statement with a single entry at the
10315 // top and a single exit at the bottom.
10316 // The point of exit cannot be a branch out of the structured block.
10317 // longjmp() and throw() must not violate the entry/exit criteria.
10318 CS->getCapturedDecl()->setNothrow();
10319
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010320 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10321 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10322 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10323 // 1.2.2 OpenMP Language Terminology
10324 // Structured block - An executable statement with a single entry at the
10325 // top and a single exit at the bottom.
10326 // The point of exit cannot be a branch out of the structured block.
10327 // longjmp() and throw() must not violate the entry/exit criteria.
10328 CS->getCapturedDecl()->setNothrow();
10329 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010330 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010331
10332 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10333 AStmt);
10334}
10335
Kelvin Li83c451e2016-12-25 04:52:54 +000010336StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10337 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010338 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010339 if (!AStmt)
10340 return StmtError();
10341
Alexey Bataeve3727102018-04-18 15:57:46 +000010342 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010343 // 1.2.2 OpenMP Language Terminology
10344 // Structured block - An executable statement with a single entry at the
10345 // top and a single exit at the bottom.
10346 // The point of exit cannot be a branch out of the structured block.
10347 // longjmp() and throw() must not violate the entry/exit criteria.
10348 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010349 for (int ThisCaptureLevel =
10350 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10351 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10352 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10353 // 1.2.2 OpenMP Language Terminology
10354 // Structured block - An executable statement with a single entry at the
10355 // top and a single exit at the bottom.
10356 // The point of exit cannot be a branch out of the structured block.
10357 // longjmp() and throw() must not violate the entry/exit criteria.
10358 CS->getCapturedDecl()->setNothrow();
10359 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010360
10361 OMPLoopDirective::HelperExprs B;
10362 // In presence of clause 'collapse' with number of loops, it will
10363 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010364 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010365 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10366 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010367 VarsWithImplicitDSA, B);
10368 if (NestedLoopCount == 0)
10369 return StmtError();
10370
10371 assert((CurContext->isDependentContext() || B.builtAll()) &&
10372 "omp target teams distribute loop exprs were not built");
10373
Reid Kleckner87a31802018-03-12 21:43:02 +000010374 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010375 return OMPTargetTeamsDistributeDirective::Create(
10376 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10377}
10378
Kelvin Li80e8f562016-12-29 22:16:30 +000010379StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10380 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010381 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010382 if (!AStmt)
10383 return StmtError();
10384
Alexey Bataeve3727102018-04-18 15:57:46 +000010385 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010386 // 1.2.2 OpenMP Language Terminology
10387 // Structured block - An executable statement with a single entry at the
10388 // top and a single exit at the bottom.
10389 // The point of exit cannot be a branch out of the structured block.
10390 // longjmp() and throw() must not violate the entry/exit criteria.
10391 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010392 for (int ThisCaptureLevel =
10393 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10394 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10395 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10396 // 1.2.2 OpenMP Language Terminology
10397 // Structured block - An executable statement with a single entry at the
10398 // top and a single exit at the bottom.
10399 // The point of exit cannot be a branch out of the structured block.
10400 // longjmp() and throw() must not violate the entry/exit criteria.
10401 CS->getCapturedDecl()->setNothrow();
10402 }
10403
Kelvin Li80e8f562016-12-29 22:16:30 +000010404 OMPLoopDirective::HelperExprs B;
10405 // In presence of clause 'collapse' with number of loops, it will
10406 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010407 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010408 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10409 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010410 VarsWithImplicitDSA, B);
10411 if (NestedLoopCount == 0)
10412 return StmtError();
10413
10414 assert((CurContext->isDependentContext() || B.builtAll()) &&
10415 "omp target teams distribute parallel for loop exprs were not built");
10416
Alexey Bataev647dd842018-01-15 20:59:40 +000010417 if (!CurContext->isDependentContext()) {
10418 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010419 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010420 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10421 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10422 B.NumIterations, *this, CurScope,
10423 DSAStack))
10424 return StmtError();
10425 }
10426 }
10427
Reid Kleckner87a31802018-03-12 21:43:02 +000010428 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010429 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010430 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10431 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010432}
10433
Kelvin Li1851df52017-01-03 05:23:48 +000010434StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10435 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010436 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010437 if (!AStmt)
10438 return StmtError();
10439
Alexey Bataeve3727102018-04-18 15:57:46 +000010440 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010441 // 1.2.2 OpenMP Language Terminology
10442 // Structured block - An executable statement with a single entry at the
10443 // top and a single exit at the bottom.
10444 // The point of exit cannot be a branch out of the structured block.
10445 // longjmp() and throw() must not violate the entry/exit criteria.
10446 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010447 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10448 OMPD_target_teams_distribute_parallel_for_simd);
10449 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10450 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10451 // 1.2.2 OpenMP Language Terminology
10452 // Structured block - An executable statement with a single entry at the
10453 // top and a single exit at the bottom.
10454 // The point of exit cannot be a branch out of the structured block.
10455 // longjmp() and throw() must not violate the entry/exit criteria.
10456 CS->getCapturedDecl()->setNothrow();
10457 }
Kelvin Li1851df52017-01-03 05:23:48 +000010458
10459 OMPLoopDirective::HelperExprs B;
10460 // In presence of clause 'collapse' with number of loops, it will
10461 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010462 unsigned NestedLoopCount =
10463 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010464 getCollapseNumberExpr(Clauses),
10465 nullptr /*ordered not a clause on distribute*/, CS, *this,
10466 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010467 if (NestedLoopCount == 0)
10468 return StmtError();
10469
10470 assert((CurContext->isDependentContext() || B.builtAll()) &&
10471 "omp target teams distribute parallel for simd loop exprs were not "
10472 "built");
10473
10474 if (!CurContext->isDependentContext()) {
10475 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010476 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010477 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10478 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10479 B.NumIterations, *this, CurScope,
10480 DSAStack))
10481 return StmtError();
10482 }
10483 }
10484
Alexey Bataev438388c2017-11-22 18:34:02 +000010485 if (checkSimdlenSafelenSpecified(*this, Clauses))
10486 return StmtError();
10487
Reid Kleckner87a31802018-03-12 21:43:02 +000010488 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010489 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10490 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10491}
10492
Kelvin Lida681182017-01-10 18:08:18 +000010493StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10494 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010495 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010496 if (!AStmt)
10497 return StmtError();
10498
10499 auto *CS = cast<CapturedStmt>(AStmt);
10500 // 1.2.2 OpenMP Language Terminology
10501 // Structured block - An executable statement with a single entry at the
10502 // top and a single exit at the bottom.
10503 // The point of exit cannot be a branch out of the structured block.
10504 // longjmp() and throw() must not violate the entry/exit criteria.
10505 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010506 for (int ThisCaptureLevel =
10507 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10508 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10509 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10510 // 1.2.2 OpenMP Language Terminology
10511 // Structured block - An executable statement with a single entry at the
10512 // top and a single exit at the bottom.
10513 // The point of exit cannot be a branch out of the structured block.
10514 // longjmp() and throw() must not violate the entry/exit criteria.
10515 CS->getCapturedDecl()->setNothrow();
10516 }
Kelvin Lida681182017-01-10 18:08:18 +000010517
10518 OMPLoopDirective::HelperExprs B;
10519 // In presence of clause 'collapse' with number of loops, it will
10520 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010521 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010522 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010523 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010524 VarsWithImplicitDSA, B);
10525 if (NestedLoopCount == 0)
10526 return StmtError();
10527
10528 assert((CurContext->isDependentContext() || B.builtAll()) &&
10529 "omp target teams distribute simd loop exprs were not built");
10530
Alexey Bataev438388c2017-11-22 18:34:02 +000010531 if (!CurContext->isDependentContext()) {
10532 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010533 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010534 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10535 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10536 B.NumIterations, *this, CurScope,
10537 DSAStack))
10538 return StmtError();
10539 }
10540 }
10541
10542 if (checkSimdlenSafelenSpecified(*this, Clauses))
10543 return StmtError();
10544
Reid Kleckner87a31802018-03-12 21:43:02 +000010545 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010546 return OMPTargetTeamsDistributeSimdDirective::Create(
10547 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10548}
10549
Alexey Bataeved09d242014-05-28 05:53:51 +000010550OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010551 SourceLocation StartLoc,
10552 SourceLocation LParenLoc,
10553 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010554 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010555 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010556 case OMPC_final:
10557 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10558 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010559 case OMPC_num_threads:
10560 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10561 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010562 case OMPC_safelen:
10563 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10564 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010565 case OMPC_simdlen:
10566 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10567 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010568 case OMPC_allocator:
10569 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10570 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010571 case OMPC_collapse:
10572 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10573 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010574 case OMPC_ordered:
10575 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10576 break;
Michael Wonge710d542015-08-07 16:16:36 +000010577 case OMPC_device:
10578 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10579 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010580 case OMPC_num_teams:
10581 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10582 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010583 case OMPC_thread_limit:
10584 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10585 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010586 case OMPC_priority:
10587 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10588 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010589 case OMPC_grainsize:
10590 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10591 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010592 case OMPC_num_tasks:
10593 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10594 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010595 case OMPC_hint:
10596 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10597 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010598 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010599 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010600 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010601 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010602 case OMPC_private:
10603 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010604 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010605 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010606 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010607 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010608 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010609 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010610 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010611 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010612 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010613 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010614 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010615 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010616 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010617 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010618 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010619 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010620 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010621 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010622 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010623 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010624 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010625 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010626 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010627 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010628 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010629 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010630 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010631 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010632 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010633 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010634 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010635 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010636 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010637 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010638 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010639 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010640 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010641 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010642 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010643 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010644 llvm_unreachable("Clause is not allowed.");
10645 }
10646 return Res;
10647}
10648
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010649// An OpenMP directive such as 'target parallel' has two captured regions:
10650// for the 'target' and 'parallel' respectively. This function returns
10651// the region in which to capture expressions associated with a clause.
10652// A return value of OMPD_unknown signifies that the expression should not
10653// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010654static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010655 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010656 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010657 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010658 switch (CKind) {
10659 case OMPC_if:
10660 switch (DKind) {
10661 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010662 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010663 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010664 // If this clause applies to the nested 'parallel' region, capture within
10665 // the 'target' region, otherwise do not capture.
10666 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10667 CaptureRegion = OMPD_target;
10668 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010669 case OMPD_target_teams_distribute_parallel_for:
10670 case OMPD_target_teams_distribute_parallel_for_simd:
10671 // If this clause applies to the nested 'parallel' region, capture within
10672 // the 'teams' region, otherwise do not capture.
10673 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10674 CaptureRegion = OMPD_teams;
10675 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010676 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010677 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010678 CaptureRegion = OMPD_teams;
10679 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010680 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010681 case OMPD_target_enter_data:
10682 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010683 CaptureRegion = OMPD_task;
10684 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010685 case OMPD_parallel_master_taskloop:
10686 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10687 CaptureRegion = OMPD_parallel;
10688 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010689 case OMPD_parallel_master_taskloop_simd:
10690 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10691 NameModifier == OMPD_taskloop) {
10692 CaptureRegion = OMPD_parallel;
10693 break;
10694 }
10695 if (OpenMPVersion <= 45)
10696 break;
10697 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10698 CaptureRegion = OMPD_taskloop;
10699 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010700 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010701 if (OpenMPVersion <= 45)
10702 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010703 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10704 CaptureRegion = OMPD_parallel;
10705 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010706 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010707 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010708 if (OpenMPVersion <= 45)
10709 break;
10710 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10711 CaptureRegion = OMPD_taskloop;
10712 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050010713 case OMPD_distribute_parallel_for_simd:
10714 if (OpenMPVersion <= 45)
10715 break;
10716 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10717 CaptureRegion = OMPD_parallel;
10718 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010719 case OMPD_cancel:
10720 case OMPD_parallel:
10721 case OMPD_parallel_sections:
10722 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010723 case OMPD_target:
10724 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010725 case OMPD_target_teams:
10726 case OMPD_target_teams_distribute:
10727 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010728 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010729 case OMPD_task:
10730 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010731 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010732 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010733 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010734 case OMPD_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010735 // Do not capture if-clause expressions.
10736 break;
10737 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010738 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010739 case OMPD_taskyield:
10740 case OMPD_barrier:
10741 case OMPD_taskwait:
10742 case OMPD_cancellation_point:
10743 case OMPD_flush:
10744 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010745 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010746 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010747 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010748 case OMPD_declare_target:
10749 case OMPD_end_declare_target:
10750 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010751 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010752 case OMPD_sections:
10753 case OMPD_section:
10754 case OMPD_single:
10755 case OMPD_master:
10756 case OMPD_critical:
10757 case OMPD_taskgroup:
10758 case OMPD_distribute:
10759 case OMPD_ordered:
10760 case OMPD_atomic:
10761 case OMPD_distribute_simd:
10762 case OMPD_teams_distribute:
10763 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010764 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010765 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10766 case OMPD_unknown:
10767 llvm_unreachable("Unknown OpenMP directive");
10768 }
10769 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010770 case OMPC_num_threads:
10771 switch (DKind) {
10772 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010773 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010774 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010775 CaptureRegion = OMPD_target;
10776 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010777 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010778 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010779 case OMPD_target_teams_distribute_parallel_for:
10780 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010781 CaptureRegion = OMPD_teams;
10782 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010783 case OMPD_parallel:
10784 case OMPD_parallel_sections:
10785 case OMPD_parallel_for:
10786 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010787 case OMPD_distribute_parallel_for:
10788 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010789 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010790 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010791 // Do not capture num_threads-clause expressions.
10792 break;
10793 case OMPD_target_data:
10794 case OMPD_target_enter_data:
10795 case OMPD_target_exit_data:
10796 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010797 case OMPD_target:
10798 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010799 case OMPD_target_teams:
10800 case OMPD_target_teams_distribute:
10801 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010802 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010803 case OMPD_task:
10804 case OMPD_taskloop:
10805 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010806 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010807 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010808 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010809 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010810 case OMPD_taskyield:
10811 case OMPD_barrier:
10812 case OMPD_taskwait:
10813 case OMPD_cancellation_point:
10814 case OMPD_flush:
10815 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010816 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010817 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010818 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010819 case OMPD_declare_target:
10820 case OMPD_end_declare_target:
10821 case OMPD_teams:
10822 case OMPD_simd:
10823 case OMPD_for:
10824 case OMPD_for_simd:
10825 case OMPD_sections:
10826 case OMPD_section:
10827 case OMPD_single:
10828 case OMPD_master:
10829 case OMPD_critical:
10830 case OMPD_taskgroup:
10831 case OMPD_distribute:
10832 case OMPD_ordered:
10833 case OMPD_atomic:
10834 case OMPD_distribute_simd:
10835 case OMPD_teams_distribute:
10836 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010837 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010838 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10839 case OMPD_unknown:
10840 llvm_unreachable("Unknown OpenMP directive");
10841 }
10842 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010843 case OMPC_num_teams:
10844 switch (DKind) {
10845 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010846 case OMPD_target_teams_distribute:
10847 case OMPD_target_teams_distribute_simd:
10848 case OMPD_target_teams_distribute_parallel_for:
10849 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010850 CaptureRegion = OMPD_target;
10851 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010852 case OMPD_teams_distribute_parallel_for:
10853 case OMPD_teams_distribute_parallel_for_simd:
10854 case OMPD_teams:
10855 case OMPD_teams_distribute:
10856 case OMPD_teams_distribute_simd:
10857 // Do not capture num_teams-clause expressions.
10858 break;
10859 case OMPD_distribute_parallel_for:
10860 case OMPD_distribute_parallel_for_simd:
10861 case OMPD_task:
10862 case OMPD_taskloop:
10863 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010864 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010865 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010866 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010867 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010868 case OMPD_target_data:
10869 case OMPD_target_enter_data:
10870 case OMPD_target_exit_data:
10871 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010872 case OMPD_cancel:
10873 case OMPD_parallel:
10874 case OMPD_parallel_sections:
10875 case OMPD_parallel_for:
10876 case OMPD_parallel_for_simd:
10877 case OMPD_target:
10878 case OMPD_target_simd:
10879 case OMPD_target_parallel:
10880 case OMPD_target_parallel_for:
10881 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010882 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010883 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010884 case OMPD_taskyield:
10885 case OMPD_barrier:
10886 case OMPD_taskwait:
10887 case OMPD_cancellation_point:
10888 case OMPD_flush:
10889 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010890 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010891 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010892 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010893 case OMPD_declare_target:
10894 case OMPD_end_declare_target:
10895 case OMPD_simd:
10896 case OMPD_for:
10897 case OMPD_for_simd:
10898 case OMPD_sections:
10899 case OMPD_section:
10900 case OMPD_single:
10901 case OMPD_master:
10902 case OMPD_critical:
10903 case OMPD_taskgroup:
10904 case OMPD_distribute:
10905 case OMPD_ordered:
10906 case OMPD_atomic:
10907 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010908 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010909 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10910 case OMPD_unknown:
10911 llvm_unreachable("Unknown OpenMP directive");
10912 }
10913 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010914 case OMPC_thread_limit:
10915 switch (DKind) {
10916 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010917 case OMPD_target_teams_distribute:
10918 case OMPD_target_teams_distribute_simd:
10919 case OMPD_target_teams_distribute_parallel_for:
10920 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010921 CaptureRegion = OMPD_target;
10922 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010923 case OMPD_teams_distribute_parallel_for:
10924 case OMPD_teams_distribute_parallel_for_simd:
10925 case OMPD_teams:
10926 case OMPD_teams_distribute:
10927 case OMPD_teams_distribute_simd:
10928 // Do not capture thread_limit-clause expressions.
10929 break;
10930 case OMPD_distribute_parallel_for:
10931 case OMPD_distribute_parallel_for_simd:
10932 case OMPD_task:
10933 case OMPD_taskloop:
10934 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010935 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010936 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010937 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010938 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010939 case OMPD_target_data:
10940 case OMPD_target_enter_data:
10941 case OMPD_target_exit_data:
10942 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010943 case OMPD_cancel:
10944 case OMPD_parallel:
10945 case OMPD_parallel_sections:
10946 case OMPD_parallel_for:
10947 case OMPD_parallel_for_simd:
10948 case OMPD_target:
10949 case OMPD_target_simd:
10950 case OMPD_target_parallel:
10951 case OMPD_target_parallel_for:
10952 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010953 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010954 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010955 case OMPD_taskyield:
10956 case OMPD_barrier:
10957 case OMPD_taskwait:
10958 case OMPD_cancellation_point:
10959 case OMPD_flush:
10960 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010961 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010962 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010963 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010964 case OMPD_declare_target:
10965 case OMPD_end_declare_target:
10966 case OMPD_simd:
10967 case OMPD_for:
10968 case OMPD_for_simd:
10969 case OMPD_sections:
10970 case OMPD_section:
10971 case OMPD_single:
10972 case OMPD_master:
10973 case OMPD_critical:
10974 case OMPD_taskgroup:
10975 case OMPD_distribute:
10976 case OMPD_ordered:
10977 case OMPD_atomic:
10978 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010979 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010980 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10981 case OMPD_unknown:
10982 llvm_unreachable("Unknown OpenMP directive");
10983 }
10984 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010985 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010986 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010987 case OMPD_parallel_for:
10988 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010989 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010990 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010991 case OMPD_teams_distribute_parallel_for:
10992 case OMPD_teams_distribute_parallel_for_simd:
10993 case OMPD_target_parallel_for:
10994 case OMPD_target_parallel_for_simd:
10995 case OMPD_target_teams_distribute_parallel_for:
10996 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010997 CaptureRegion = OMPD_parallel;
10998 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010999 case OMPD_for:
11000 case OMPD_for_simd:
11001 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011002 break;
11003 case OMPD_task:
11004 case OMPD_taskloop:
11005 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011006 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011007 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011008 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011009 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011010 case OMPD_target_data:
11011 case OMPD_target_enter_data:
11012 case OMPD_target_exit_data:
11013 case OMPD_target_update:
11014 case OMPD_teams:
11015 case OMPD_teams_distribute:
11016 case OMPD_teams_distribute_simd:
11017 case OMPD_target_teams_distribute:
11018 case OMPD_target_teams_distribute_simd:
11019 case OMPD_target:
11020 case OMPD_target_simd:
11021 case OMPD_target_parallel:
11022 case OMPD_cancel:
11023 case OMPD_parallel:
11024 case OMPD_parallel_sections:
11025 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011026 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011027 case OMPD_taskyield:
11028 case OMPD_barrier:
11029 case OMPD_taskwait:
11030 case OMPD_cancellation_point:
11031 case OMPD_flush:
11032 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011033 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011034 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011035 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011036 case OMPD_declare_target:
11037 case OMPD_end_declare_target:
11038 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011039 case OMPD_sections:
11040 case OMPD_section:
11041 case OMPD_single:
11042 case OMPD_master:
11043 case OMPD_critical:
11044 case OMPD_taskgroup:
11045 case OMPD_distribute:
11046 case OMPD_ordered:
11047 case OMPD_atomic:
11048 case OMPD_distribute_simd:
11049 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011050 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011051 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11052 case OMPD_unknown:
11053 llvm_unreachable("Unknown OpenMP directive");
11054 }
11055 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011056 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011057 switch (DKind) {
11058 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011059 case OMPD_teams_distribute_parallel_for_simd:
11060 case OMPD_teams_distribute:
11061 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011062 case OMPD_target_teams_distribute_parallel_for:
11063 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011064 case OMPD_target_teams_distribute:
11065 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011066 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011067 break;
11068 case OMPD_distribute_parallel_for:
11069 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011070 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011071 case OMPD_distribute_simd:
11072 // Do not capture thread_limit-clause expressions.
11073 break;
11074 case OMPD_parallel_for:
11075 case OMPD_parallel_for_simd:
11076 case OMPD_target_parallel_for_simd:
11077 case OMPD_target_parallel_for:
11078 case OMPD_task:
11079 case OMPD_taskloop:
11080 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011081 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011082 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011083 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011084 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011085 case OMPD_target_data:
11086 case OMPD_target_enter_data:
11087 case OMPD_target_exit_data:
11088 case OMPD_target_update:
11089 case OMPD_teams:
11090 case OMPD_target:
11091 case OMPD_target_simd:
11092 case OMPD_target_parallel:
11093 case OMPD_cancel:
11094 case OMPD_parallel:
11095 case OMPD_parallel_sections:
11096 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011097 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011098 case OMPD_taskyield:
11099 case OMPD_barrier:
11100 case OMPD_taskwait:
11101 case OMPD_cancellation_point:
11102 case OMPD_flush:
11103 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011104 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011105 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011106 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011107 case OMPD_declare_target:
11108 case OMPD_end_declare_target:
11109 case OMPD_simd:
11110 case OMPD_for:
11111 case OMPD_for_simd:
11112 case OMPD_sections:
11113 case OMPD_section:
11114 case OMPD_single:
11115 case OMPD_master:
11116 case OMPD_critical:
11117 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011118 case OMPD_ordered:
11119 case OMPD_atomic:
11120 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011121 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011122 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11123 case OMPD_unknown:
11124 llvm_unreachable("Unknown OpenMP directive");
11125 }
11126 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011127 case OMPC_device:
11128 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011129 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011130 case OMPD_target_enter_data:
11131 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011132 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011133 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011134 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011135 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011136 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011137 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011138 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011139 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011140 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011141 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011142 CaptureRegion = OMPD_task;
11143 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011144 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011145 // Do not capture device-clause expressions.
11146 break;
11147 case OMPD_teams_distribute_parallel_for:
11148 case OMPD_teams_distribute_parallel_for_simd:
11149 case OMPD_teams:
11150 case OMPD_teams_distribute:
11151 case OMPD_teams_distribute_simd:
11152 case OMPD_distribute_parallel_for:
11153 case OMPD_distribute_parallel_for_simd:
11154 case OMPD_task:
11155 case OMPD_taskloop:
11156 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011157 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011158 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011159 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011160 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011161 case OMPD_cancel:
11162 case OMPD_parallel:
11163 case OMPD_parallel_sections:
11164 case OMPD_parallel_for:
11165 case OMPD_parallel_for_simd:
11166 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011167 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011168 case OMPD_taskyield:
11169 case OMPD_barrier:
11170 case OMPD_taskwait:
11171 case OMPD_cancellation_point:
11172 case OMPD_flush:
11173 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011174 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011175 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011176 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011177 case OMPD_declare_target:
11178 case OMPD_end_declare_target:
11179 case OMPD_simd:
11180 case OMPD_for:
11181 case OMPD_for_simd:
11182 case OMPD_sections:
11183 case OMPD_section:
11184 case OMPD_single:
11185 case OMPD_master:
11186 case OMPD_critical:
11187 case OMPD_taskgroup:
11188 case OMPD_distribute:
11189 case OMPD_ordered:
11190 case OMPD_atomic:
11191 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011192 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011193 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11194 case OMPD_unknown:
11195 llvm_unreachable("Unknown OpenMP directive");
11196 }
11197 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011198 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011199 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011200 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011201 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011202 switch (DKind) {
11203 case OMPD_task:
11204 case OMPD_taskloop:
11205 case OMPD_taskloop_simd:
11206 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011207 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011208 break;
11209 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011210 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011211 CaptureRegion = OMPD_parallel;
11212 break;
11213 case OMPD_target_update:
11214 case OMPD_target_enter_data:
11215 case OMPD_target_exit_data:
11216 case OMPD_target:
11217 case OMPD_target_simd:
11218 case OMPD_target_teams:
11219 case OMPD_target_parallel:
11220 case OMPD_target_teams_distribute:
11221 case OMPD_target_teams_distribute_simd:
11222 case OMPD_target_parallel_for:
11223 case OMPD_target_parallel_for_simd:
11224 case OMPD_target_teams_distribute_parallel_for:
11225 case OMPD_target_teams_distribute_parallel_for_simd:
11226 case OMPD_target_data:
11227 case OMPD_teams_distribute_parallel_for:
11228 case OMPD_teams_distribute_parallel_for_simd:
11229 case OMPD_teams:
11230 case OMPD_teams_distribute:
11231 case OMPD_teams_distribute_simd:
11232 case OMPD_distribute_parallel_for:
11233 case OMPD_distribute_parallel_for_simd:
11234 case OMPD_cancel:
11235 case OMPD_parallel:
11236 case OMPD_parallel_sections:
11237 case OMPD_parallel_for:
11238 case OMPD_parallel_for_simd:
11239 case OMPD_threadprivate:
11240 case OMPD_allocate:
11241 case OMPD_taskyield:
11242 case OMPD_barrier:
11243 case OMPD_taskwait:
11244 case OMPD_cancellation_point:
11245 case OMPD_flush:
11246 case OMPD_declare_reduction:
11247 case OMPD_declare_mapper:
11248 case OMPD_declare_simd:
11249 case OMPD_declare_variant:
11250 case OMPD_declare_target:
11251 case OMPD_end_declare_target:
11252 case OMPD_simd:
11253 case OMPD_for:
11254 case OMPD_for_simd:
11255 case OMPD_sections:
11256 case OMPD_section:
11257 case OMPD_single:
11258 case OMPD_master:
11259 case OMPD_critical:
11260 case OMPD_taskgroup:
11261 case OMPD_distribute:
11262 case OMPD_ordered:
11263 case OMPD_atomic:
11264 case OMPD_distribute_simd:
11265 case OMPD_requires:
11266 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11267 case OMPD_unknown:
11268 llvm_unreachable("Unknown OpenMP directive");
11269 }
11270 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011271 case OMPC_firstprivate:
11272 case OMPC_lastprivate:
11273 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011274 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011275 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011276 case OMPC_linear:
11277 case OMPC_default:
11278 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011279 case OMPC_safelen:
11280 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011281 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011282 case OMPC_collapse:
11283 case OMPC_private:
11284 case OMPC_shared:
11285 case OMPC_aligned:
11286 case OMPC_copyin:
11287 case OMPC_copyprivate:
11288 case OMPC_ordered:
11289 case OMPC_nowait:
11290 case OMPC_untied:
11291 case OMPC_mergeable:
11292 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011293 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011294 case OMPC_flush:
11295 case OMPC_read:
11296 case OMPC_write:
11297 case OMPC_update:
11298 case OMPC_capture:
11299 case OMPC_seq_cst:
11300 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011301 case OMPC_threads:
11302 case OMPC_simd:
11303 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011304 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011305 case OMPC_hint:
11306 case OMPC_defaultmap:
11307 case OMPC_unknown:
11308 case OMPC_uniform:
11309 case OMPC_to:
11310 case OMPC_from:
11311 case OMPC_use_device_ptr:
11312 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011313 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011314 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011315 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011316 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011317 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011318 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011319 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011320 llvm_unreachable("Unexpected OpenMP clause.");
11321 }
11322 return CaptureRegion;
11323}
11324
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011325OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11326 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011327 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011328 SourceLocation NameModifierLoc,
11329 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011330 SourceLocation EndLoc) {
11331 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011332 Stmt *HelperValStmt = nullptr;
11333 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011334 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11335 !Condition->isInstantiationDependent() &&
11336 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011337 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011338 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011339 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011340
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011341 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011342
11343 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011344 CaptureRegion = getOpenMPCaptureRegionForClause(
11345 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011346 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011347 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011348 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011349 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11350 HelperValStmt = buildPreInits(Context, Captures);
11351 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011352 }
11353
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011354 return new (Context)
11355 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11356 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011357}
11358
Alexey Bataev3778b602014-07-17 07:32:53 +000011359OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11360 SourceLocation StartLoc,
11361 SourceLocation LParenLoc,
11362 SourceLocation EndLoc) {
11363 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011364 Stmt *HelperValStmt = nullptr;
11365 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011366 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11367 !Condition->isInstantiationDependent() &&
11368 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011369 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011370 if (Val.isInvalid())
11371 return nullptr;
11372
Richard Smith03a4aa32016-06-23 19:02:52 +000011373 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011374
11375 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011376 CaptureRegion =
11377 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011378 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11379 ValExpr = MakeFullExpr(ValExpr).get();
11380 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11381 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11382 HelperValStmt = buildPreInits(Context, Captures);
11383 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011384 }
11385
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011386 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11387 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011388}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011389
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011390ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11391 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011392 if (!Op)
11393 return ExprError();
11394
11395 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11396 public:
11397 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011398 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011399 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11400 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011401 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11402 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011403 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11404 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011405 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11406 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011407 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11408 QualType T,
11409 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011410 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11411 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011412 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11413 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011414 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011415 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011416 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011417 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11418 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011419 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11420 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011421 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11422 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011423 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011424 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011425 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011426 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11427 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011428 llvm_unreachable("conversion functions are permitted");
11429 }
11430 } ConvertDiagnoser;
11431 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11432}
11433
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011434static bool
11435isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11436 bool StrictlyPositive, bool BuildCapture = false,
11437 OpenMPDirectiveKind DKind = OMPD_unknown,
11438 OpenMPDirectiveKind *CaptureRegion = nullptr,
11439 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011440 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11441 !ValExpr->isInstantiationDependent()) {
11442 SourceLocation Loc = ValExpr->getExprLoc();
11443 ExprResult Value =
11444 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11445 if (Value.isInvalid())
11446 return false;
11447
11448 ValExpr = Value.get();
11449 // The expression must evaluate to a non-negative integer value.
11450 llvm::APSInt Result;
11451 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011452 Result.isSigned() &&
11453 !((!StrictlyPositive && Result.isNonNegative()) ||
11454 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011455 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011456 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11457 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011458 return false;
11459 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011460 if (!BuildCapture)
11461 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011462 *CaptureRegion =
11463 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011464 if (*CaptureRegion != OMPD_unknown &&
11465 !SemaRef.CurContext->isDependentContext()) {
11466 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11467 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11468 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11469 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11470 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011471 }
11472 return true;
11473}
11474
Alexey Bataev568a8332014-03-06 06:15:19 +000011475OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11476 SourceLocation StartLoc,
11477 SourceLocation LParenLoc,
11478 SourceLocation EndLoc) {
11479 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011480 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011481
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011482 // OpenMP [2.5, Restrictions]
11483 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011484 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011485 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011486 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011487
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011488 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011489 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011490 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011491 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011492 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011493 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011494 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11495 HelperValStmt = buildPreInits(Context, Captures);
11496 }
11497
11498 return new (Context) OMPNumThreadsClause(
11499 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011500}
11501
Alexey Bataev62c87d22014-03-21 04:51:18 +000011502ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011503 OpenMPClauseKind CKind,
11504 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011505 if (!E)
11506 return ExprError();
11507 if (E->isValueDependent() || E->isTypeDependent() ||
11508 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011509 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011510 llvm::APSInt Result;
11511 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11512 if (ICE.isInvalid())
11513 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011514 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11515 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011516 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011517 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11518 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011519 return ExprError();
11520 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011521 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11522 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11523 << E->getSourceRange();
11524 return ExprError();
11525 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011526 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11527 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011528 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011529 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011530 return ICE;
11531}
11532
11533OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11534 SourceLocation LParenLoc,
11535 SourceLocation EndLoc) {
11536 // OpenMP [2.8.1, simd construct, Description]
11537 // The parameter of the safelen clause must be a constant
11538 // positive integer expression.
11539 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11540 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011541 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011542 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011543 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011544}
11545
Alexey Bataev66b15b52015-08-21 11:14:16 +000011546OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11547 SourceLocation LParenLoc,
11548 SourceLocation EndLoc) {
11549 // OpenMP [2.8.1, simd construct, Description]
11550 // The parameter of the simdlen clause must be a constant
11551 // positive integer expression.
11552 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11553 if (Simdlen.isInvalid())
11554 return nullptr;
11555 return new (Context)
11556 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11557}
11558
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011559/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011560static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11561 DSAStackTy *Stack) {
11562 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011563 if (!OMPAllocatorHandleT.isNull())
11564 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011565 // Build the predefined allocator expressions.
11566 bool ErrorFound = false;
11567 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11568 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11569 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11570 StringRef Allocator =
11571 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11572 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11573 auto *VD = dyn_cast_or_null<ValueDecl>(
11574 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11575 if (!VD) {
11576 ErrorFound = true;
11577 break;
11578 }
11579 QualType AllocatorType =
11580 VD->getType().getNonLValueExprType(S.getASTContext());
11581 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11582 if (!Res.isUsable()) {
11583 ErrorFound = true;
11584 break;
11585 }
11586 if (OMPAllocatorHandleT.isNull())
11587 OMPAllocatorHandleT = AllocatorType;
11588 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11589 ErrorFound = true;
11590 break;
11591 }
11592 Stack->setAllocator(AllocatorKind, Res.get());
11593 }
11594 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011595 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11596 return false;
11597 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011598 OMPAllocatorHandleT.addConst();
11599 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011600 return true;
11601}
11602
11603OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11604 SourceLocation LParenLoc,
11605 SourceLocation EndLoc) {
11606 // OpenMP [2.11.3, allocate Directive, Description]
11607 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011608 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011609 return nullptr;
11610
11611 ExprResult Allocator = DefaultLvalueConversion(A);
11612 if (Allocator.isInvalid())
11613 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011614 Allocator = PerformImplicitConversion(Allocator.get(),
11615 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011616 Sema::AA_Initializing,
11617 /*AllowExplicit=*/true);
11618 if (Allocator.isInvalid())
11619 return nullptr;
11620 return new (Context)
11621 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11622}
11623
Alexander Musman64d33f12014-06-04 07:53:32 +000011624OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11625 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011626 SourceLocation LParenLoc,
11627 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011628 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011629 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011630 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011631 // The parameter of the collapse clause must be a constant
11632 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011633 ExprResult NumForLoopsResult =
11634 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11635 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011636 return nullptr;
11637 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011638 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011639}
11640
Alexey Bataev10e775f2015-07-30 11:36:16 +000011641OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11642 SourceLocation EndLoc,
11643 SourceLocation LParenLoc,
11644 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011645 // OpenMP [2.7.1, loop construct, Description]
11646 // OpenMP [2.8.1, simd construct, Description]
11647 // OpenMP [2.9.6, distribute construct, Description]
11648 // The parameter of the ordered clause must be a constant
11649 // positive integer expression if any.
11650 if (NumForLoops && LParenLoc.isValid()) {
11651 ExprResult NumForLoopsResult =
11652 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11653 if (NumForLoopsResult.isInvalid())
11654 return nullptr;
11655 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011656 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011657 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011658 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011659 auto *Clause = OMPOrderedClause::Create(
11660 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11661 StartLoc, LParenLoc, EndLoc);
11662 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11663 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011664}
11665
Alexey Bataeved09d242014-05-28 05:53:51 +000011666OMPClause *Sema::ActOnOpenMPSimpleClause(
11667 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11668 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011669 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011670 switch (Kind) {
11671 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011672 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011673 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11674 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011675 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011676 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011677 Res = ActOnOpenMPProcBindClause(
11678 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11679 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011680 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011681 case OMPC_atomic_default_mem_order:
11682 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11683 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11684 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11685 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011686 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011687 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011688 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011689 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011690 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011691 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011692 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011693 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011694 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011695 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011696 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011697 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011698 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011699 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011700 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011701 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011702 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011703 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011704 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011705 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011706 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011707 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011708 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011709 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011710 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011711 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011712 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011713 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011714 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011715 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011716 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011717 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011718 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011719 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011720 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011721 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011722 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011723 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011724 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011725 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011726 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011727 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011728 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011729 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011730 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011731 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011732 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011733 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011734 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011735 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011736 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011737 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011738 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011739 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011740 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011741 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011742 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011743 llvm_unreachable("Clause is not allowed.");
11744 }
11745 return Res;
11746}
11747
Alexey Bataev6402bca2015-12-28 07:25:51 +000011748static std::string
11749getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11750 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011751 SmallString<256> Buffer;
11752 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011753 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11754 unsigned Skipped = Exclude.size();
11755 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011756 for (unsigned I = First; I < Last; ++I) {
11757 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011758 --Skipped;
11759 continue;
11760 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011761 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11762 if (I == Bound - Skipped)
11763 Out << " or ";
11764 else if (I != Bound + 1 - Skipped)
11765 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011766 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011767 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011768}
11769
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011770OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11771 SourceLocation KindKwLoc,
11772 SourceLocation StartLoc,
11773 SourceLocation LParenLoc,
11774 SourceLocation EndLoc) {
11775 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011776 static_assert(OMPC_DEFAULT_unknown > 0,
11777 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011778 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011779 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11780 /*Last=*/OMPC_DEFAULT_unknown)
11781 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011782 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011783 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011784 switch (Kind) {
11785 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011786 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011787 break;
11788 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011789 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011790 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011791 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011792 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011793 break;
11794 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011795 return new (Context)
11796 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011797}
11798
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011799OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11800 SourceLocation KindKwLoc,
11801 SourceLocation StartLoc,
11802 SourceLocation LParenLoc,
11803 SourceLocation EndLoc) {
11804 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011805 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011806 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11807 /*Last=*/OMPC_PROC_BIND_unknown)
11808 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011809 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011810 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011811 return new (Context)
11812 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011813}
11814
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011815OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11816 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11817 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11818 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11819 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11820 << getListOfPossibleValues(
11821 OMPC_atomic_default_mem_order, /*First=*/0,
11822 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11823 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11824 return nullptr;
11825 }
11826 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11827 LParenLoc, EndLoc);
11828}
11829
Alexey Bataev56dafe82014-06-20 07:16:17 +000011830OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011831 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011832 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011833 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011834 SourceLocation EndLoc) {
11835 OMPClause *Res = nullptr;
11836 switch (Kind) {
11837 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011838 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11839 assert(Argument.size() == NumberOfElements &&
11840 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011841 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011842 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11843 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11844 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11845 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11846 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011847 break;
11848 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011849 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11850 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11851 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11852 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011853 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011854 case OMPC_dist_schedule:
11855 Res = ActOnOpenMPDistScheduleClause(
11856 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11857 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11858 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011859 case OMPC_defaultmap:
11860 enum { Modifier, DefaultmapKind };
11861 Res = ActOnOpenMPDefaultmapClause(
11862 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11863 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011864 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11865 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011866 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011867 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011868 case OMPC_num_threads:
11869 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011870 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011871 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011872 case OMPC_collapse:
11873 case OMPC_default:
11874 case OMPC_proc_bind:
11875 case OMPC_private:
11876 case OMPC_firstprivate:
11877 case OMPC_lastprivate:
11878 case OMPC_shared:
11879 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011880 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011881 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011882 case OMPC_linear:
11883 case OMPC_aligned:
11884 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011885 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011886 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011887 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011888 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011889 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011890 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011891 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011892 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011893 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011894 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011895 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011896 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011897 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011898 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011899 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011900 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011901 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011902 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011903 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011904 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011905 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011906 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011907 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011908 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011909 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011910 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011911 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011912 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011913 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011914 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011915 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011916 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011917 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011918 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011919 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011920 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011921 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011922 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011923 llvm_unreachable("Clause is not allowed.");
11924 }
11925 return Res;
11926}
11927
Alexey Bataev6402bca2015-12-28 07:25:51 +000011928static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11929 OpenMPScheduleClauseModifier M2,
11930 SourceLocation M1Loc, SourceLocation M2Loc) {
11931 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11932 SmallVector<unsigned, 2> Excluded;
11933 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11934 Excluded.push_back(M2);
11935 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11936 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11937 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11938 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11939 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11940 << getListOfPossibleValues(OMPC_schedule,
11941 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11942 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11943 Excluded)
11944 << getOpenMPClauseName(OMPC_schedule);
11945 return true;
11946 }
11947 return false;
11948}
11949
Alexey Bataev56dafe82014-06-20 07:16:17 +000011950OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011951 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011952 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011953 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11954 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11955 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11956 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11957 return nullptr;
11958 // OpenMP, 2.7.1, Loop Construct, Restrictions
11959 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11960 // but not both.
11961 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11962 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11963 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11964 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11965 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11966 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11967 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11968 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11969 return nullptr;
11970 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011971 if (Kind == OMPC_SCHEDULE_unknown) {
11972 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011973 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11974 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11975 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11976 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11977 Exclude);
11978 } else {
11979 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11980 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011981 }
11982 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11983 << Values << getOpenMPClauseName(OMPC_schedule);
11984 return nullptr;
11985 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011986 // OpenMP, 2.7.1, Loop Construct, Restrictions
11987 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11988 // schedule(guided).
11989 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11990 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11991 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11992 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11993 diag::err_omp_schedule_nonmonotonic_static);
11994 return nullptr;
11995 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011996 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011997 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011998 if (ChunkSize) {
11999 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12000 !ChunkSize->isInstantiationDependent() &&
12001 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012002 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012003 ExprResult Val =
12004 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12005 if (Val.isInvalid())
12006 return nullptr;
12007
12008 ValExpr = Val.get();
12009
12010 // OpenMP [2.7.1, Restrictions]
12011 // chunk_size must be a loop invariant integer expression with a positive
12012 // value.
12013 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012014 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12015 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12016 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012017 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012018 return nullptr;
12019 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012020 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012021 DSAStack->getCurrentDirective(), OMPC_schedule,
12022 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012023 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012024 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012025 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012026 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12027 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012028 }
12029 }
12030 }
12031
Alexey Bataev6402bca2015-12-28 07:25:51 +000012032 return new (Context)
12033 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012034 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012035}
12036
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012037OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12038 SourceLocation StartLoc,
12039 SourceLocation EndLoc) {
12040 OMPClause *Res = nullptr;
12041 switch (Kind) {
12042 case OMPC_ordered:
12043 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12044 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012045 case OMPC_nowait:
12046 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12047 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012048 case OMPC_untied:
12049 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12050 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012051 case OMPC_mergeable:
12052 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12053 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012054 case OMPC_read:
12055 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12056 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012057 case OMPC_write:
12058 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12059 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012060 case OMPC_update:
12061 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12062 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012063 case OMPC_capture:
12064 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12065 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012066 case OMPC_seq_cst:
12067 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12068 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012069 case OMPC_threads:
12070 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12071 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012072 case OMPC_simd:
12073 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12074 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012075 case OMPC_nogroup:
12076 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12077 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012078 case OMPC_unified_address:
12079 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12080 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012081 case OMPC_unified_shared_memory:
12082 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12083 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012084 case OMPC_reverse_offload:
12085 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12086 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012087 case OMPC_dynamic_allocators:
12088 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12089 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012090 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012091 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012092 case OMPC_num_threads:
12093 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012094 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012095 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012096 case OMPC_collapse:
12097 case OMPC_schedule:
12098 case OMPC_private:
12099 case OMPC_firstprivate:
12100 case OMPC_lastprivate:
12101 case OMPC_shared:
12102 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012103 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012104 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012105 case OMPC_linear:
12106 case OMPC_aligned:
12107 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012108 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012109 case OMPC_default:
12110 case OMPC_proc_bind:
12111 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012112 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012113 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012114 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012115 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012116 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012117 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012118 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012119 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012120 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012121 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012122 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012123 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012124 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012125 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012126 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012127 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012128 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012129 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012130 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012131 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012132 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012133 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012134 llvm_unreachable("Clause is not allowed.");
12135 }
12136 return Res;
12137}
12138
Alexey Bataev236070f2014-06-20 11:19:47 +000012139OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12140 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012141 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012142 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12143}
12144
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012145OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12146 SourceLocation EndLoc) {
12147 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12148}
12149
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012150OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12151 SourceLocation EndLoc) {
12152 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12153}
12154
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012155OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12156 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012157 return new (Context) OMPReadClause(StartLoc, EndLoc);
12158}
12159
Alexey Bataevdea47612014-07-23 07:46:59 +000012160OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12161 SourceLocation EndLoc) {
12162 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12163}
12164
Alexey Bataev67a4f222014-07-23 10:25:33 +000012165OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12166 SourceLocation EndLoc) {
12167 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12168}
12169
Alexey Bataev459dec02014-07-24 06:46:57 +000012170OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12171 SourceLocation EndLoc) {
12172 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12173}
12174
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012175OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12176 SourceLocation EndLoc) {
12177 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12178}
12179
Alexey Bataev346265e2015-09-25 10:37:12 +000012180OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12181 SourceLocation EndLoc) {
12182 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12183}
12184
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012185OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12186 SourceLocation EndLoc) {
12187 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12188}
12189
Alexey Bataevb825de12015-12-07 10:51:44 +000012190OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12191 SourceLocation EndLoc) {
12192 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12193}
12194
Kelvin Li1408f912018-09-26 04:28:39 +000012195OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12196 SourceLocation EndLoc) {
12197 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12198}
12199
Patrick Lyster4a370b92018-10-01 13:47:43 +000012200OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12201 SourceLocation EndLoc) {
12202 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12203}
12204
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012205OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12206 SourceLocation EndLoc) {
12207 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12208}
12209
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012210OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12211 SourceLocation EndLoc) {
12212 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12213}
12214
Alexey Bataevc5e02582014-06-16 07:08:35 +000012215OMPClause *Sema::ActOnOpenMPVarListClause(
12216 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012217 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12218 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
12219 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000012220 OpenMPLinearClauseKind LinKind,
12221 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012222 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
12223 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
12224 SourceLocation StartLoc = Locs.StartLoc;
12225 SourceLocation LParenLoc = Locs.LParenLoc;
12226 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012227 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012228 switch (Kind) {
12229 case OMPC_private:
12230 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12231 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012232 case OMPC_firstprivate:
12233 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12234 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012235 case OMPC_lastprivate:
12236 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12237 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012238 case OMPC_shared:
12239 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12240 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012241 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012242 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012243 EndLoc, ReductionOrMapperIdScopeSpec,
12244 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012245 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012246 case OMPC_task_reduction:
12247 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012248 EndLoc, ReductionOrMapperIdScopeSpec,
12249 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012250 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012251 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012252 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12253 EndLoc, ReductionOrMapperIdScopeSpec,
12254 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012255 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012256 case OMPC_linear:
12257 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012258 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012259 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012260 case OMPC_aligned:
12261 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12262 ColonLoc, EndLoc);
12263 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012264 case OMPC_copyin:
12265 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12266 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012267 case OMPC_copyprivate:
12268 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12269 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012270 case OMPC_flush:
12271 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12272 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012273 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000012274 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012275 StartLoc, LParenLoc, EndLoc);
12276 break;
12277 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012278 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
12279 ReductionOrMapperIdScopeSpec,
12280 ReductionOrMapperId, MapType, IsMapTypeImplicit,
12281 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012282 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012283 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012284 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12285 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012286 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012287 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012288 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12289 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012290 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012291 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012292 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012293 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012294 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012295 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012296 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012297 case OMPC_allocate:
12298 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12299 ColonLoc, EndLoc);
12300 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012301 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012302 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012303 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012304 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012305 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012306 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012307 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012308 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012309 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012310 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012311 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012312 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012313 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012314 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012315 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012316 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012317 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012318 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012319 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012320 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012321 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012322 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012323 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012324 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012325 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012326 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012327 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012328 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012329 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012330 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012331 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012332 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012333 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012334 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012335 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012336 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012337 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012338 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012339 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012340 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012341 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012342 llvm_unreachable("Clause is not allowed.");
12343 }
12344 return Res;
12345}
12346
Alexey Bataev90c228f2016-02-08 09:29:13 +000012347ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012348 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012349 ExprResult Res = BuildDeclRefExpr(
12350 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12351 if (!Res.isUsable())
12352 return ExprError();
12353 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12354 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12355 if (!Res.isUsable())
12356 return ExprError();
12357 }
12358 if (VK != VK_LValue && Res.get()->isGLValue()) {
12359 Res = DefaultLvalueConversion(Res.get());
12360 if (!Res.isUsable())
12361 return ExprError();
12362 }
12363 return Res;
12364}
12365
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012366OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12367 SourceLocation StartLoc,
12368 SourceLocation LParenLoc,
12369 SourceLocation EndLoc) {
12370 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012371 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012372 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012373 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012374 SourceLocation ELoc;
12375 SourceRange ERange;
12376 Expr *SimpleRefExpr = RefExpr;
12377 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012378 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012379 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012380 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012381 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012382 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012383 ValueDecl *D = Res.first;
12384 if (!D)
12385 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012386
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012387 QualType Type = D->getType();
12388 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012389
12390 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12391 // A variable that appears in a private clause must not have an incomplete
12392 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012393 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012394 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012395 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012396
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012397 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12398 // A variable that is privatized must not have a const-qualified type
12399 // unless it is of class type with a mutable member. This restriction does
12400 // not apply to the firstprivate clause.
12401 //
12402 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12403 // A variable that appears in a private clause must not have a
12404 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012405 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012406 continue;
12407
Alexey Bataev758e55e2013-09-06 18:03:48 +000012408 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12409 // in a Construct]
12410 // Variables with the predetermined data-sharing attributes may not be
12411 // listed in data-sharing attributes clauses, except for the cases
12412 // listed below. For these exceptions only, listing a predetermined
12413 // variable in a data-sharing attribute clause is allowed and overrides
12414 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012415 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012416 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012417 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12418 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012419 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012420 continue;
12421 }
12422
Alexey Bataeve3727102018-04-18 15:57:46 +000012423 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012424 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012425 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012426 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012427 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12428 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012429 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012430 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012431 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012432 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012433 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012434 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012435 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012436 continue;
12437 }
12438
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012439 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12440 // A list item cannot appear in both a map clause and a data-sharing
12441 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012442 //
12443 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12444 // A list item cannot appear in both a map clause and a data-sharing
12445 // attribute clause on the same construct unless the construct is a
12446 // combined construct.
12447 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12448 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012449 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012450 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012451 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012452 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12453 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12454 ConflictKind = WhereFoundClauseKind;
12455 return true;
12456 })) {
12457 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012458 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012459 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012460 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012461 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012462 continue;
12463 }
12464 }
12465
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012466 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12467 // A variable of class type (or array thereof) that appears in a private
12468 // clause requires an accessible, unambiguous default constructor for the
12469 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012470 // Generate helper private variable and initialize it with the default
12471 // value. The address of the original variable is replaced by the address of
12472 // the new private variable in CodeGen. This new variable is not added to
12473 // IdResolver, so the code in the OpenMP region uses original variable for
12474 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012475 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012476 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012477 buildVarDecl(*this, ELoc, Type, D->getName(),
12478 D->hasAttrs() ? &D->getAttrs() : nullptr,
12479 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012480 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012481 if (VDPrivate->isInvalidDecl())
12482 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012483 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012484 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012485
Alexey Bataev90c228f2016-02-08 09:29:13 +000012486 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012487 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012488 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012489 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012490 Vars.push_back((VD || CurContext->isDependentContext())
12491 ? RefExpr->IgnoreParens()
12492 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012493 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012494 }
12495
Alexey Bataeved09d242014-05-28 05:53:51 +000012496 if (Vars.empty())
12497 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012498
Alexey Bataev03b340a2014-10-21 03:16:40 +000012499 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12500 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012501}
12502
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012503namespace {
12504class DiagsUninitializedSeveretyRAII {
12505private:
12506 DiagnosticsEngine &Diags;
12507 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012508 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012509
12510public:
12511 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12512 bool IsIgnored)
12513 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12514 if (!IsIgnored) {
12515 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12516 /*Map*/ diag::Severity::Ignored, Loc);
12517 }
12518 }
12519 ~DiagsUninitializedSeveretyRAII() {
12520 if (!IsIgnored)
12521 Diags.popMappings(SavedLoc);
12522 }
12523};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012524}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012525
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012526OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12527 SourceLocation StartLoc,
12528 SourceLocation LParenLoc,
12529 SourceLocation EndLoc) {
12530 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012531 SmallVector<Expr *, 8> PrivateCopies;
12532 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012533 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012534 bool IsImplicitClause =
12535 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012536 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012537
Alexey Bataeve3727102018-04-18 15:57:46 +000012538 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012539 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012540 SourceLocation ELoc;
12541 SourceRange ERange;
12542 Expr *SimpleRefExpr = RefExpr;
12543 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012544 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012545 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012546 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012547 PrivateCopies.push_back(nullptr);
12548 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012549 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012550 ValueDecl *D = Res.first;
12551 if (!D)
12552 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012553
Alexey Bataev60da77e2016-02-29 05:54:20 +000012554 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012555 QualType Type = D->getType();
12556 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012557
12558 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12559 // A variable that appears in a private clause must not have an incomplete
12560 // type or a reference type.
12561 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012562 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012563 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012564 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012565
12566 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12567 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012568 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012569 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012570 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012571
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012572 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012573 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012574 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012575 DSAStackTy::DSAVarData DVar =
12576 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012577 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012578 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012579 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012580 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12581 // A list item that specifies a given variable may not appear in more
12582 // than one clause on the same directive, except that a variable may be
12583 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012584 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12585 // A list item may appear in a firstprivate or lastprivate clause but not
12586 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012587 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012588 (isOpenMPDistributeDirective(CurrDir) ||
12589 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012590 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012591 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012592 << getOpenMPClauseName(DVar.CKind)
12593 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012594 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012595 continue;
12596 }
12597
12598 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12599 // in a Construct]
12600 // Variables with the predetermined data-sharing attributes may not be
12601 // listed in data-sharing attributes clauses, except for the cases
12602 // listed below. For these exceptions only, listing a predetermined
12603 // variable in a data-sharing attribute clause is allowed and overrides
12604 // the variable's predetermined data-sharing attributes.
12605 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12606 // in a Construct, C/C++, p.2]
12607 // Variables with const-qualified type having no mutable member may be
12608 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012609 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012610 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12611 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012612 << getOpenMPClauseName(DVar.CKind)
12613 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012614 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012615 continue;
12616 }
12617
12618 // OpenMP [2.9.3.4, Restrictions, p.2]
12619 // A list item that is private within a parallel region must not appear
12620 // in a firstprivate clause on a worksharing construct if any of the
12621 // worksharing regions arising from the worksharing construct ever bind
12622 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012623 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12624 // A list item that is private within a teams region must not appear in a
12625 // firstprivate clause on a distribute construct if any of the distribute
12626 // regions arising from the distribute construct ever bind to any of the
12627 // teams regions arising from the teams construct.
12628 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12629 // A list item that appears in a reduction clause of a teams construct
12630 // must not appear in a firstprivate clause on a distribute construct if
12631 // any of the distribute regions arising from the distribute construct
12632 // ever bind to any of the teams regions arising from the teams construct.
12633 if ((isOpenMPWorksharingDirective(CurrDir) ||
12634 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012635 !isOpenMPParallelDirective(CurrDir) &&
12636 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012637 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012638 if (DVar.CKind != OMPC_shared &&
12639 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012640 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012641 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012642 Diag(ELoc, diag::err_omp_required_access)
12643 << getOpenMPClauseName(OMPC_firstprivate)
12644 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012645 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012646 continue;
12647 }
12648 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012649 // OpenMP [2.9.3.4, Restrictions, p.3]
12650 // A list item that appears in a reduction clause of a parallel construct
12651 // must not appear in a firstprivate clause on a worksharing or task
12652 // construct if any of the worksharing or task regions arising from the
12653 // worksharing or task construct ever bind to any of the parallel regions
12654 // arising from the parallel construct.
12655 // OpenMP [2.9.3.4, Restrictions, p.4]
12656 // A list item that appears in a reduction clause in worksharing
12657 // construct must not appear in a firstprivate clause in a task construct
12658 // encountered during execution of any of the worksharing regions arising
12659 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012660 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012661 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012662 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12663 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012664 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012665 isOpenMPWorksharingDirective(K) ||
12666 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012667 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012668 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012669 if (DVar.CKind == OMPC_reduction &&
12670 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012671 isOpenMPWorksharingDirective(DVar.DKind) ||
12672 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012673 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12674 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012675 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012676 continue;
12677 }
12678 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012679
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012680 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12681 // A list item cannot appear in both a map clause and a data-sharing
12682 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012683 //
12684 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12685 // A list item cannot appear in both a map clause and a data-sharing
12686 // attribute clause on the same construct unless the construct is a
12687 // combined construct.
12688 if ((LangOpts.OpenMP <= 45 &&
12689 isOpenMPTargetExecutionDirective(CurrDir)) ||
12690 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012691 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012692 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012693 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012694 [&ConflictKind](
12695 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12696 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012697 ConflictKind = WhereFoundClauseKind;
12698 return true;
12699 })) {
12700 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012701 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012702 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012703 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012704 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012705 continue;
12706 }
12707 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012708 }
12709
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012710 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012711 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012712 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012713 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12714 << getOpenMPClauseName(OMPC_firstprivate) << Type
12715 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12716 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012717 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012718 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012719 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012720 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012721 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012722 continue;
12723 }
12724
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012725 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012726 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012727 buildVarDecl(*this, ELoc, Type, D->getName(),
12728 D->hasAttrs() ? &D->getAttrs() : nullptr,
12729 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012730 // Generate helper private variable and initialize it with the value of the
12731 // original variable. The address of the original variable is replaced by
12732 // the address of the new private variable in the CodeGen. This new variable
12733 // is not added to IdResolver, so the code in the OpenMP region uses
12734 // original variable for proper diagnostics and variable capturing.
12735 Expr *VDInitRefExpr = nullptr;
12736 // For arrays generate initializer for single element and replace it by the
12737 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012738 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012739 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012740 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012741 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012742 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012743 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012744 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12745 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012746 InitializedEntity Entity =
12747 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012748 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12749
12750 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12751 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12752 if (Result.isInvalid())
12753 VDPrivate->setInvalidDecl();
12754 else
12755 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012756 // Remove temp variable declaration.
12757 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012758 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012759 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12760 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012761 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12762 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012763 AddInitializerToDecl(VDPrivate,
12764 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012765 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012766 }
12767 if (VDPrivate->isInvalidDecl()) {
12768 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012769 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012770 diag::note_omp_task_predetermined_firstprivate_here);
12771 }
12772 continue;
12773 }
12774 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012775 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012776 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12777 RefExpr->getExprLoc());
12778 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012779 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012780 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012781 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012782 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012783 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012784 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012785 ExprCaptures.push_back(Ref->getDecl());
12786 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012787 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012788 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012789 Vars.push_back((VD || CurContext->isDependentContext())
12790 ? RefExpr->IgnoreParens()
12791 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012792 PrivateCopies.push_back(VDPrivateRefExpr);
12793 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012794 }
12795
Alexey Bataeved09d242014-05-28 05:53:51 +000012796 if (Vars.empty())
12797 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012798
12799 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012800 Vars, PrivateCopies, Inits,
12801 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012802}
12803
Alexander Musman1bb328c2014-06-04 13:06:39 +000012804OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12805 SourceLocation StartLoc,
12806 SourceLocation LParenLoc,
12807 SourceLocation EndLoc) {
12808 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012809 SmallVector<Expr *, 8> SrcExprs;
12810 SmallVector<Expr *, 8> DstExprs;
12811 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012812 SmallVector<Decl *, 4> ExprCaptures;
12813 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012814 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012815 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012816 SourceLocation ELoc;
12817 SourceRange ERange;
12818 Expr *SimpleRefExpr = RefExpr;
12819 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012820 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012821 // It will be analyzed later.
12822 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012823 SrcExprs.push_back(nullptr);
12824 DstExprs.push_back(nullptr);
12825 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012826 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012827 ValueDecl *D = Res.first;
12828 if (!D)
12829 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012830
Alexey Bataev74caaf22016-02-20 04:09:36 +000012831 QualType Type = D->getType();
12832 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012833
12834 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12835 // A variable that appears in a lastprivate clause must not have an
12836 // incomplete type or a reference type.
12837 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012838 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012839 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012840 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012841
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012842 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12843 // A variable that is privatized must not have a const-qualified type
12844 // unless it is of class type with a mutable member. This restriction does
12845 // not apply to the firstprivate clause.
12846 //
12847 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12848 // A variable that appears in a lastprivate clause must not have a
12849 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012850 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012851 continue;
12852
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012853 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012854 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12855 // in a Construct]
12856 // Variables with the predetermined data-sharing attributes may not be
12857 // listed in data-sharing attributes clauses, except for the cases
12858 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012859 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12860 // A list item may appear in a firstprivate or lastprivate clause but not
12861 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012862 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012863 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012864 (isOpenMPDistributeDirective(CurrDir) ||
12865 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012866 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12867 Diag(ELoc, diag::err_omp_wrong_dsa)
12868 << getOpenMPClauseName(DVar.CKind)
12869 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012870 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012871 continue;
12872 }
12873
Alexey Bataevf29276e2014-06-18 04:14:57 +000012874 // OpenMP [2.14.3.5, Restrictions, p.2]
12875 // A list item that is private within a parallel region, or that appears in
12876 // the reduction clause of a parallel construct, must not appear in a
12877 // lastprivate clause on a worksharing construct if any of the corresponding
12878 // worksharing regions ever binds to any of the corresponding parallel
12879 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012880 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012881 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012882 !isOpenMPParallelDirective(CurrDir) &&
12883 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012884 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012885 if (DVar.CKind != OMPC_shared) {
12886 Diag(ELoc, diag::err_omp_required_access)
12887 << getOpenMPClauseName(OMPC_lastprivate)
12888 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012889 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012890 continue;
12891 }
12892 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012893
Alexander Musman1bb328c2014-06-04 13:06:39 +000012894 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012895 // A variable of class type (or array thereof) that appears in a
12896 // lastprivate clause requires an accessible, unambiguous default
12897 // constructor for the class type, unless the list item is also specified
12898 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012899 // A variable of class type (or array thereof) that appears in a
12900 // lastprivate clause requires an accessible, unambiguous copy assignment
12901 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012902 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012903 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12904 Type.getUnqualifiedType(), ".lastprivate.src",
12905 D->hasAttrs() ? &D->getAttrs() : nullptr);
12906 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012907 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012908 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012909 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012910 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012911 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012912 // For arrays generate assignment operation for single element and replace
12913 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012914 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12915 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012916 if (AssignmentOp.isInvalid())
12917 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012918 AssignmentOp =
12919 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012920 if (AssignmentOp.isInvalid())
12921 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012922
Alexey Bataev74caaf22016-02-20 04:09:36 +000012923 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012924 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012925 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012926 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012927 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012928 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012929 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012930 ExprCaptures.push_back(Ref->getDecl());
12931 }
12932 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012933 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012934 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012935 ExprResult RefRes = DefaultLvalueConversion(Ref);
12936 if (!RefRes.isUsable())
12937 continue;
12938 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012939 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12940 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012941 if (!PostUpdateRes.isUsable())
12942 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012943 ExprPostUpdates.push_back(
12944 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012945 }
12946 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012947 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012948 Vars.push_back((VD || CurContext->isDependentContext())
12949 ? RefExpr->IgnoreParens()
12950 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012951 SrcExprs.push_back(PseudoSrcExpr);
12952 DstExprs.push_back(PseudoDstExpr);
12953 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012954 }
12955
12956 if (Vars.empty())
12957 return nullptr;
12958
12959 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012960 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012961 buildPreInits(Context, ExprCaptures),
12962 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012963}
12964
Alexey Bataev758e55e2013-09-06 18:03:48 +000012965OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12966 SourceLocation StartLoc,
12967 SourceLocation LParenLoc,
12968 SourceLocation EndLoc) {
12969 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012970 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012971 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012972 SourceLocation ELoc;
12973 SourceRange ERange;
12974 Expr *SimpleRefExpr = RefExpr;
12975 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012976 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012977 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012978 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012979 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012980 ValueDecl *D = Res.first;
12981 if (!D)
12982 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012983
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012984 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012985 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12986 // in a Construct]
12987 // Variables with the predetermined data-sharing attributes may not be
12988 // listed in data-sharing attributes clauses, except for the cases
12989 // listed below. For these exceptions only, listing a predetermined
12990 // variable in a data-sharing attribute clause is allowed and overrides
12991 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012992 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012993 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12994 DVar.RefExpr) {
12995 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12996 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012997 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012998 continue;
12999 }
13000
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013001 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013002 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013003 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013004 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013005 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13006 ? RefExpr->IgnoreParens()
13007 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013008 }
13009
Alexey Bataeved09d242014-05-28 05:53:51 +000013010 if (Vars.empty())
13011 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013012
13013 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13014}
13015
Alexey Bataevc5e02582014-06-16 07:08:35 +000013016namespace {
13017class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13018 DSAStackTy *Stack;
13019
13020public:
13021 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013022 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13023 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013024 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13025 return false;
13026 if (DVar.CKind != OMPC_unknown)
13027 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013028 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013029 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013030 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013031 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013032 }
13033 return false;
13034 }
13035 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013036 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013037 if (Child && Visit(Child))
13038 return true;
13039 }
13040 return false;
13041 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013042 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013043};
Alexey Bataev23b69422014-06-18 07:08:49 +000013044} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013045
Alexey Bataev60da77e2016-02-29 05:54:20 +000013046namespace {
13047// Transform MemberExpression for specified FieldDecl of current class to
13048// DeclRefExpr to specified OMPCapturedExprDecl.
13049class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13050 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013051 ValueDecl *Field = nullptr;
13052 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013053
13054public:
13055 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13056 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13057
13058 ExprResult TransformMemberExpr(MemberExpr *E) {
13059 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13060 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013061 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013062 return CapturedExpr;
13063 }
13064 return BaseTransform::TransformMemberExpr(E);
13065 }
13066 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13067};
13068} // namespace
13069
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013070template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013071static T filterLookupForUDReductionAndMapper(
13072 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013073 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013074 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013075 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013076 return Res;
13077 }
13078 }
13079 return T();
13080}
13081
Alexey Bataev43b90b72018-09-12 16:31:59 +000013082static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13083 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13084
13085 for (auto RD : D->redecls()) {
13086 // Don't bother with extra checks if we already know this one isn't visible.
13087 if (RD == D)
13088 continue;
13089
13090 auto ND = cast<NamedDecl>(RD);
13091 if (LookupResult::isVisible(SemaRef, ND))
13092 return ND;
13093 }
13094
13095 return nullptr;
13096}
13097
13098static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013099argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013100 SourceLocation Loc, QualType Ty,
13101 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13102 // Find all of the associated namespaces and classes based on the
13103 // arguments we have.
13104 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13105 Sema::AssociatedClassSet AssociatedClasses;
13106 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13107 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13108 AssociatedClasses);
13109
13110 // C++ [basic.lookup.argdep]p3:
13111 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13112 // and let Y be the lookup set produced by argument dependent
13113 // lookup (defined as follows). If X contains [...] then Y is
13114 // empty. Otherwise Y is the set of declarations found in the
13115 // namespaces associated with the argument types as described
13116 // below. The set of declarations found by the lookup of the name
13117 // is the union of X and Y.
13118 //
13119 // Here, we compute Y and add its members to the overloaded
13120 // candidate set.
13121 for (auto *NS : AssociatedNamespaces) {
13122 // When considering an associated namespace, the lookup is the
13123 // same as the lookup performed when the associated namespace is
13124 // used as a qualifier (3.4.3.2) except that:
13125 //
13126 // -- Any using-directives in the associated namespace are
13127 // ignored.
13128 //
13129 // -- Any namespace-scope friend functions declared in
13130 // associated classes are visible within their respective
13131 // namespaces even if they are not visible during an ordinary
13132 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013133 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013134 for (auto *D : R) {
13135 auto *Underlying = D;
13136 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13137 Underlying = USD->getTargetDecl();
13138
Michael Kruse4304e9d2019-02-19 16:38:20 +000013139 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13140 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013141 continue;
13142
13143 if (!SemaRef.isVisible(D)) {
13144 D = findAcceptableDecl(SemaRef, D);
13145 if (!D)
13146 continue;
13147 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13148 Underlying = USD->getTargetDecl();
13149 }
13150 Lookups.emplace_back();
13151 Lookups.back().addDecl(Underlying);
13152 }
13153 }
13154}
13155
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013156static ExprResult
13157buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13158 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13159 const DeclarationNameInfo &ReductionId, QualType Ty,
13160 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13161 if (ReductionIdScopeSpec.isInvalid())
13162 return ExprError();
13163 SmallVector<UnresolvedSet<8>, 4> Lookups;
13164 if (S) {
13165 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13166 Lookup.suppressDiagnostics();
13167 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013168 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013169 do {
13170 S = S->getParent();
13171 } while (S && !S->isDeclScope(D));
13172 if (S)
13173 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013174 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013175 Lookups.back().append(Lookup.begin(), Lookup.end());
13176 Lookup.clear();
13177 }
13178 } else if (auto *ULE =
13179 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13180 Lookups.push_back(UnresolvedSet<8>());
13181 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013182 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013183 if (D == PrevD)
13184 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013185 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013186 Lookups.back().addDecl(DRD);
13187 PrevD = D;
13188 }
13189 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013190 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13191 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013192 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013193 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013194 return !D->isInvalidDecl() &&
13195 (D->getType()->isDependentType() ||
13196 D->getType()->isInstantiationDependentType() ||
13197 D->getType()->containsUnexpandedParameterPack());
13198 })) {
13199 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013200 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013201 if (Set.empty())
13202 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013203 ResSet.append(Set.begin(), Set.end());
13204 // The last item marks the end of all declarations at the specified scope.
13205 ResSet.addDecl(Set[Set.size() - 1]);
13206 }
13207 return UnresolvedLookupExpr::Create(
13208 SemaRef.Context, /*NamingClass=*/nullptr,
13209 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13210 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13211 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013212 // Lookup inside the classes.
13213 // C++ [over.match.oper]p3:
13214 // For a unary operator @ with an operand of a type whose
13215 // cv-unqualified version is T1, and for a binary operator @ with
13216 // a left operand of a type whose cv-unqualified version is T1 and
13217 // a right operand of a type whose cv-unqualified version is T2,
13218 // three sets of candidate functions, designated member
13219 // candidates, non-member candidates and built-in candidates, are
13220 // constructed as follows:
13221 // -- If T1 is a complete class type or a class currently being
13222 // defined, the set of member candidates is the result of the
13223 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13224 // the set of member candidates is empty.
13225 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13226 Lookup.suppressDiagnostics();
13227 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13228 // Complete the type if it can be completed.
13229 // If the type is neither complete nor being defined, bail out now.
13230 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13231 TyRec->getDecl()->getDefinition()) {
13232 Lookup.clear();
13233 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13234 if (Lookup.empty()) {
13235 Lookups.emplace_back();
13236 Lookups.back().append(Lookup.begin(), Lookup.end());
13237 }
13238 }
13239 }
13240 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013241 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013242 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013243 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13244 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13245 if (!D->isInvalidDecl() &&
13246 SemaRef.Context.hasSameType(D->getType(), Ty))
13247 return D;
13248 return nullptr;
13249 }))
13250 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13251 VK_LValue, Loc);
13252 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013253 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13254 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13255 if (!D->isInvalidDecl() &&
13256 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13257 !Ty.isMoreQualifiedThan(D->getType()))
13258 return D;
13259 return nullptr;
13260 })) {
13261 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13262 /*DetectVirtual=*/false);
13263 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13264 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13265 VD->getType().getUnqualifiedType()))) {
13266 if (SemaRef.CheckBaseClassAccess(
13267 Loc, VD->getType(), Ty, Paths.front(),
13268 /*DiagID=*/0) != Sema::AR_inaccessible) {
13269 SemaRef.BuildBasePathArray(Paths, BasePath);
13270 return SemaRef.BuildDeclRefExpr(
13271 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13272 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013273 }
13274 }
13275 }
13276 }
13277 if (ReductionIdScopeSpec.isSet()) {
13278 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13279 return ExprError();
13280 }
13281 return ExprEmpty();
13282}
13283
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013284namespace {
13285/// Data for the reduction-based clauses.
13286struct ReductionData {
13287 /// List of original reduction items.
13288 SmallVector<Expr *, 8> Vars;
13289 /// List of private copies of the reduction items.
13290 SmallVector<Expr *, 8> Privates;
13291 /// LHS expressions for the reduction_op expressions.
13292 SmallVector<Expr *, 8> LHSs;
13293 /// RHS expressions for the reduction_op expressions.
13294 SmallVector<Expr *, 8> RHSs;
13295 /// Reduction operation expression.
13296 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013297 /// Taskgroup descriptors for the corresponding reduction items in
13298 /// in_reduction clauses.
13299 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013300 /// List of captures for clause.
13301 SmallVector<Decl *, 4> ExprCaptures;
13302 /// List of postupdate expressions.
13303 SmallVector<Expr *, 4> ExprPostUpdates;
13304 ReductionData() = delete;
13305 /// Reserves required memory for the reduction data.
13306 ReductionData(unsigned Size) {
13307 Vars.reserve(Size);
13308 Privates.reserve(Size);
13309 LHSs.reserve(Size);
13310 RHSs.reserve(Size);
13311 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013312 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013313 ExprCaptures.reserve(Size);
13314 ExprPostUpdates.reserve(Size);
13315 }
13316 /// Stores reduction item and reduction operation only (required for dependent
13317 /// reduction item).
13318 void push(Expr *Item, Expr *ReductionOp) {
13319 Vars.emplace_back(Item);
13320 Privates.emplace_back(nullptr);
13321 LHSs.emplace_back(nullptr);
13322 RHSs.emplace_back(nullptr);
13323 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013324 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013325 }
13326 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013327 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13328 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013329 Vars.emplace_back(Item);
13330 Privates.emplace_back(Private);
13331 LHSs.emplace_back(LHS);
13332 RHSs.emplace_back(RHS);
13333 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013334 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013335 }
13336};
13337} // namespace
13338
Alexey Bataeve3727102018-04-18 15:57:46 +000013339static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013340 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13341 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13342 const Expr *Length = OASE->getLength();
13343 if (Length == nullptr) {
13344 // For array sections of the form [1:] or [:], we would need to analyze
13345 // the lower bound...
13346 if (OASE->getColonLoc().isValid())
13347 return false;
13348
13349 // This is an array subscript which has implicit length 1!
13350 SingleElement = true;
13351 ArraySizes.push_back(llvm::APSInt::get(1));
13352 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013353 Expr::EvalResult Result;
13354 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013355 return false;
13356
Fangrui Song407659a2018-11-30 23:41:18 +000013357 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013358 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13359 ArraySizes.push_back(ConstantLengthValue);
13360 }
13361
13362 // Get the base of this array section and walk up from there.
13363 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13364
13365 // We require length = 1 for all array sections except the right-most to
13366 // guarantee that the memory region is contiguous and has no holes in it.
13367 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13368 Length = TempOASE->getLength();
13369 if (Length == nullptr) {
13370 // For array sections of the form [1:] or [:], we would need to analyze
13371 // the lower bound...
13372 if (OASE->getColonLoc().isValid())
13373 return false;
13374
13375 // This is an array subscript which has implicit length 1!
13376 ArraySizes.push_back(llvm::APSInt::get(1));
13377 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013378 Expr::EvalResult Result;
13379 if (!Length->EvaluateAsInt(Result, Context))
13380 return false;
13381
13382 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13383 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013384 return false;
13385
13386 ArraySizes.push_back(ConstantLengthValue);
13387 }
13388 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13389 }
13390
13391 // If we have a single element, we don't need to add the implicit lengths.
13392 if (!SingleElement) {
13393 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13394 // Has implicit length 1!
13395 ArraySizes.push_back(llvm::APSInt::get(1));
13396 Base = TempASE->getBase()->IgnoreParenImpCasts();
13397 }
13398 }
13399
13400 // This array section can be privatized as a single value or as a constant
13401 // sized array.
13402 return true;
13403}
13404
Alexey Bataeve3727102018-04-18 15:57:46 +000013405static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013406 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13407 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13408 SourceLocation ColonLoc, SourceLocation EndLoc,
13409 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013410 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013411 DeclarationName DN = ReductionId.getName();
13412 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013413 BinaryOperatorKind BOK = BO_Comma;
13414
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013415 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013416 // OpenMP [2.14.3.6, reduction clause]
13417 // C
13418 // reduction-identifier is either an identifier or one of the following
13419 // operators: +, -, *, &, |, ^, && and ||
13420 // C++
13421 // reduction-identifier is either an id-expression or one of the following
13422 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013423 switch (OOK) {
13424 case OO_Plus:
13425 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013426 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013427 break;
13428 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013429 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013430 break;
13431 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013432 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013433 break;
13434 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013435 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013436 break;
13437 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013438 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013439 break;
13440 case OO_AmpAmp:
13441 BOK = BO_LAnd;
13442 break;
13443 case OO_PipePipe:
13444 BOK = BO_LOr;
13445 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013446 case OO_New:
13447 case OO_Delete:
13448 case OO_Array_New:
13449 case OO_Array_Delete:
13450 case OO_Slash:
13451 case OO_Percent:
13452 case OO_Tilde:
13453 case OO_Exclaim:
13454 case OO_Equal:
13455 case OO_Less:
13456 case OO_Greater:
13457 case OO_LessEqual:
13458 case OO_GreaterEqual:
13459 case OO_PlusEqual:
13460 case OO_MinusEqual:
13461 case OO_StarEqual:
13462 case OO_SlashEqual:
13463 case OO_PercentEqual:
13464 case OO_CaretEqual:
13465 case OO_AmpEqual:
13466 case OO_PipeEqual:
13467 case OO_LessLess:
13468 case OO_GreaterGreater:
13469 case OO_LessLessEqual:
13470 case OO_GreaterGreaterEqual:
13471 case OO_EqualEqual:
13472 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013473 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013474 case OO_PlusPlus:
13475 case OO_MinusMinus:
13476 case OO_Comma:
13477 case OO_ArrowStar:
13478 case OO_Arrow:
13479 case OO_Call:
13480 case OO_Subscript:
13481 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013482 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013483 case NUM_OVERLOADED_OPERATORS:
13484 llvm_unreachable("Unexpected reduction identifier");
13485 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013486 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013487 if (II->isStr("max"))
13488 BOK = BO_GT;
13489 else if (II->isStr("min"))
13490 BOK = BO_LT;
13491 }
13492 break;
13493 }
13494 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013495 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013496 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013497 else
13498 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013499 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013500
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013501 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13502 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013503 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013504 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013505 // OpenMP [2.1, C/C++]
13506 // A list item is a variable or array section, subject to the restrictions
13507 // specified in Section 2.4 on page 42 and in each of the sections
13508 // describing clauses and directives for which a list appears.
13509 // OpenMP [2.14.3.3, Restrictions, p.1]
13510 // A variable that is part of another variable (as an array or
13511 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013512 if (!FirstIter && IR != ER)
13513 ++IR;
13514 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013515 SourceLocation ELoc;
13516 SourceRange ERange;
13517 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013518 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013519 /*AllowArraySection=*/true);
13520 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013521 // Try to find 'declare reduction' corresponding construct before using
13522 // builtin/overloaded operators.
13523 QualType Type = Context.DependentTy;
13524 CXXCastPath BasePath;
13525 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013526 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013527 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013528 Expr *ReductionOp = nullptr;
13529 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013530 (DeclareReductionRef.isUnset() ||
13531 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013532 ReductionOp = DeclareReductionRef.get();
13533 // It will be analyzed later.
13534 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013535 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013536 ValueDecl *D = Res.first;
13537 if (!D)
13538 continue;
13539
Alexey Bataev88202be2017-07-27 13:20:36 +000013540 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013541 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013542 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13543 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013544 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013545 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013546 } else if (OASE) {
13547 QualType BaseType =
13548 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13549 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013550 Type = ATy->getElementType();
13551 else
13552 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013553 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013554 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013555 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013556 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013557 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013558
Alexey Bataevc5e02582014-06-16 07:08:35 +000013559 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13560 // A variable that appears in a private clause must not have an incomplete
13561 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013562 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013563 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013564 continue;
13565 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013566 // A list item that appears in a reduction clause must not be
13567 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013568 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13569 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013570 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013571
13572 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013573 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13574 // If a list-item is a reference type then it must bind to the same object
13575 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013576 if (!ASE && !OASE) {
13577 if (VD) {
13578 VarDecl *VDDef = VD->getDefinition();
13579 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13580 DSARefChecker Check(Stack);
13581 if (Check.Visit(VDDef->getInit())) {
13582 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13583 << getOpenMPClauseName(ClauseKind) << ERange;
13584 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13585 continue;
13586 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013587 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013588 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013589
Alexey Bataevbc529672018-09-28 19:33:14 +000013590 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13591 // in a Construct]
13592 // Variables with the predetermined data-sharing attributes may not be
13593 // listed in data-sharing attributes clauses, except for the cases
13594 // listed below. For these exceptions only, listing a predetermined
13595 // variable in a data-sharing attribute clause is allowed and overrides
13596 // the variable's predetermined data-sharing attributes.
13597 // OpenMP [2.14.3.6, Restrictions, p.3]
13598 // Any number of reduction clauses can be specified on the directive,
13599 // but a list item can appear only once in the reduction clauses for that
13600 // directive.
13601 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13602 if (DVar.CKind == OMPC_reduction) {
13603 S.Diag(ELoc, diag::err_omp_once_referenced)
13604 << getOpenMPClauseName(ClauseKind);
13605 if (DVar.RefExpr)
13606 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13607 continue;
13608 }
13609 if (DVar.CKind != OMPC_unknown) {
13610 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13611 << getOpenMPClauseName(DVar.CKind)
13612 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013613 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013614 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013615 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013616
13617 // OpenMP [2.14.3.6, Restrictions, p.1]
13618 // A list item that appears in a reduction clause of a worksharing
13619 // construct must be shared in the parallel regions to which any of the
13620 // worksharing regions arising from the worksharing construct bind.
13621 if (isOpenMPWorksharingDirective(CurrDir) &&
13622 !isOpenMPParallelDirective(CurrDir) &&
13623 !isOpenMPTeamsDirective(CurrDir)) {
13624 DVar = Stack->getImplicitDSA(D, true);
13625 if (DVar.CKind != OMPC_shared) {
13626 S.Diag(ELoc, diag::err_omp_required_access)
13627 << getOpenMPClauseName(OMPC_reduction)
13628 << getOpenMPClauseName(OMPC_shared);
13629 reportOriginalDsa(S, Stack, D, DVar);
13630 continue;
13631 }
13632 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013633 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013634
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013635 // Try to find 'declare reduction' corresponding construct before using
13636 // builtin/overloaded operators.
13637 CXXCastPath BasePath;
13638 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013639 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013640 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13641 if (DeclareReductionRef.isInvalid())
13642 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013643 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013644 (DeclareReductionRef.isUnset() ||
13645 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013646 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013647 continue;
13648 }
13649 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13650 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013651 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013652 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013653 << Type << ReductionIdRange;
13654 continue;
13655 }
13656
13657 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13658 // The type of a list item that appears in a reduction clause must be valid
13659 // for the reduction-identifier. For a max or min reduction in C, the type
13660 // of the list item must be an allowed arithmetic data type: char, int,
13661 // float, double, or _Bool, possibly modified with long, short, signed, or
13662 // unsigned. For a max or min reduction in C++, the type of the list item
13663 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13664 // double, or bool, possibly modified with long, short, signed, or unsigned.
13665 if (DeclareReductionRef.isUnset()) {
13666 if ((BOK == BO_GT || BOK == BO_LT) &&
13667 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013668 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13669 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013670 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013671 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013672 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13673 VarDecl::DeclarationOnly;
13674 S.Diag(D->getLocation(),
13675 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013676 << D;
13677 }
13678 continue;
13679 }
13680 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013681 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013682 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13683 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013684 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013685 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13686 VarDecl::DeclarationOnly;
13687 S.Diag(D->getLocation(),
13688 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013689 << D;
13690 }
13691 continue;
13692 }
13693 }
13694
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013695 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013696 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13697 D->hasAttrs() ? &D->getAttrs() : nullptr);
13698 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13699 D->hasAttrs() ? &D->getAttrs() : nullptr);
13700 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013701
13702 // Try if we can determine constant lengths for all array sections and avoid
13703 // the VLA.
13704 bool ConstantLengthOASE = false;
13705 if (OASE) {
13706 bool SingleElement;
13707 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013708 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013709 Context, OASE, SingleElement, ArraySizes);
13710
13711 // If we don't have a single element, we must emit a constant array type.
13712 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013713 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013714 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13715 ArrayType::Normal,
13716 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013717 }
13718 }
13719
13720 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013721 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013722 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013723 if (!Context.getTargetInfo().isVLASupported()) {
13724 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13725 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13726 S.Diag(ELoc, diag::note_vla_unsupported);
13727 } else {
13728 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13729 S.targetDiag(ELoc, diag::note_vla_unsupported);
13730 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013731 continue;
13732 }
David Majnemer9d168222016-08-05 17:44:54 +000013733 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013734 // Create pseudo array type for private copy. The size for this array will
13735 // be generated during codegen.
13736 // For array subscripts or single variables Private Ty is the same as Type
13737 // (type of the variable or single array element).
13738 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013739 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013740 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013741 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013742 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013743 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013744 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013745 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013746 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013747 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013748 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13749 D->hasAttrs() ? &D->getAttrs() : nullptr,
13750 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013751 // Add initializer for private variable.
13752 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013753 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13754 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013755 if (DeclareReductionRef.isUsable()) {
13756 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13757 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13758 if (DRD->getInitializer()) {
13759 Init = DRDRef;
13760 RHSVD->setInit(DRDRef);
13761 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013762 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013763 } else {
13764 switch (BOK) {
13765 case BO_Add:
13766 case BO_Xor:
13767 case BO_Or:
13768 case BO_LOr:
13769 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13770 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013771 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013772 break;
13773 case BO_Mul:
13774 case BO_LAnd:
13775 if (Type->isScalarType() || Type->isAnyComplexType()) {
13776 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013777 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013778 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013779 break;
13780 case BO_And: {
13781 // '&' reduction op - initializer is '~0'.
13782 QualType OrigType = Type;
13783 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13784 Type = ComplexTy->getElementType();
13785 if (Type->isRealFloatingType()) {
13786 llvm::APFloat InitValue =
13787 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13788 /*isIEEE=*/true);
13789 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13790 Type, ELoc);
13791 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013792 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013793 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13794 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13795 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13796 }
13797 if (Init && OrigType->isAnyComplexType()) {
13798 // Init = 0xFFFF + 0xFFFFi;
13799 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013800 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013801 }
13802 Type = OrigType;
13803 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013804 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013805 case BO_LT:
13806 case BO_GT: {
13807 // 'min' reduction op - initializer is 'Largest representable number in
13808 // the reduction list item type'.
13809 // 'max' reduction op - initializer is 'Least representable number in
13810 // the reduction list item type'.
13811 if (Type->isIntegerType() || Type->isPointerType()) {
13812 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013813 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013814 QualType IntTy =
13815 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13816 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013817 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13818 : llvm::APInt::getMinValue(Size)
13819 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13820 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013821 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13822 if (Type->isPointerType()) {
13823 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013824 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013825 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013826 if (CastExpr.isInvalid())
13827 continue;
13828 Init = CastExpr.get();
13829 }
13830 } else if (Type->isRealFloatingType()) {
13831 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13832 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13833 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13834 Type, ELoc);
13835 }
13836 break;
13837 }
13838 case BO_PtrMemD:
13839 case BO_PtrMemI:
13840 case BO_MulAssign:
13841 case BO_Div:
13842 case BO_Rem:
13843 case BO_Sub:
13844 case BO_Shl:
13845 case BO_Shr:
13846 case BO_LE:
13847 case BO_GE:
13848 case BO_EQ:
13849 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013850 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013851 case BO_AndAssign:
13852 case BO_XorAssign:
13853 case BO_OrAssign:
13854 case BO_Assign:
13855 case BO_AddAssign:
13856 case BO_SubAssign:
13857 case BO_DivAssign:
13858 case BO_RemAssign:
13859 case BO_ShlAssign:
13860 case BO_ShrAssign:
13861 case BO_Comma:
13862 llvm_unreachable("Unexpected reduction operation");
13863 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013864 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013865 if (Init && DeclareReductionRef.isUnset())
13866 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13867 else if (!Init)
13868 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013869 if (RHSVD->isInvalidDecl())
13870 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013871 if (!RHSVD->hasInit() &&
13872 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013873 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13874 << Type << ReductionIdRange;
13875 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13876 VarDecl::DeclarationOnly;
13877 S.Diag(D->getLocation(),
13878 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013879 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013880 continue;
13881 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013882 // Store initializer for single element in private copy. Will be used during
13883 // codegen.
13884 PrivateVD->setInit(RHSVD->getInit());
13885 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013886 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013887 ExprResult ReductionOp;
13888 if (DeclareReductionRef.isUsable()) {
13889 QualType RedTy = DeclareReductionRef.get()->getType();
13890 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013891 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13892 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013893 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013894 LHS = S.DefaultLvalueConversion(LHS.get());
13895 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013896 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13897 CK_UncheckedDerivedToBase, LHS.get(),
13898 &BasePath, LHS.get()->getValueKind());
13899 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13900 CK_UncheckedDerivedToBase, RHS.get(),
13901 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013902 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013903 FunctionProtoType::ExtProtoInfo EPI;
13904 QualType Params[] = {PtrRedTy, PtrRedTy};
13905 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13906 auto *OVE = new (Context) OpaqueValueExpr(
13907 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013908 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013909 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013910 ReductionOp =
13911 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013912 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013913 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013914 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013915 if (ReductionOp.isUsable()) {
13916 if (BOK != BO_LT && BOK != BO_GT) {
13917 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013918 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013919 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013920 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013921 auto *ConditionalOp = new (Context)
13922 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13923 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013924 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013925 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013926 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013927 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013928 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013929 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13930 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013931 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013932 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013933 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013934 }
13935
Alexey Bataevfa312f32017-07-21 18:48:21 +000013936 // OpenMP [2.15.4.6, Restrictions, p.2]
13937 // A list item that appears in an in_reduction clause of a task construct
13938 // must appear in a task_reduction clause of a construct associated with a
13939 // taskgroup region that includes the participating task in its taskgroup
13940 // set. The construct associated with the innermost region that meets this
13941 // condition must specify the same reduction-identifier as the in_reduction
13942 // clause.
13943 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013944 SourceRange ParentSR;
13945 BinaryOperatorKind ParentBOK;
13946 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013947 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013948 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013949 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13950 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013951 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013952 Stack->getTopMostTaskgroupReductionData(
13953 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013954 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13955 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13956 if (!IsParentBOK && !IsParentReductionOp) {
13957 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13958 continue;
13959 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013960 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13961 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13962 IsParentReductionOp) {
13963 bool EmitError = true;
13964 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13965 llvm::FoldingSetNodeID RedId, ParentRedId;
13966 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13967 DeclareReductionRef.get()->Profile(RedId, Context,
13968 /*Canonical=*/true);
13969 EmitError = RedId != ParentRedId;
13970 }
13971 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013972 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013973 diag::err_omp_reduction_identifier_mismatch)
13974 << ReductionIdRange << RefExpr->getSourceRange();
13975 S.Diag(ParentSR.getBegin(),
13976 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013977 << ParentSR
13978 << (IsParentBOK ? ParentBOKDSA.RefExpr
13979 : ParentReductionOpDSA.RefExpr)
13980 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013981 continue;
13982 }
13983 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013984 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13985 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013986 }
13987
Alexey Bataev60da77e2016-02-29 05:54:20 +000013988 DeclRefExpr *Ref = nullptr;
13989 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013990 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013991 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013992 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013993 VarsExpr =
13994 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13995 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013996 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013997 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013998 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013999 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014000 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014001 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014002 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014003 if (!RefRes.isUsable())
14004 continue;
14005 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014006 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14007 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014008 if (!PostUpdateRes.isUsable())
14009 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014010 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14011 Stack->getCurrentDirective() == OMPD_taskgroup) {
14012 S.Diag(RefExpr->getExprLoc(),
14013 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014014 << RefExpr->getSourceRange();
14015 continue;
14016 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014017 RD.ExprPostUpdates.emplace_back(
14018 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014019 }
14020 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014021 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014022 // All reduction items are still marked as reduction (to do not increase
14023 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014024 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014025 if (CurrDir == OMPD_taskgroup) {
14026 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014027 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14028 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014029 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014030 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014031 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014032 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14033 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014034 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014035 return RD.Vars.empty();
14036}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014037
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014038OMPClause *Sema::ActOnOpenMPReductionClause(
14039 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14040 SourceLocation ColonLoc, SourceLocation EndLoc,
14041 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14042 ArrayRef<Expr *> UnresolvedReductions) {
14043 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014044 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014045 StartLoc, LParenLoc, ColonLoc, EndLoc,
14046 ReductionIdScopeSpec, ReductionId,
14047 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014048 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014049
Alexey Bataevc5e02582014-06-16 07:08:35 +000014050 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014051 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14052 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14053 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14054 buildPreInits(Context, RD.ExprCaptures),
14055 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014056}
14057
Alexey Bataev169d96a2017-07-18 20:17:46 +000014058OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14059 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14060 SourceLocation ColonLoc, SourceLocation EndLoc,
14061 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14062 ArrayRef<Expr *> UnresolvedReductions) {
14063 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014064 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14065 StartLoc, LParenLoc, ColonLoc, EndLoc,
14066 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014067 UnresolvedReductions, RD))
14068 return nullptr;
14069
14070 return OMPTaskReductionClause::Create(
14071 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14072 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14073 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14074 buildPreInits(Context, RD.ExprCaptures),
14075 buildPostUpdate(*this, RD.ExprPostUpdates));
14076}
14077
Alexey Bataevfa312f32017-07-21 18:48:21 +000014078OMPClause *Sema::ActOnOpenMPInReductionClause(
14079 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14080 SourceLocation ColonLoc, SourceLocation EndLoc,
14081 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14082 ArrayRef<Expr *> UnresolvedReductions) {
14083 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014084 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014085 StartLoc, LParenLoc, ColonLoc, EndLoc,
14086 ReductionIdScopeSpec, ReductionId,
14087 UnresolvedReductions, RD))
14088 return nullptr;
14089
14090 return OMPInReductionClause::Create(
14091 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14092 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014093 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014094 buildPreInits(Context, RD.ExprCaptures),
14095 buildPostUpdate(*this, RD.ExprPostUpdates));
14096}
14097
Alexey Bataevecba70f2016-04-12 11:02:11 +000014098bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14099 SourceLocation LinLoc) {
14100 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14101 LinKind == OMPC_LINEAR_unknown) {
14102 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14103 return true;
14104 }
14105 return false;
14106}
14107
Alexey Bataeve3727102018-04-18 15:57:46 +000014108bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014109 OpenMPLinearClauseKind LinKind,
14110 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014111 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014112 // A variable must not have an incomplete type or a reference type.
14113 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14114 return true;
14115 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14116 !Type->isReferenceType()) {
14117 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14118 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14119 return true;
14120 }
14121 Type = Type.getNonReferenceType();
14122
Joel E. Dennybae586f2019-01-04 22:12:13 +000014123 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14124 // A variable that is privatized must not have a const-qualified type
14125 // unless it is of class type with a mutable member. This restriction does
14126 // not apply to the firstprivate clause.
14127 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014128 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014129
14130 // A list item must be of integral or pointer type.
14131 Type = Type.getUnqualifiedType().getCanonicalType();
14132 const auto *Ty = Type.getTypePtrOrNull();
14133 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
14134 !Ty->isPointerType())) {
14135 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14136 if (D) {
14137 bool IsDecl =
14138 !VD ||
14139 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14140 Diag(D->getLocation(),
14141 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14142 << D;
14143 }
14144 return true;
14145 }
14146 return false;
14147}
14148
Alexey Bataev182227b2015-08-20 10:54:39 +000014149OMPClause *Sema::ActOnOpenMPLinearClause(
14150 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14151 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14152 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014153 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014154 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014155 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014156 SmallVector<Decl *, 4> ExprCaptures;
14157 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014158 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014159 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014160 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014161 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014162 SourceLocation ELoc;
14163 SourceRange ERange;
14164 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014165 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014166 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014167 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014168 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014169 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014170 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014171 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014172 ValueDecl *D = Res.first;
14173 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014174 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014175
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014176 QualType Type = D->getType();
14177 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014178
14179 // OpenMP [2.14.3.7, linear clause]
14180 // A list-item cannot appear in more than one linear clause.
14181 // A list-item that appears in a linear clause cannot appear in any
14182 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014183 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014184 if (DVar.RefExpr) {
14185 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14186 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014187 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014188 continue;
14189 }
14190
Alexey Bataevecba70f2016-04-12 11:02:11 +000014191 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014192 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014193 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014194
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014195 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014196 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014197 buildVarDecl(*this, ELoc, Type, D->getName(),
14198 D->hasAttrs() ? &D->getAttrs() : nullptr,
14199 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014200 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014201 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014202 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014203 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014204 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014205 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014206 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014207 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014208 ExprCaptures.push_back(Ref->getDecl());
14209 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14210 ExprResult RefRes = DefaultLvalueConversion(Ref);
14211 if (!RefRes.isUsable())
14212 continue;
14213 ExprResult PostUpdateRes =
14214 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14215 SimpleRefExpr, RefRes.get());
14216 if (!PostUpdateRes.isUsable())
14217 continue;
14218 ExprPostUpdates.push_back(
14219 IgnoredValueConversions(PostUpdateRes.get()).get());
14220 }
14221 }
14222 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014223 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014224 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014225 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014226 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014227 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014228 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014229 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014230
14231 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014232 Vars.push_back((VD || CurContext->isDependentContext())
14233 ? RefExpr->IgnoreParens()
14234 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014235 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014236 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014237 }
14238
14239 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014240 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014241
14242 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014243 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014244 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14245 !Step->isInstantiationDependent() &&
14246 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014247 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014248 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014249 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014250 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014251 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014252
Alexander Musman3276a272015-03-21 10:12:56 +000014253 // Build var to save the step value.
14254 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014255 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014256 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014257 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014258 ExprResult CalcStep =
14259 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014260 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014261
Alexander Musman8dba6642014-04-22 13:09:42 +000014262 // Warn about zero linear step (it would be probably better specified as
14263 // making corresponding variables 'const').
14264 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014265 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14266 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014267 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14268 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014269 if (!IsConstant && CalcStep.isUsable()) {
14270 // Calculate the step beforehand instead of doing this on each iteration.
14271 // (This is not used if the number of iterations may be kfold-ed).
14272 CalcStepExpr = CalcStep.get();
14273 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014274 }
14275
Alexey Bataev182227b2015-08-20 10:54:39 +000014276 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14277 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014278 StepExpr, CalcStepExpr,
14279 buildPreInits(Context, ExprCaptures),
14280 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014281}
14282
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014283static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14284 Expr *NumIterations, Sema &SemaRef,
14285 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014286 // Walk the vars and build update/final expressions for the CodeGen.
14287 SmallVector<Expr *, 8> Updates;
14288 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014289 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014290 Expr *Step = Clause.getStep();
14291 Expr *CalcStep = Clause.getCalcStep();
14292 // OpenMP [2.14.3.7, linear clause]
14293 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014294 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014295 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014296 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014297 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14298 bool HasErrors = false;
14299 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014300 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014301 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14302 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014303 SourceLocation ELoc;
14304 SourceRange ERange;
14305 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014306 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014307 ValueDecl *D = Res.first;
14308 if (Res.second || !D) {
14309 Updates.push_back(nullptr);
14310 Finals.push_back(nullptr);
14311 HasErrors = true;
14312 continue;
14313 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014314 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014315 // OpenMP [2.15.11, distribute simd Construct]
14316 // A list item may not appear in a linear clause, unless it is the loop
14317 // iteration variable.
14318 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14319 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14320 SemaRef.Diag(ELoc,
14321 diag::err_omp_linear_distribute_var_non_loop_iteration);
14322 Updates.push_back(nullptr);
14323 Finals.push_back(nullptr);
14324 HasErrors = true;
14325 continue;
14326 }
Alexander Musman3276a272015-03-21 10:12:56 +000014327 Expr *InitExpr = *CurInit;
14328
14329 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014330 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014331 Expr *CapturedRef;
14332 if (LinKind == OMPC_LINEAR_uval)
14333 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14334 else
14335 CapturedRef =
14336 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14337 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14338 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014339
14340 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014341 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014342 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014343 Update = buildCounterUpdate(
14344 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14345 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014346 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014347 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014348 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014349 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014350
14351 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014352 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014353 if (!Info.first)
14354 Final =
14355 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014356 InitExpr, NumIterations, Step, /*Subtract=*/false,
14357 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014358 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014359 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014360 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014361 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014362
Alexander Musman3276a272015-03-21 10:12:56 +000014363 if (!Update.isUsable() || !Final.isUsable()) {
14364 Updates.push_back(nullptr);
14365 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014366 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014367 HasErrors = true;
14368 } else {
14369 Updates.push_back(Update.get());
14370 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014371 if (!Info.first)
14372 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014373 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014374 ++CurInit;
14375 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014376 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014377 if (Expr *S = Clause.getStep())
14378 UsedExprs.push_back(S);
14379 // Fill the remaining part with the nullptr.
14380 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014381 Clause.setUpdates(Updates);
14382 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014383 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014384 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014385}
14386
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014387OMPClause *Sema::ActOnOpenMPAlignedClause(
14388 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14389 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014390 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014391 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014392 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14393 SourceLocation ELoc;
14394 SourceRange ERange;
14395 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014396 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014397 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014398 // It will be analyzed later.
14399 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014400 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014401 ValueDecl *D = Res.first;
14402 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014403 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014404
Alexey Bataev1efd1662016-03-29 10:59:56 +000014405 QualType QType = D->getType();
14406 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014407
14408 // OpenMP [2.8.1, simd construct, Restrictions]
14409 // The type of list items appearing in the aligned clause must be
14410 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014411 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014412 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014413 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014414 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014415 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014416 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014417 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014418 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014419 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014420 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014421 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014422 continue;
14423 }
14424
14425 // OpenMP [2.8.1, simd construct, Restrictions]
14426 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014427 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000014428 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014429 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14430 << getOpenMPClauseName(OMPC_aligned);
14431 continue;
14432 }
14433
Alexey Bataev1efd1662016-03-29 10:59:56 +000014434 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014435 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014436 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14437 Vars.push_back(DefaultFunctionArrayConversion(
14438 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14439 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014440 }
14441
14442 // OpenMP [2.8.1, simd construct, Description]
14443 // The parameter of the aligned clause, alignment, must be a constant
14444 // positive integer expression.
14445 // If no optional parameter is specified, implementation-defined default
14446 // alignments for SIMD instructions on the target platforms are assumed.
14447 if (Alignment != nullptr) {
14448 ExprResult AlignResult =
14449 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14450 if (AlignResult.isInvalid())
14451 return nullptr;
14452 Alignment = AlignResult.get();
14453 }
14454 if (Vars.empty())
14455 return nullptr;
14456
14457 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14458 EndLoc, Vars, Alignment);
14459}
14460
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014461OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14462 SourceLocation StartLoc,
14463 SourceLocation LParenLoc,
14464 SourceLocation EndLoc) {
14465 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014466 SmallVector<Expr *, 8> SrcExprs;
14467 SmallVector<Expr *, 8> DstExprs;
14468 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014469 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014470 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14471 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014472 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014473 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014474 SrcExprs.push_back(nullptr);
14475 DstExprs.push_back(nullptr);
14476 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014477 continue;
14478 }
14479
Alexey Bataeved09d242014-05-28 05:53:51 +000014480 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014481 // OpenMP [2.1, C/C++]
14482 // A list item is a variable name.
14483 // OpenMP [2.14.4.1, Restrictions, p.1]
14484 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014485 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014486 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014487 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14488 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014489 continue;
14490 }
14491
14492 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014493 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014494
14495 QualType Type = VD->getType();
14496 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14497 // It will be analyzed later.
14498 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014499 SrcExprs.push_back(nullptr);
14500 DstExprs.push_back(nullptr);
14501 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014502 continue;
14503 }
14504
14505 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14506 // A list item that appears in a copyin clause must be threadprivate.
14507 if (!DSAStack->isThreadPrivate(VD)) {
14508 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014509 << getOpenMPClauseName(OMPC_copyin)
14510 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014511 continue;
14512 }
14513
14514 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14515 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014516 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014517 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014518 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14519 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014520 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014521 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014522 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014523 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014524 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014525 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014526 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014527 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014528 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014529 // For arrays generate assignment operation for single element and replace
14530 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014531 ExprResult AssignmentOp =
14532 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14533 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014534 if (AssignmentOp.isInvalid())
14535 continue;
14536 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014537 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014538 if (AssignmentOp.isInvalid())
14539 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014540
14541 DSAStack->addDSA(VD, DE, OMPC_copyin);
14542 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014543 SrcExprs.push_back(PseudoSrcExpr);
14544 DstExprs.push_back(PseudoDstExpr);
14545 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014546 }
14547
Alexey Bataeved09d242014-05-28 05:53:51 +000014548 if (Vars.empty())
14549 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014550
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014551 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14552 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014553}
14554
Alexey Bataevbae9a792014-06-27 10:37:06 +000014555OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14556 SourceLocation StartLoc,
14557 SourceLocation LParenLoc,
14558 SourceLocation EndLoc) {
14559 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014560 SmallVector<Expr *, 8> SrcExprs;
14561 SmallVector<Expr *, 8> DstExprs;
14562 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014563 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014564 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14565 SourceLocation ELoc;
14566 SourceRange ERange;
14567 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014568 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014569 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014570 // It will be analyzed later.
14571 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014572 SrcExprs.push_back(nullptr);
14573 DstExprs.push_back(nullptr);
14574 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014575 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014576 ValueDecl *D = Res.first;
14577 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014578 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014579
Alexey Bataeve122da12016-03-17 10:50:17 +000014580 QualType Type = D->getType();
14581 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014582
14583 // OpenMP [2.14.4.2, Restrictions, p.2]
14584 // A list item that appears in a copyprivate clause may not appear in a
14585 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014586 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014587 DSAStackTy::DSAVarData DVar =
14588 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014589 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14590 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014591 Diag(ELoc, diag::err_omp_wrong_dsa)
14592 << getOpenMPClauseName(DVar.CKind)
14593 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014594 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014595 continue;
14596 }
14597
14598 // OpenMP [2.11.4.2, Restrictions, p.1]
14599 // All list items that appear in a copyprivate clause must be either
14600 // threadprivate or private in the enclosing context.
14601 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014602 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014603 if (DVar.CKind == OMPC_shared) {
14604 Diag(ELoc, diag::err_omp_required_access)
14605 << getOpenMPClauseName(OMPC_copyprivate)
14606 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014607 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014608 continue;
14609 }
14610 }
14611 }
14612
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014613 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014614 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014615 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014616 << getOpenMPClauseName(OMPC_copyprivate) << Type
14617 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014618 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014619 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014620 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014621 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014622 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014623 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014624 continue;
14625 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014626
Alexey Bataevbae9a792014-06-27 10:37:06 +000014627 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14628 // A variable of class type (or array thereof) that appears in a
14629 // copyin clause requires an accessible, unambiguous copy assignment
14630 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014631 Type = Context.getBaseElementType(Type.getNonReferenceType())
14632 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014633 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014634 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014635 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014636 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14637 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014638 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014639 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014640 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14641 ExprResult AssignmentOp = BuildBinOp(
14642 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014643 if (AssignmentOp.isInvalid())
14644 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014645 AssignmentOp =
14646 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014647 if (AssignmentOp.isInvalid())
14648 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014649
14650 // No need to mark vars as copyprivate, they are already threadprivate or
14651 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014652 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014653 Vars.push_back(
14654 VD ? RefExpr->IgnoreParens()
14655 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014656 SrcExprs.push_back(PseudoSrcExpr);
14657 DstExprs.push_back(PseudoDstExpr);
14658 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014659 }
14660
14661 if (Vars.empty())
14662 return nullptr;
14663
Alexey Bataeva63048e2015-03-23 06:18:07 +000014664 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14665 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014666}
14667
Alexey Bataev6125da92014-07-21 11:26:11 +000014668OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14669 SourceLocation StartLoc,
14670 SourceLocation LParenLoc,
14671 SourceLocation EndLoc) {
14672 if (VarList.empty())
14673 return nullptr;
14674
14675 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14676}
Alexey Bataevdea47612014-07-23 07:46:59 +000014677
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014678OMPClause *
14679Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14680 SourceLocation DepLoc, SourceLocation ColonLoc,
14681 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14682 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014683 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014684 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014685 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014686 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014687 return nullptr;
14688 }
14689 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014690 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14691 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014692 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014693 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014694 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14695 /*Last=*/OMPC_DEPEND_unknown, Except)
14696 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014697 return nullptr;
14698 }
14699 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014700 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014701 llvm::APSInt DepCounter(/*BitWidth=*/32);
14702 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014703 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14704 if (const Expr *OrderedCountExpr =
14705 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014706 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14707 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014708 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014709 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014710 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014711 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14712 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14713 // It will be analyzed later.
14714 Vars.push_back(RefExpr);
14715 continue;
14716 }
14717
14718 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014719 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014720 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014721 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014722 DepCounter >= TotalDepCount) {
14723 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14724 continue;
14725 }
14726 ++DepCounter;
14727 // OpenMP [2.13.9, Summary]
14728 // depend(dependence-type : vec), where dependence-type is:
14729 // 'sink' and where vec is the iteration vector, which has the form:
14730 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14731 // where n is the value specified by the ordered clause in the loop
14732 // directive, xi denotes the loop iteration variable of the i-th nested
14733 // loop associated with the loop directive, and di is a constant
14734 // non-negative integer.
14735 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014736 // It will be analyzed later.
14737 Vars.push_back(RefExpr);
14738 continue;
14739 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014740 SimpleExpr = SimpleExpr->IgnoreImplicit();
14741 OverloadedOperatorKind OOK = OO_None;
14742 SourceLocation OOLoc;
14743 Expr *LHS = SimpleExpr;
14744 Expr *RHS = nullptr;
14745 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14746 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14747 OOLoc = BO->getOperatorLoc();
14748 LHS = BO->getLHS()->IgnoreParenImpCasts();
14749 RHS = BO->getRHS()->IgnoreParenImpCasts();
14750 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14751 OOK = OCE->getOperator();
14752 OOLoc = OCE->getOperatorLoc();
14753 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14754 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14755 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14756 OOK = MCE->getMethodDecl()
14757 ->getNameInfo()
14758 .getName()
14759 .getCXXOverloadedOperator();
14760 OOLoc = MCE->getCallee()->getExprLoc();
14761 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14762 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014763 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014764 SourceLocation ELoc;
14765 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014766 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014767 if (Res.second) {
14768 // It will be analyzed later.
14769 Vars.push_back(RefExpr);
14770 }
14771 ValueDecl *D = Res.first;
14772 if (!D)
14773 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014774
Alexey Bataev17daedf2018-02-15 22:42:57 +000014775 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14776 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14777 continue;
14778 }
14779 if (RHS) {
14780 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14781 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14782 if (RHSRes.isInvalid())
14783 continue;
14784 }
14785 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014786 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014787 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014788 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014789 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014790 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014791 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14792 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014793 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014794 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014795 continue;
14796 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014797 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014798 } else {
14799 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14800 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14801 (ASE &&
14802 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14803 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14804 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14805 << RefExpr->getSourceRange();
14806 continue;
14807 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014808
14809 ExprResult Res;
14810 {
14811 Sema::TentativeAnalysisScope Trap(*this);
14812 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14813 RefExpr->IgnoreParenImpCasts());
14814 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014815 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14816 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14817 << RefExpr->getSourceRange();
14818 continue;
14819 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014820 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014821 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014822 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014823
14824 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14825 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014826 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014827 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14828 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14829 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14830 }
14831 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14832 Vars.empty())
14833 return nullptr;
14834
Alexey Bataev8b427062016-05-25 12:36:08 +000014835 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014836 DepKind, DepLoc, ColonLoc, Vars,
14837 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014838 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14839 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014840 DSAStack->addDoacrossDependClause(C, OpsOffs);
14841 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014842}
Michael Wonge710d542015-08-07 16:16:36 +000014843
14844OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14845 SourceLocation LParenLoc,
14846 SourceLocation EndLoc) {
14847 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014848 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014849
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014850 // OpenMP [2.9.1, Restrictions]
14851 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014852 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014853 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014854 return nullptr;
14855
Alexey Bataev931e19b2017-10-02 16:32:39 +000014856 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014857 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050014858 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000014859 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014860 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014861 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014862 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14863 HelperValStmt = buildPreInits(Context, Captures);
14864 }
14865
Alexey Bataev8451efa2018-01-15 19:06:12 +000014866 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14867 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014868}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014869
Alexey Bataeve3727102018-04-18 15:57:46 +000014870static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014871 DSAStackTy *Stack, QualType QTy,
14872 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014873 NamedDecl *ND;
14874 if (QTy->isIncompleteType(&ND)) {
14875 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14876 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014877 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014878 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14879 !QTy.isTrivialType(SemaRef.Context))
14880 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014881 return true;
14882}
14883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014884/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014885/// (array section or array subscript) does NOT specify the whole size of the
14886/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014887static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014888 const Expr *E,
14889 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014890 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014891
14892 // If this is an array subscript, it refers to the whole size if the size of
14893 // the dimension is constant and equals 1. Also, an array section assumes the
14894 // format of an array subscript if no colon is used.
14895 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014896 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014897 return ATy->getSize().getSExtValue() != 1;
14898 // Size can't be evaluated statically.
14899 return false;
14900 }
14901
14902 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014903 const Expr *LowerBound = OASE->getLowerBound();
14904 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014905
14906 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014907 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014908 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014909 Expr::EvalResult Result;
14910 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014911 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014912
14913 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014914 if (ConstLowerBound.getSExtValue())
14915 return true;
14916 }
14917
14918 // If we don't have a length we covering the whole dimension.
14919 if (!Length)
14920 return false;
14921
14922 // If the base is a pointer, we don't have a way to get the size of the
14923 // pointee.
14924 if (BaseQTy->isPointerType())
14925 return false;
14926
14927 // We can only check if the length is the same as the size of the dimension
14928 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014929 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014930 if (!CATy)
14931 return false;
14932
Fangrui Song407659a2018-11-30 23:41:18 +000014933 Expr::EvalResult Result;
14934 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014935 return false; // Can't get the integer value as a constant.
14936
Fangrui Song407659a2018-11-30 23:41:18 +000014937 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014938 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14939}
14940
14941// Return true if it can be proven that the provided array expression (array
14942// section or array subscript) does NOT specify a single element of the array
14943// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014944static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014945 const Expr *E,
14946 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014947 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014948
14949 // An array subscript always refer to a single element. Also, an array section
14950 // assumes the format of an array subscript if no colon is used.
14951 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14952 return false;
14953
14954 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014955 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014956
14957 // If we don't have a length we have to check if the array has unitary size
14958 // for this dimension. Also, we should always expect a length if the base type
14959 // is pointer.
14960 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014961 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014962 return ATy->getSize().getSExtValue() != 1;
14963 // We cannot assume anything.
14964 return false;
14965 }
14966
14967 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014968 Expr::EvalResult Result;
14969 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014970 return false; // Can't get the integer value as a constant.
14971
Fangrui Song407659a2018-11-30 23:41:18 +000014972 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014973 return ConstLength.getSExtValue() != 1;
14974}
14975
Samuel Antao661c0902016-05-26 17:39:58 +000014976// Return the expression of the base of the mappable expression or null if it
14977// cannot be determined and do all the necessary checks to see if the expression
14978// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014979// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014980static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014981 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014982 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014983 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014984 SourceLocation ELoc = E->getExprLoc();
14985 SourceRange ERange = E->getSourceRange();
14986
14987 // The base of elements of list in a map clause have to be either:
14988 // - a reference to variable or field.
14989 // - a member expression.
14990 // - an array expression.
14991 //
14992 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14993 // reference to 'r'.
14994 //
14995 // If we have:
14996 //
14997 // struct SS {
14998 // Bla S;
14999 // foo() {
15000 // #pragma omp target map (S.Arr[:12]);
15001 // }
15002 // }
15003 //
15004 // We want to retrieve the member expression 'this->S';
15005
Alexey Bataeve3727102018-04-18 15:57:46 +000015006 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015007
Samuel Antao5de996e2016-01-22 20:21:36 +000015008 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15009 // If a list item is an array section, it must specify contiguous storage.
15010 //
15011 // For this restriction it is sufficient that we make sure only references
15012 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015013 // exist except in the rightmost expression (unless they cover the whole
15014 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015015 //
15016 // r.ArrS[3:5].Arr[6:7]
15017 //
15018 // r.ArrS[3:5].x
15019 //
15020 // but these would be valid:
15021 // r.ArrS[3].Arr[6:7]
15022 //
15023 // r.ArrS[3].x
15024
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015025 bool AllowUnitySizeArraySection = true;
15026 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015027
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015028 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015029 E = E->IgnoreParenImpCasts();
15030
15031 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15032 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015033 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015034
15035 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015036
15037 // If we got a reference to a declaration, we should not expect any array
15038 // section before that.
15039 AllowUnitySizeArraySection = false;
15040 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015041
15042 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015043 CurComponents.emplace_back(CurE, CurE->getDecl());
15044 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015045 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015046
15047 if (isa<CXXThisExpr>(BaseE))
15048 // We found a base expression: this->Val.
15049 RelevantExpr = CurE;
15050 else
15051 E = BaseE;
15052
15053 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015054 if (!NoDiagnose) {
15055 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15056 << CurE->getSourceRange();
15057 return nullptr;
15058 }
15059 if (RelevantExpr)
15060 return nullptr;
15061 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015062 }
15063
15064 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15065
15066 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15067 // A bit-field cannot appear in a map clause.
15068 //
15069 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015070 if (!NoDiagnose) {
15071 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15072 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15073 return nullptr;
15074 }
15075 if (RelevantExpr)
15076 return nullptr;
15077 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015078 }
15079
15080 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15081 // If the type of a list item is a reference to a type T then the type
15082 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015083 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015084
15085 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15086 // A list item cannot be a variable that is a member of a structure with
15087 // a union type.
15088 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015089 if (CurType->isUnionType()) {
15090 if (!NoDiagnose) {
15091 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15092 << CurE->getSourceRange();
15093 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015094 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015095 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015096 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015097
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015098 // If we got a member expression, we should not expect any array section
15099 // before that:
15100 //
15101 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15102 // If a list item is an element of a structure, only the rightmost symbol
15103 // of the variable reference can be an array section.
15104 //
15105 AllowUnitySizeArraySection = false;
15106 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015107
15108 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015109 CurComponents.emplace_back(CurE, FD);
15110 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015111 E = CurE->getBase()->IgnoreParenImpCasts();
15112
15113 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015114 if (!NoDiagnose) {
15115 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15116 << 0 << CurE->getSourceRange();
15117 return nullptr;
15118 }
15119 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015120 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015121
15122 // If we got an array subscript that express the whole dimension we
15123 // can have any array expressions before. If it only expressing part of
15124 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015125 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015126 E->getType()))
15127 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015128
Patrick Lystere13b1e32019-01-02 19:28:48 +000015129 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15130 Expr::EvalResult Result;
15131 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15132 if (!Result.Val.getInt().isNullValue()) {
15133 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15134 diag::err_omp_invalid_map_this_expr);
15135 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15136 diag::note_omp_invalid_subscript_on_this_ptr_map);
15137 }
15138 }
15139 RelevantExpr = TE;
15140 }
15141
Samuel Antao90927002016-04-26 14:54:23 +000015142 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015143 CurComponents.emplace_back(CurE, nullptr);
15144 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015145 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015146 E = CurE->getBase()->IgnoreParenImpCasts();
15147
Alexey Bataev27041fa2017-12-05 15:22:49 +000015148 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015149 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15150
Samuel Antao5de996e2016-01-22 20:21:36 +000015151 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15152 // If the type of a list item is a reference to a type T then the type
15153 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015154 if (CurType->isReferenceType())
15155 CurType = CurType->getPointeeType();
15156
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015157 bool IsPointer = CurType->isAnyPointerType();
15158
15159 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015160 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15161 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015162 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015163 }
15164
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015165 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015166 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015167 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015168 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015169
Samuel Antaodab51bb2016-07-18 23:22:11 +000015170 if (AllowWholeSizeArraySection) {
15171 // Any array section is currently allowed. Allowing a whole size array
15172 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015173 //
15174 // If this array section refers to the whole dimension we can still
15175 // accept other array sections before this one, except if the base is a
15176 // pointer. Otherwise, only unitary sections are accepted.
15177 if (NotWhole || IsPointer)
15178 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015179 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015180 // A unity or whole array section is not allowed and that is not
15181 // compatible with the properties of the current array section.
15182 SemaRef.Diag(
15183 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15184 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015185 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015186 }
Samuel Antao90927002016-04-26 14:54:23 +000015187
Patrick Lystere13b1e32019-01-02 19:28:48 +000015188 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15189 Expr::EvalResult ResultR;
15190 Expr::EvalResult ResultL;
15191 if (CurE->getLength()->EvaluateAsInt(ResultR,
15192 SemaRef.getASTContext())) {
15193 if (!ResultR.Val.getInt().isOneValue()) {
15194 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15195 diag::err_omp_invalid_map_this_expr);
15196 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15197 diag::note_omp_invalid_length_on_this_ptr_mapping);
15198 }
15199 }
15200 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15201 ResultL, SemaRef.getASTContext())) {
15202 if (!ResultL.Val.getInt().isNullValue()) {
15203 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15204 diag::err_omp_invalid_map_this_expr);
15205 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15206 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15207 }
15208 }
15209 RelevantExpr = TE;
15210 }
15211
Samuel Antao90927002016-04-26 14:54:23 +000015212 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015213 CurComponents.emplace_back(CurE, nullptr);
15214 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015215 if (!NoDiagnose) {
15216 // If nothing else worked, this is not a valid map clause expression.
15217 SemaRef.Diag(
15218 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15219 << ERange;
15220 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015221 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015222 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015223 }
15224
15225 return RelevantExpr;
15226}
15227
15228// Return true if expression E associated with value VD has conflicts with other
15229// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015230static bool checkMapConflicts(
15231 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015232 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015233 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15234 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015235 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015236 SourceLocation ELoc = E->getExprLoc();
15237 SourceRange ERange = E->getSourceRange();
15238
15239 // In order to easily check the conflicts we need to match each component of
15240 // the expression under test with the components of the expressions that are
15241 // already in the stack.
15242
Samuel Antao5de996e2016-01-22 20:21:36 +000015243 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015244 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015245 "Map clause expression with unexpected base!");
15246
15247 // Variables to help detecting enclosing problems in data environment nests.
15248 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015249 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015250
Samuel Antao90927002016-04-26 14:54:23 +000015251 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15252 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015253 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15254 ERange, CKind, &EnclosingExpr,
15255 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15256 StackComponents,
15257 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015258 assert(!StackComponents.empty() &&
15259 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015260 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015261 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015262 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015263
Samuel Antao90927002016-04-26 14:54:23 +000015264 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015265 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015266
Samuel Antao5de996e2016-01-22 20:21:36 +000015267 // Expressions must start from the same base. Here we detect at which
15268 // point both expressions diverge from each other and see if we can
15269 // detect if the memory referred to both expressions is contiguous and
15270 // do not overlap.
15271 auto CI = CurComponents.rbegin();
15272 auto CE = CurComponents.rend();
15273 auto SI = StackComponents.rbegin();
15274 auto SE = StackComponents.rend();
15275 for (; CI != CE && SI != SE; ++CI, ++SI) {
15276
15277 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15278 // At most one list item can be an array item derived from a given
15279 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015280 if (CurrentRegionOnly &&
15281 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15282 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15283 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15284 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15285 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015286 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015287 << CI->getAssociatedExpression()->getSourceRange();
15288 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15289 diag::note_used_here)
15290 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015291 return true;
15292 }
15293
15294 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015295 if (CI->getAssociatedExpression()->getStmtClass() !=
15296 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015297 break;
15298
15299 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015300 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015301 break;
15302 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015303 // Check if the extra components of the expressions in the enclosing
15304 // data environment are redundant for the current base declaration.
15305 // If they are, the maps completely overlap, which is legal.
15306 for (; SI != SE; ++SI) {
15307 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015308 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015309 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015310 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015311 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015312 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015313 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015314 Type =
15315 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15316 }
15317 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015318 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015319 SemaRef, SI->getAssociatedExpression(), Type))
15320 break;
15321 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015322
15323 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15324 // List items of map clauses in the same construct must not share
15325 // original storage.
15326 //
15327 // If the expressions are exactly the same or one is a subset of the
15328 // other, it means they are sharing storage.
15329 if (CI == CE && SI == SE) {
15330 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015331 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015332 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015333 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015334 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015335 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15336 << ERange;
15337 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015338 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15339 << RE->getSourceRange();
15340 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015341 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015342 // If we find the same expression in the enclosing data environment,
15343 // that is legal.
15344 IsEnclosedByDataEnvironmentExpr = true;
15345 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015346 }
15347
Samuel Antao90927002016-04-26 14:54:23 +000015348 QualType DerivedType =
15349 std::prev(CI)->getAssociatedDeclaration()->getType();
15350 SourceLocation DerivedLoc =
15351 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015352
15353 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15354 // If the type of a list item is a reference to a type T then the type
15355 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015356 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015357
15358 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15359 // A variable for which the type is pointer and an array section
15360 // derived from that variable must not appear as list items of map
15361 // clauses of the same construct.
15362 //
15363 // Also, cover one of the cases in:
15364 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15365 // If any part of the original storage of a list item has corresponding
15366 // storage in the device data environment, all of the original storage
15367 // must have corresponding storage in the device data environment.
15368 //
15369 if (DerivedType->isAnyPointerType()) {
15370 if (CI == CE || SI == SE) {
15371 SemaRef.Diag(
15372 DerivedLoc,
15373 diag::err_omp_pointer_mapped_along_with_derived_section)
15374 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015375 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15376 << RE->getSourceRange();
15377 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015378 }
15379 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015380 SI->getAssociatedExpression()->getStmtClass() ||
15381 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15382 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015383 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015384 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015385 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015386 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15387 << RE->getSourceRange();
15388 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015389 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015390 }
15391
15392 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15393 // List items of map clauses in the same construct must not share
15394 // original storage.
15395 //
15396 // An expression is a subset of the other.
15397 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015398 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015399 if (CI != CE || SI != SE) {
15400 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15401 // a pointer.
15402 auto Begin =
15403 CI != CE ? CurComponents.begin() : StackComponents.begin();
15404 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15405 auto It = Begin;
15406 while (It != End && !It->getAssociatedDeclaration())
15407 std::advance(It, 1);
15408 assert(It != End &&
15409 "Expected at least one component with the declaration.");
15410 if (It != Begin && It->getAssociatedDeclaration()
15411 ->getType()
15412 .getCanonicalType()
15413 ->isAnyPointerType()) {
15414 IsEnclosedByDataEnvironmentExpr = false;
15415 EnclosingExpr = nullptr;
15416 return false;
15417 }
15418 }
Samuel Antao661c0902016-05-26 17:39:58 +000015419 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015420 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015421 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015422 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15423 << ERange;
15424 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015425 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15426 << RE->getSourceRange();
15427 return true;
15428 }
15429
15430 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015431 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015432 if (!CurrentRegionOnly && SI != SE)
15433 EnclosingExpr = RE;
15434
15435 // The current expression is a subset of the expression in the data
15436 // environment.
15437 IsEnclosedByDataEnvironmentExpr |=
15438 (!CurrentRegionOnly && CI != CE && SI == SE);
15439
15440 return false;
15441 });
15442
15443 if (CurrentRegionOnly)
15444 return FoundError;
15445
15446 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15447 // If any part of the original storage of a list item has corresponding
15448 // storage in the device data environment, all of the original storage must
15449 // have corresponding storage in the device data environment.
15450 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15451 // If a list item is an element of a structure, and a different element of
15452 // the structure has a corresponding list item in the device data environment
15453 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015454 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015455 // data environment prior to the task encountering the construct.
15456 //
15457 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15458 SemaRef.Diag(ELoc,
15459 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15460 << ERange;
15461 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15462 << EnclosingExpr->getSourceRange();
15463 return true;
15464 }
15465
15466 return FoundError;
15467}
15468
Michael Kruse4304e9d2019-02-19 16:38:20 +000015469// Look up the user-defined mapper given the mapper name and mapped type, and
15470// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015471static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15472 CXXScopeSpec &MapperIdScopeSpec,
15473 const DeclarationNameInfo &MapperId,
15474 QualType Type,
15475 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015476 if (MapperIdScopeSpec.isInvalid())
15477 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015478 // Get the actual type for the array type.
15479 if (Type->isArrayType()) {
15480 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15481 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15482 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015483 // Find all user-defined mappers with the given MapperId.
15484 SmallVector<UnresolvedSet<8>, 4> Lookups;
15485 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15486 Lookup.suppressDiagnostics();
15487 if (S) {
15488 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15489 NamedDecl *D = Lookup.getRepresentativeDecl();
15490 while (S && !S->isDeclScope(D))
15491 S = S->getParent();
15492 if (S)
15493 S = S->getParent();
15494 Lookups.emplace_back();
15495 Lookups.back().append(Lookup.begin(), Lookup.end());
15496 Lookup.clear();
15497 }
15498 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15499 // Extract the user-defined mappers with the given MapperId.
15500 Lookups.push_back(UnresolvedSet<8>());
15501 for (NamedDecl *D : ULE->decls()) {
15502 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15503 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15504 Lookups.back().addDecl(DMD);
15505 }
15506 }
15507 // Defer the lookup for dependent types. The results will be passed through
15508 // UnresolvedMapper on instantiation.
15509 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15510 Type->isInstantiationDependentType() ||
15511 Type->containsUnexpandedParameterPack() ||
15512 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15513 return !D->isInvalidDecl() &&
15514 (D->getType()->isDependentType() ||
15515 D->getType()->isInstantiationDependentType() ||
15516 D->getType()->containsUnexpandedParameterPack());
15517 })) {
15518 UnresolvedSet<8> URS;
15519 for (const UnresolvedSet<8> &Set : Lookups) {
15520 if (Set.empty())
15521 continue;
15522 URS.append(Set.begin(), Set.end());
15523 }
15524 return UnresolvedLookupExpr::Create(
15525 SemaRef.Context, /*NamingClass=*/nullptr,
15526 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15527 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15528 }
Michael Kruse945249b2019-09-26 22:53:01 +000015529 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015530 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15531 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015532 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15533 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15534 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15535 return ExprError();
15536 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015537 // Perform argument dependent lookup.
15538 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15539 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15540 // Return the first user-defined mapper with the desired type.
15541 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15542 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15543 if (!D->isInvalidDecl() &&
15544 SemaRef.Context.hasSameType(D->getType(), Type))
15545 return D;
15546 return nullptr;
15547 }))
15548 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15549 // Find the first user-defined mapper with a type derived from the desired
15550 // type.
15551 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15552 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15553 if (!D->isInvalidDecl() &&
15554 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15555 !Type.isMoreQualifiedThan(D->getType()))
15556 return D;
15557 return nullptr;
15558 })) {
15559 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15560 /*DetectVirtual=*/false);
15561 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15562 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15563 VD->getType().getUnqualifiedType()))) {
15564 if (SemaRef.CheckBaseClassAccess(
15565 Loc, VD->getType(), Type, Paths.front(),
15566 /*DiagID=*/0) != Sema::AR_inaccessible) {
15567 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15568 }
15569 }
15570 }
15571 }
15572 // Report error if a mapper is specified, but cannot be found.
15573 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15574 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15575 << Type << MapperId.getName();
15576 return ExprError();
15577 }
15578 return ExprEmpty();
15579}
15580
Samuel Antao661c0902016-05-26 17:39:58 +000015581namespace {
15582// Utility struct that gathers all the related lists associated with a mappable
15583// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015584struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015585 // The list of expressions.
15586 ArrayRef<Expr *> VarList;
15587 // The list of processed expressions.
15588 SmallVector<Expr *, 16> ProcessedVarList;
15589 // The mappble components for each expression.
15590 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15591 // The base declaration of the variable.
15592 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015593 // The reference to the user-defined mapper associated with every expression.
15594 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015595
15596 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15597 // We have a list of components and base declarations for each entry in the
15598 // variable list.
15599 VarComponents.reserve(VarList.size());
15600 VarBaseDeclarations.reserve(VarList.size());
15601 }
15602};
15603}
15604
15605// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015606// \a CKind. In the check process the valid expressions, mappable expression
15607// components, variables, and user-defined mappers are extracted and used to
15608// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15609// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15610// and \a MapperId are expected to be valid if the clause kind is 'map'.
15611static void checkMappableExpressionList(
15612 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15613 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015614 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15615 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015616 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015617 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015618 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15619 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015620 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015621
15622 // If the identifier of user-defined mapper is not specified, it is "default".
15623 // We do not change the actual name in this clause to distinguish whether a
15624 // mapper is specified explicitly, i.e., it is not explicitly specified when
15625 // MapperId.getName() is empty.
15626 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15627 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15628 MapperId.setName(DeclNames.getIdentifier(
15629 &SemaRef.getASTContext().Idents.get("default")));
15630 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015631
15632 // Iterators to find the current unresolved mapper expression.
15633 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15634 bool UpdateUMIt = false;
15635 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015636
Samuel Antao90927002016-04-26 14:54:23 +000015637 // Keep track of the mappable components and base declarations in this clause.
15638 // Each entry in the list is going to have a list of components associated. We
15639 // record each set of the components so that we can build the clause later on.
15640 // In the end we should have the same amount of declarations and component
15641 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015642
Alexey Bataeve3727102018-04-18 15:57:46 +000015643 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015644 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015645 SourceLocation ELoc = RE->getExprLoc();
15646
Michael Kruse4304e9d2019-02-19 16:38:20 +000015647 // Find the current unresolved mapper expression.
15648 if (UpdateUMIt && UMIt != UMEnd) {
15649 UMIt++;
15650 assert(
15651 UMIt != UMEnd &&
15652 "Expect the size of UnresolvedMappers to match with that of VarList");
15653 }
15654 UpdateUMIt = true;
15655 if (UMIt != UMEnd)
15656 UnresolvedMapper = *UMIt;
15657
Alexey Bataeve3727102018-04-18 15:57:46 +000015658 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015659
15660 if (VE->isValueDependent() || VE->isTypeDependent() ||
15661 VE->isInstantiationDependent() ||
15662 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015663 // Try to find the associated user-defined mapper.
15664 ExprResult ER = buildUserDefinedMapperRef(
15665 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15666 VE->getType().getCanonicalType(), UnresolvedMapper);
15667 if (ER.isInvalid())
15668 continue;
15669 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015670 // We can only analyze this information once the missing information is
15671 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015672 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015673 continue;
15674 }
15675
Alexey Bataeve3727102018-04-18 15:57:46 +000015676 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015677
Samuel Antao5de996e2016-01-22 20:21:36 +000015678 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015679 SemaRef.Diag(ELoc,
15680 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015681 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015682 continue;
15683 }
15684
Samuel Antao90927002016-04-26 14:54:23 +000015685 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15686 ValueDecl *CurDeclaration = nullptr;
15687
15688 // Obtain the array or member expression bases if required. Also, fill the
15689 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015690 const Expr *BE = checkMapClauseExpressionBase(
15691 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015692 if (!BE)
15693 continue;
15694
Samuel Antao90927002016-04-26 14:54:23 +000015695 assert(!CurComponents.empty() &&
15696 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015697
Patrick Lystere13b1e32019-01-02 19:28:48 +000015698 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15699 // Add store "this" pointer to class in DSAStackTy for future checking
15700 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015701 // Try to find the associated user-defined mapper.
15702 ExprResult ER = buildUserDefinedMapperRef(
15703 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15704 VE->getType().getCanonicalType(), UnresolvedMapper);
15705 if (ER.isInvalid())
15706 continue;
15707 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015708 // Skip restriction checking for variable or field declarations
15709 MVLI.ProcessedVarList.push_back(RE);
15710 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15711 MVLI.VarComponents.back().append(CurComponents.begin(),
15712 CurComponents.end());
15713 MVLI.VarBaseDeclarations.push_back(nullptr);
15714 continue;
15715 }
15716
Samuel Antao90927002016-04-26 14:54:23 +000015717 // For the following checks, we rely on the base declaration which is
15718 // expected to be associated with the last component. The declaration is
15719 // expected to be a variable or a field (if 'this' is being mapped).
15720 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15721 assert(CurDeclaration && "Null decl on map clause.");
15722 assert(
15723 CurDeclaration->isCanonicalDecl() &&
15724 "Expecting components to have associated only canonical declarations.");
15725
15726 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015727 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015728
15729 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015730 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015731
15732 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015733 // threadprivate variables cannot appear in a map clause.
15734 // OpenMP 4.5 [2.10.5, target update Construct]
15735 // threadprivate variables cannot appear in a from clause.
15736 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015737 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015738 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15739 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015740 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015741 continue;
15742 }
15743
Samuel Antao5de996e2016-01-22 20:21:36 +000015744 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15745 // A list item cannot appear in both a map clause and a data-sharing
15746 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015747
Samuel Antao5de996e2016-01-22 20:21:36 +000015748 // Check conflicts with other map clause expressions. We check the conflicts
15749 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015750 // environment, because the restrictions are different. We only have to
15751 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015752 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015753 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015754 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015755 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015756 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015757 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015758 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015759
Samuel Antao661c0902016-05-26 17:39:58 +000015760 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015761 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15762 // If the type of a list item is a reference to a type T then the type will
15763 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015764 auto I = llvm::find_if(
15765 CurComponents,
15766 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15767 return MC.getAssociatedDeclaration();
15768 });
15769 assert(I != CurComponents.end() && "Null decl on map clause.");
15770 QualType Type =
15771 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015772
Samuel Antao661c0902016-05-26 17:39:58 +000015773 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15774 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015775 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015776 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015777 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015778 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015779 continue;
15780
Samuel Antao661c0902016-05-26 17:39:58 +000015781 if (CKind == OMPC_map) {
15782 // target enter data
15783 // OpenMP [2.10.2, Restrictions, p. 99]
15784 // A map-type must be specified in all map clauses and must be either
15785 // to or alloc.
15786 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15787 if (DKind == OMPD_target_enter_data &&
15788 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15789 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15790 << (IsMapTypeImplicit ? 1 : 0)
15791 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15792 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015793 continue;
15794 }
Samuel Antao661c0902016-05-26 17:39:58 +000015795
15796 // target exit_data
15797 // OpenMP [2.10.3, Restrictions, p. 102]
15798 // A map-type must be specified in all map clauses and must be either
15799 // from, release, or delete.
15800 if (DKind == OMPD_target_exit_data &&
15801 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15802 MapType == OMPC_MAP_delete)) {
15803 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15804 << (IsMapTypeImplicit ? 1 : 0)
15805 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15806 << getOpenMPDirectiveName(DKind);
15807 continue;
15808 }
15809
15810 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15811 // A list item cannot appear in both a map clause and a data-sharing
15812 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015813 //
15814 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15815 // A list item cannot appear in both a map clause and a data-sharing
15816 // attribute clause on the same construct unless the construct is a
15817 // combined construct.
15818 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15819 isOpenMPTargetExecutionDirective(DKind)) ||
15820 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015821 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015822 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015823 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015824 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015825 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015826 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015827 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015828 continue;
15829 }
15830 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015831 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015832
Michael Kruse01f670d2019-02-22 22:29:42 +000015833 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015834 ExprResult ER = buildUserDefinedMapperRef(
15835 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15836 Type.getCanonicalType(), UnresolvedMapper);
15837 if (ER.isInvalid())
15838 continue;
15839 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015840
Samuel Antao90927002016-04-26 14:54:23 +000015841 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015842 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015843
15844 // Store the components in the stack so that they can be used to check
15845 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015846 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15847 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015848
15849 // Save the components and declaration to create the clause. For purposes of
15850 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015851 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015852 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15853 MVLI.VarComponents.back().append(CurComponents.begin(),
15854 CurComponents.end());
15855 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15856 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015857 }
Samuel Antao661c0902016-05-26 17:39:58 +000015858}
15859
Michael Kruse4304e9d2019-02-19 16:38:20 +000015860OMPClause *Sema::ActOnOpenMPMapClause(
15861 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15862 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15863 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15864 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15865 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15866 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15867 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15868 OMPC_MAP_MODIFIER_unknown,
15869 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015870 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15871
15872 // Process map-type-modifiers, flag errors for duplicate modifiers.
15873 unsigned Count = 0;
15874 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15875 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15876 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15877 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15878 continue;
15879 }
15880 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015881 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015882 Modifiers[Count] = MapTypeModifiers[I];
15883 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15884 ++Count;
15885 }
15886
Michael Kruse4304e9d2019-02-19 16:38:20 +000015887 MappableVarListInfo MVLI(VarList);
15888 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015889 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15890 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015891
Samuel Antao5de996e2016-01-22 20:21:36 +000015892 // We need to produce a map clause even if we don't have variables so that
15893 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015894 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15895 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15896 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15897 MapperIdScopeSpec.getWithLocInContext(Context),
15898 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015899}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015900
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015901QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15902 TypeResult ParsedType) {
15903 assert(ParsedType.isUsable());
15904
15905 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15906 if (ReductionType.isNull())
15907 return QualType();
15908
15909 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15910 // A type name in a declare reduction directive cannot be a function type, an
15911 // array type, a reference type, or a type qualified with const, volatile or
15912 // restrict.
15913 if (ReductionType.hasQualifiers()) {
15914 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15915 return QualType();
15916 }
15917
15918 if (ReductionType->isFunctionType()) {
15919 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15920 return QualType();
15921 }
15922 if (ReductionType->isReferenceType()) {
15923 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15924 return QualType();
15925 }
15926 if (ReductionType->isArrayType()) {
15927 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15928 return QualType();
15929 }
15930 return ReductionType;
15931}
15932
15933Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15934 Scope *S, DeclContext *DC, DeclarationName Name,
15935 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15936 AccessSpecifier AS, Decl *PrevDeclInScope) {
15937 SmallVector<Decl *, 8> Decls;
15938 Decls.reserve(ReductionTypes.size());
15939
15940 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015941 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015942 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15943 // A reduction-identifier may not be re-declared in the current scope for the
15944 // same type or for a type that is compatible according to the base language
15945 // rules.
15946 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15947 OMPDeclareReductionDecl *PrevDRD = nullptr;
15948 bool InCompoundScope = true;
15949 if (S != nullptr) {
15950 // Find previous declaration with the same name not referenced in other
15951 // declarations.
15952 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15953 InCompoundScope =
15954 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15955 LookupName(Lookup, S);
15956 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15957 /*AllowInlineNamespace=*/false);
15958 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015959 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015960 while (Filter.hasNext()) {
15961 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15962 if (InCompoundScope) {
15963 auto I = UsedAsPrevious.find(PrevDecl);
15964 if (I == UsedAsPrevious.end())
15965 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015966 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015967 UsedAsPrevious[D] = true;
15968 }
15969 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15970 PrevDecl->getLocation();
15971 }
15972 Filter.done();
15973 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015974 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015975 if (!PrevData.second) {
15976 PrevDRD = PrevData.first;
15977 break;
15978 }
15979 }
15980 }
15981 } else if (PrevDeclInScope != nullptr) {
15982 auto *PrevDRDInScope = PrevDRD =
15983 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15984 do {
15985 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15986 PrevDRDInScope->getLocation();
15987 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15988 } while (PrevDRDInScope != nullptr);
15989 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015990 for (const auto &TyData : ReductionTypes) {
15991 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015992 bool Invalid = false;
15993 if (I != PreviousRedeclTypes.end()) {
15994 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15995 << TyData.first;
15996 Diag(I->second, diag::note_previous_definition);
15997 Invalid = true;
15998 }
15999 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16000 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16001 Name, TyData.first, PrevDRD);
16002 DC->addDecl(DRD);
16003 DRD->setAccess(AS);
16004 Decls.push_back(DRD);
16005 if (Invalid)
16006 DRD->setInvalidDecl();
16007 else
16008 PrevDRD = DRD;
16009 }
16010
16011 return DeclGroupPtrTy::make(
16012 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16013}
16014
16015void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16016 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16017
16018 // Enter new function scope.
16019 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016020 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016021 getCurFunction()->setHasOMPDeclareReductionCombiner();
16022
16023 if (S != nullptr)
16024 PushDeclContext(S, DRD);
16025 else
16026 CurContext = DRD;
16027
Faisal Valid143a0c2017-04-01 21:30:49 +000016028 PushExpressionEvaluationContext(
16029 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016030
16031 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016032 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16033 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16034 // uses semantics of argument handles by value, but it should be passed by
16035 // reference. C lang does not support references, so pass all parameters as
16036 // pointers.
16037 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016038 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016039 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016040 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16041 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16042 // uses semantics of argument handles by value, but it should be passed by
16043 // reference. C lang does not support references, so pass all parameters as
16044 // pointers.
16045 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016046 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016047 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16048 if (S != nullptr) {
16049 PushOnScopeChains(OmpInParm, S);
16050 PushOnScopeChains(OmpOutParm, S);
16051 } else {
16052 DRD->addDecl(OmpInParm);
16053 DRD->addDecl(OmpOutParm);
16054 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016055 Expr *InE =
16056 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16057 Expr *OutE =
16058 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16059 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016060}
16061
16062void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16063 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16064 DiscardCleanupsInEvaluationContext();
16065 PopExpressionEvaluationContext();
16066
16067 PopDeclContext();
16068 PopFunctionScopeInfo();
16069
16070 if (Combiner != nullptr)
16071 DRD->setCombiner(Combiner);
16072 else
16073 DRD->setInvalidDecl();
16074}
16075
Alexey Bataev070f43a2017-09-06 14:49:58 +000016076VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016077 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16078
16079 // Enter new function scope.
16080 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016081 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016082
16083 if (S != nullptr)
16084 PushDeclContext(S, DRD);
16085 else
16086 CurContext = DRD;
16087
Faisal Valid143a0c2017-04-01 21:30:49 +000016088 PushExpressionEvaluationContext(
16089 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016090
16091 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016092 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16093 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16094 // uses semantics of argument handles by value, but it should be passed by
16095 // reference. C lang does not support references, so pass all parameters as
16096 // pointers.
16097 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016098 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016099 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016100 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16101 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16102 // uses semantics of argument handles by value, but it should be passed by
16103 // reference. C lang does not support references, so pass all parameters as
16104 // pointers.
16105 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016106 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016107 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016108 if (S != nullptr) {
16109 PushOnScopeChains(OmpPrivParm, S);
16110 PushOnScopeChains(OmpOrigParm, S);
16111 } else {
16112 DRD->addDecl(OmpPrivParm);
16113 DRD->addDecl(OmpOrigParm);
16114 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016115 Expr *OrigE =
16116 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16117 Expr *PrivE =
16118 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16119 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016120 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016121}
16122
Alexey Bataev070f43a2017-09-06 14:49:58 +000016123void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16124 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016125 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16126 DiscardCleanupsInEvaluationContext();
16127 PopExpressionEvaluationContext();
16128
16129 PopDeclContext();
16130 PopFunctionScopeInfo();
16131
Alexey Bataev070f43a2017-09-06 14:49:58 +000016132 if (Initializer != nullptr) {
16133 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16134 } else if (OmpPrivParm->hasInit()) {
16135 DRD->setInitializer(OmpPrivParm->getInit(),
16136 OmpPrivParm->isDirectInit()
16137 ? OMPDeclareReductionDecl::DirectInit
16138 : OMPDeclareReductionDecl::CopyInit);
16139 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016140 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016141 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016142}
16143
16144Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16145 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016146 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016147 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016148 if (S)
16149 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16150 /*AddToContext=*/false);
16151 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016152 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016153 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016154 }
16155 return DeclReductions;
16156}
16157
Michael Kruse251e1482019-02-01 20:25:04 +000016158TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16159 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16160 QualType T = TInfo->getType();
16161 if (D.isInvalidType())
16162 return true;
16163
16164 if (getLangOpts().CPlusPlus) {
16165 // Check that there are no default arguments (C++ only).
16166 CheckExtraCXXDefaultArguments(D);
16167 }
16168
16169 return CreateParsedType(T, TInfo);
16170}
16171
16172QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16173 TypeResult ParsedType) {
16174 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16175
16176 QualType MapperType = GetTypeFromParser(ParsedType.get());
16177 assert(!MapperType.isNull() && "Expect valid mapper type");
16178
16179 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16180 // The type must be of struct, union or class type in C and C++
16181 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16182 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16183 return QualType();
16184 }
16185 return MapperType;
16186}
16187
16188OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16189 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16190 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16191 Decl *PrevDeclInScope) {
16192 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16193 forRedeclarationInCurContext());
16194 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16195 // A mapper-identifier may not be redeclared in the current scope for the
16196 // same type or for a type that is compatible according to the base language
16197 // rules.
16198 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16199 OMPDeclareMapperDecl *PrevDMD = nullptr;
16200 bool InCompoundScope = true;
16201 if (S != nullptr) {
16202 // Find previous declaration with the same name not referenced in other
16203 // declarations.
16204 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16205 InCompoundScope =
16206 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16207 LookupName(Lookup, S);
16208 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16209 /*AllowInlineNamespace=*/false);
16210 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16211 LookupResult::Filter Filter = Lookup.makeFilter();
16212 while (Filter.hasNext()) {
16213 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16214 if (InCompoundScope) {
16215 auto I = UsedAsPrevious.find(PrevDecl);
16216 if (I == UsedAsPrevious.end())
16217 UsedAsPrevious[PrevDecl] = false;
16218 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16219 UsedAsPrevious[D] = true;
16220 }
16221 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16222 PrevDecl->getLocation();
16223 }
16224 Filter.done();
16225 if (InCompoundScope) {
16226 for (const auto &PrevData : UsedAsPrevious) {
16227 if (!PrevData.second) {
16228 PrevDMD = PrevData.first;
16229 break;
16230 }
16231 }
16232 }
16233 } else if (PrevDeclInScope) {
16234 auto *PrevDMDInScope = PrevDMD =
16235 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16236 do {
16237 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16238 PrevDMDInScope->getLocation();
16239 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16240 } while (PrevDMDInScope != nullptr);
16241 }
16242 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16243 bool Invalid = false;
16244 if (I != PreviousRedeclTypes.end()) {
16245 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16246 << MapperType << Name;
16247 Diag(I->second, diag::note_previous_definition);
16248 Invalid = true;
16249 }
16250 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16251 MapperType, VN, PrevDMD);
16252 DC->addDecl(DMD);
16253 DMD->setAccess(AS);
16254 if (Invalid)
16255 DMD->setInvalidDecl();
16256
16257 // Enter new function scope.
16258 PushFunctionScope();
16259 setFunctionHasBranchProtectedScope();
16260
16261 CurContext = DMD;
16262
16263 return DMD;
16264}
16265
16266void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16267 Scope *S,
16268 QualType MapperType,
16269 SourceLocation StartLoc,
16270 DeclarationName VN) {
16271 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16272 if (S)
16273 PushOnScopeChains(VD, S);
16274 else
16275 DMD->addDecl(VD);
16276 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16277 DMD->setMapperVarRef(MapperVarRefExpr);
16278}
16279
16280Sema::DeclGroupPtrTy
16281Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16282 ArrayRef<OMPClause *> ClauseList) {
16283 PopDeclContext();
16284 PopFunctionScopeInfo();
16285
16286 if (D) {
16287 if (S)
16288 PushOnScopeChains(D, S, /*AddToContext=*/false);
16289 D->CreateClauses(Context, ClauseList);
16290 }
16291
16292 return DeclGroupPtrTy::make(DeclGroupRef(D));
16293}
16294
David Majnemer9d168222016-08-05 17:44:54 +000016295OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016296 SourceLocation StartLoc,
16297 SourceLocation LParenLoc,
16298 SourceLocation EndLoc) {
16299 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016300 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016301
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016302 // OpenMP [teams Constrcut, Restrictions]
16303 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016304 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016305 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016306 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016307
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016308 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016309 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016310 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016311 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016312 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016313 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016314 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16315 HelperValStmt = buildPreInits(Context, Captures);
16316 }
16317
16318 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16319 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016320}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016321
16322OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16323 SourceLocation StartLoc,
16324 SourceLocation LParenLoc,
16325 SourceLocation EndLoc) {
16326 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016327 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016328
16329 // OpenMP [teams Constrcut, Restrictions]
16330 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016331 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016332 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016333 return nullptr;
16334
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016335 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016336 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16337 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016338 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016339 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016340 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016341 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16342 HelperValStmt = buildPreInits(Context, Captures);
16343 }
16344
16345 return new (Context) OMPThreadLimitClause(
16346 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016347}
Alexey Bataeva0569352015-12-01 10:17:31 +000016348
16349OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16350 SourceLocation StartLoc,
16351 SourceLocation LParenLoc,
16352 SourceLocation EndLoc) {
16353 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016354 Stmt *HelperValStmt = nullptr;
16355 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016356
16357 // OpenMP [2.9.1, task Constrcut]
16358 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016359 if (!isNonNegativeIntegerValue(
16360 ValExpr, *this, OMPC_priority,
16361 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16362 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016363 return nullptr;
16364
Alexey Bataev31ba4762019-10-16 18:09:37 +000016365 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16366 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016367}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016368
16369OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16370 SourceLocation StartLoc,
16371 SourceLocation LParenLoc,
16372 SourceLocation EndLoc) {
16373 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016374 Stmt *HelperValStmt = nullptr;
16375 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016376
16377 // OpenMP [2.9.2, taskloop Constrcut]
16378 // The parameter of the grainsize clause must be a positive integer
16379 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016380 if (!isNonNegativeIntegerValue(
16381 ValExpr, *this, OMPC_grainsize,
16382 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16383 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016384 return nullptr;
16385
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016386 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16387 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016388}
Alexey Bataev382967a2015-12-08 12:06:20 +000016389
16390OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16391 SourceLocation StartLoc,
16392 SourceLocation LParenLoc,
16393 SourceLocation EndLoc) {
16394 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016395 Stmt *HelperValStmt = nullptr;
16396 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016397
16398 // OpenMP [2.9.2, taskloop Constrcut]
16399 // The parameter of the num_tasks clause must be a positive integer
16400 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016401 if (!isNonNegativeIntegerValue(
16402 ValExpr, *this, OMPC_num_tasks,
16403 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16404 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016405 return nullptr;
16406
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016407 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16408 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016409}
16410
Alexey Bataev28c75412015-12-15 08:19:24 +000016411OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16412 SourceLocation LParenLoc,
16413 SourceLocation EndLoc) {
16414 // OpenMP [2.13.2, critical construct, Description]
16415 // ... where hint-expression is an integer constant expression that evaluates
16416 // to a valid lock hint.
16417 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16418 if (HintExpr.isInvalid())
16419 return nullptr;
16420 return new (Context)
16421 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16422}
16423
Carlo Bertollib4adf552016-01-15 18:50:31 +000016424OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16425 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16426 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16427 SourceLocation EndLoc) {
16428 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16429 std::string Values;
16430 Values += "'";
16431 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16432 Values += "'";
16433 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16434 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16435 return nullptr;
16436 }
16437 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016438 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016439 if (ChunkSize) {
16440 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16441 !ChunkSize->isInstantiationDependent() &&
16442 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016443 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016444 ExprResult Val =
16445 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16446 if (Val.isInvalid())
16447 return nullptr;
16448
16449 ValExpr = Val.get();
16450
16451 // OpenMP [2.7.1, Restrictions]
16452 // chunk_size must be a loop invariant integer expression with a positive
16453 // value.
16454 llvm::APSInt Result;
16455 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16456 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16457 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16458 << "dist_schedule" << ChunkSize->getSourceRange();
16459 return nullptr;
16460 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016461 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016462 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16463 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016464 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016465 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016466 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016467 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16468 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016469 }
16470 }
16471 }
16472
16473 return new (Context)
16474 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016475 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016476}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016477
16478OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16479 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16480 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16481 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016482 if (getLangOpts().OpenMP < 50) {
16483 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16484 Kind != OMPC_DEFAULTMAP_scalar) {
16485 std::string Value;
16486 SourceLocation Loc;
16487 Value += "'";
16488 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16489 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16490 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16491 Loc = MLoc;
16492 } else {
16493 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16494 OMPC_DEFAULTMAP_scalar);
16495 Loc = KindLoc;
16496 }
16497 Value += "'";
16498 Diag(Loc, diag::err_omp_unexpected_clause_value)
16499 << Value << getOpenMPClauseName(OMPC_defaultmap);
16500 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016501 }
cchene06f3e02019-11-15 13:02:06 -050016502 } else {
16503 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16504 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16505 if (!isDefaultmapKind || !isDefaultmapModifier) {
16506 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16507 "'firstprivate', 'none', 'default'";
16508 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16509 if (!isDefaultmapKind && isDefaultmapModifier) {
16510 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16511 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16512 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16513 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16514 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16515 } else {
16516 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16517 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16518 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16519 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16520 }
16521 return nullptr;
16522 }
16523
16524 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16525 // At most one defaultmap clause for each category can appear on the
16526 // directive.
16527 if (DSAStack->checkDefaultmapCategory(Kind)) {
16528 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16529 return nullptr;
16530 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016531 }
cchene06f3e02019-11-15 13:02:06 -050016532 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016533
16534 return new (Context)
16535 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16536}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016537
16538bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16539 DeclContext *CurLexicalContext = getCurLexicalContext();
16540 if (!CurLexicalContext->isFileContext() &&
16541 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016542 !CurLexicalContext->isExternCXXContext() &&
16543 !isa<CXXRecordDecl>(CurLexicalContext) &&
16544 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16545 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16546 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016547 Diag(Loc, diag::err_omp_region_not_file_context);
16548 return false;
16549 }
Kelvin Libc38e632018-09-10 02:07:09 +000016550 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016551 return true;
16552}
16553
16554void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016555 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016556 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016557 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016558}
16559
Alexey Bataev729e2422019-08-23 16:11:14 +000016560NamedDecl *
16561Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16562 const DeclarationNameInfo &Id,
16563 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016564 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16565 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16566
16567 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016568 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016569 Lookup.suppressDiagnostics();
16570
16571 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016572 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016573 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016574 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016575 CTK_ErrorRecovery)) {
16576 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16577 << Id.getName());
16578 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016579 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016580 }
16581
16582 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016583 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016584 }
16585
16586 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016587 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16588 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016589 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016590 return nullptr;
16591 }
16592 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16593 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16594 return ND;
16595}
16596
16597void Sema::ActOnOpenMPDeclareTargetName(
16598 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16599 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16600 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16601 isa<FunctionTemplateDecl>(ND)) &&
16602 "Expected variable, function or function template.");
16603
16604 // Diagnose marking after use as it may lead to incorrect diagnosis and
16605 // codegen.
16606 if (LangOpts.OpenMP >= 50 &&
16607 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16608 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16609
16610 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16611 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16612 if (DevTy.hasValue() && *DevTy != DT) {
16613 Diag(Loc, diag::err_omp_device_type_mismatch)
16614 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16615 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16616 return;
16617 }
16618 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16619 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16620 if (!Res) {
16621 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16622 SourceRange(Loc, Loc));
16623 ND->addAttr(A);
16624 if (ASTMutationListener *ML = Context.getASTMutationListener())
16625 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16626 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16627 } else if (*Res != MT) {
16628 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016629 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016630}
16631
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016632static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16633 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016634 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016635 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016636 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016637 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16638 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16639 if (SemaRef.LangOpts.OpenMP >= 50 &&
16640 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16641 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16642 VD->hasGlobalStorage()) {
16643 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16644 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16645 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16646 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16647 // If a lambda declaration and definition appears between a
16648 // declare target directive and the matching end declare target
16649 // directive, all variables that are captured by the lambda
16650 // expression must also appear in a to clause.
16651 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016652 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016653 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16654 << VD << 0 << SR;
16655 return;
16656 }
16657 }
16658 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016659 return;
16660 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16661 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016662}
16663
16664static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16665 Sema &SemaRef, DSAStackTy *Stack,
16666 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016667 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016668 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16669 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016670}
16671
Kelvin Li1ce87c72017-12-12 20:08:12 +000016672void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16673 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016674 if (!D || D->isInvalidDecl())
16675 return;
16676 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016677 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016678 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016679 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016680 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16681 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016682 return;
16683 // 2.10.6: threadprivate variable cannot appear in a declare target
16684 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016685 if (DSAStack->isThreadPrivate(VD)) {
16686 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016687 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016688 return;
16689 }
16690 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016691 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16692 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016693 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016694 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16695 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016696 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016697 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16698 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16699 return;
16700 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016701 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016702 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16703 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16704 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16705 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016706 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016707 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16708 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16709 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016710 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016711 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16712 // Problem if any with var declared with incomplete type will be reported
16713 // as normal, so no need to check it here.
16714 if ((E || !VD->getType()->isIncompleteType()) &&
16715 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16716 return;
16717 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16718 // Checking declaration inside declare target region.
16719 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16720 isa<FunctionTemplateDecl>(D)) {
16721 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016722 Context, OMPDeclareTargetDeclAttr::MT_To,
16723 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016724 D->addAttr(A);
16725 if (ASTMutationListener *ML = Context.getASTMutationListener())
16726 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16727 }
16728 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016729 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016730 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016731 if (!E)
16732 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016733 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16734}
Samuel Antao661c0902016-05-26 17:39:58 +000016735
16736OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016737 CXXScopeSpec &MapperIdScopeSpec,
16738 DeclarationNameInfo &MapperId,
16739 const OMPVarListLocTy &Locs,
16740 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016741 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016742 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16743 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016744 if (MVLI.ProcessedVarList.empty())
16745 return nullptr;
16746
Michael Kruse01f670d2019-02-22 22:29:42 +000016747 return OMPToClause::Create(
16748 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16749 MVLI.VarComponents, MVLI.UDMapperList,
16750 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016751}
Samuel Antaoec172c62016-05-26 17:49:04 +000016752
16753OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016754 CXXScopeSpec &MapperIdScopeSpec,
16755 DeclarationNameInfo &MapperId,
16756 const OMPVarListLocTy &Locs,
16757 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016758 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016759 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16760 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016761 if (MVLI.ProcessedVarList.empty())
16762 return nullptr;
16763
Michael Kruse0336c752019-02-25 20:34:15 +000016764 return OMPFromClause::Create(
16765 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16766 MVLI.VarComponents, MVLI.UDMapperList,
16767 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016768}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016769
16770OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016771 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016772 MappableVarListInfo MVLI(VarList);
16773 SmallVector<Expr *, 8> PrivateCopies;
16774 SmallVector<Expr *, 8> Inits;
16775
Alexey Bataeve3727102018-04-18 15:57:46 +000016776 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016777 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16778 SourceLocation ELoc;
16779 SourceRange ERange;
16780 Expr *SimpleRefExpr = RefExpr;
16781 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16782 if (Res.second) {
16783 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016784 MVLI.ProcessedVarList.push_back(RefExpr);
16785 PrivateCopies.push_back(nullptr);
16786 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016787 }
16788 ValueDecl *D = Res.first;
16789 if (!D)
16790 continue;
16791
16792 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016793 Type = Type.getNonReferenceType().getUnqualifiedType();
16794
16795 auto *VD = dyn_cast<VarDecl>(D);
16796
16797 // Item should be a pointer or reference to pointer.
16798 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016799 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16800 << 0 << RefExpr->getSourceRange();
16801 continue;
16802 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016803
16804 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016805 auto VDPrivate =
16806 buildVarDecl(*this, ELoc, Type, D->getName(),
16807 D->hasAttrs() ? &D->getAttrs() : nullptr,
16808 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016809 if (VDPrivate->isInvalidDecl())
16810 continue;
16811
16812 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016813 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016814 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16815
16816 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016817 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016818 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016819 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16820 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016821 AddInitializerToDecl(VDPrivate,
16822 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016823 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016824
16825 // If required, build a capture to implement the privatization initialized
16826 // with the current list item value.
16827 DeclRefExpr *Ref = nullptr;
16828 if (!VD)
16829 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16830 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16831 PrivateCopies.push_back(VDPrivateRefExpr);
16832 Inits.push_back(VDInitRefExpr);
16833
16834 // We need to add a data sharing attribute for this variable to make sure it
16835 // is correctly captured. A variable that shows up in a use_device_ptr has
16836 // similar properties of a first private variable.
16837 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16838
16839 // Create a mappable component for the list item. List items in this clause
16840 // only need a component.
16841 MVLI.VarBaseDeclarations.push_back(D);
16842 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16843 MVLI.VarComponents.back().push_back(
16844 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016845 }
16846
Samuel Antaocc10b852016-07-28 14:23:26 +000016847 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016848 return nullptr;
16849
Samuel Antaocc10b852016-07-28 14:23:26 +000016850 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016851 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16852 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016853}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016854
16855OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016856 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016857 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016858 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016859 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016860 SourceLocation ELoc;
16861 SourceRange ERange;
16862 Expr *SimpleRefExpr = RefExpr;
16863 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16864 if (Res.second) {
16865 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016866 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016867 }
16868 ValueDecl *D = Res.first;
16869 if (!D)
16870 continue;
16871
16872 QualType Type = D->getType();
16873 // item should be a pointer or array or reference to pointer or array
16874 if (!Type.getNonReferenceType()->isPointerType() &&
16875 !Type.getNonReferenceType()->isArrayType()) {
16876 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16877 << 0 << RefExpr->getSourceRange();
16878 continue;
16879 }
Samuel Antao6890b092016-07-28 14:25:09 +000016880
16881 // Check if the declaration in the clause does not show up in any data
16882 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016883 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016884 if (isOpenMPPrivate(DVar.CKind)) {
16885 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16886 << getOpenMPClauseName(DVar.CKind)
16887 << getOpenMPClauseName(OMPC_is_device_ptr)
16888 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016889 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016890 continue;
16891 }
16892
Alexey Bataeve3727102018-04-18 15:57:46 +000016893 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016894 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016895 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016896 [&ConflictExpr](
16897 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16898 OpenMPClauseKind) -> bool {
16899 ConflictExpr = R.front().getAssociatedExpression();
16900 return true;
16901 })) {
16902 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16903 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16904 << ConflictExpr->getSourceRange();
16905 continue;
16906 }
16907
16908 // Store the components in the stack so that they can be used to check
16909 // against other clauses later on.
16910 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16911 DSAStack->addMappableExpressionComponents(
16912 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16913
16914 // Record the expression we've just processed.
16915 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16916
16917 // Create a mappable component for the list item. List items in this clause
16918 // only need a component. We use a null declaration to signal fields in
16919 // 'this'.
16920 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16921 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16922 "Unexpected device pointer expression!");
16923 MVLI.VarBaseDeclarations.push_back(
16924 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16925 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16926 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016927 }
16928
Samuel Antao6890b092016-07-28 14:25:09 +000016929 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016930 return nullptr;
16931
Michael Kruse4304e9d2019-02-19 16:38:20 +000016932 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16933 MVLI.VarBaseDeclarations,
16934 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016935}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016936
16937OMPClause *Sema::ActOnOpenMPAllocateClause(
16938 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16939 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16940 if (Allocator) {
16941 // OpenMP [2.11.4 allocate Clause, Description]
16942 // allocator is an expression of omp_allocator_handle_t type.
16943 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16944 return nullptr;
16945
16946 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16947 if (AllocatorRes.isInvalid())
16948 return nullptr;
16949 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16950 DSAStack->getOMPAllocatorHandleT(),
16951 Sema::AA_Initializing,
16952 /*AllowExplicit=*/true);
16953 if (AllocatorRes.isInvalid())
16954 return nullptr;
16955 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016956 } else {
16957 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16958 // allocate clauses that appear on a target construct or on constructs in a
16959 // target region must specify an allocator expression unless a requires
16960 // directive with the dynamic_allocators clause is present in the same
16961 // compilation unit.
16962 if (LangOpts.OpenMPIsDevice &&
16963 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16964 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016965 }
16966 // Analyze and build list of variables.
16967 SmallVector<Expr *, 8> Vars;
16968 for (Expr *RefExpr : VarList) {
16969 assert(RefExpr && "NULL expr in OpenMP private clause.");
16970 SourceLocation ELoc;
16971 SourceRange ERange;
16972 Expr *SimpleRefExpr = RefExpr;
16973 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16974 if (Res.second) {
16975 // It will be analyzed later.
16976 Vars.push_back(RefExpr);
16977 }
16978 ValueDecl *D = Res.first;
16979 if (!D)
16980 continue;
16981
16982 auto *VD = dyn_cast<VarDecl>(D);
16983 DeclRefExpr *Ref = nullptr;
16984 if (!VD && !CurContext->isDependentContext())
16985 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16986 Vars.push_back((VD || CurContext->isDependentContext())
16987 ? RefExpr->IgnoreParens()
16988 : Ref);
16989 }
16990
16991 if (Vars.empty())
16992 return nullptr;
16993
16994 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16995 ColonLoc, EndLoc, Vars);
16996}