blob: ff9fe4f10c176d26c9ba15d8492ecf06e3b549d9 [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);
4698 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004699 case OMPD_distribute_simd:
4700 Res = ActOnOpenMPDistributeSimdDirective(
4701 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4702 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004703 case OMPD_target_parallel_for_simd:
4704 Res = ActOnOpenMPTargetParallelForSimdDirective(
4705 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4706 AllowedNameModifiers.push_back(OMPD_target);
4707 AllowedNameModifiers.push_back(OMPD_parallel);
4708 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004709 case OMPD_target_simd:
4710 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4711 EndLoc, VarsWithInheritedDSA);
4712 AllowedNameModifiers.push_back(OMPD_target);
4713 break;
Kelvin Li02532872016-08-05 14:37:37 +00004714 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004715 Res = ActOnOpenMPTeamsDistributeDirective(
4716 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004717 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004718 case OMPD_teams_distribute_simd:
4719 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4720 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4721 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004722 case OMPD_teams_distribute_parallel_for_simd:
4723 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4724 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4725 AllowedNameModifiers.push_back(OMPD_parallel);
4726 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004727 case OMPD_teams_distribute_parallel_for:
4728 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4729 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4730 AllowedNameModifiers.push_back(OMPD_parallel);
4731 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004732 case OMPD_target_teams:
4733 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4734 EndLoc);
4735 AllowedNameModifiers.push_back(OMPD_target);
4736 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004737 case OMPD_target_teams_distribute:
4738 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4739 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4740 AllowedNameModifiers.push_back(OMPD_target);
4741 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004742 case OMPD_target_teams_distribute_parallel_for:
4743 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4744 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4745 AllowedNameModifiers.push_back(OMPD_target);
4746 AllowedNameModifiers.push_back(OMPD_parallel);
4747 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004748 case OMPD_target_teams_distribute_parallel_for_simd:
4749 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4750 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4751 AllowedNameModifiers.push_back(OMPD_target);
4752 AllowedNameModifiers.push_back(OMPD_parallel);
4753 break;
Kelvin Lida681182017-01-10 18:08:18 +00004754 case OMPD_target_teams_distribute_simd:
4755 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4756 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4757 AllowedNameModifiers.push_back(OMPD_target);
4758 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004759 case OMPD_declare_target:
4760 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004761 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004762 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004763 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004764 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004765 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004766 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004767 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004768 llvm_unreachable("OpenMP Directive is not allowed");
4769 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004770 llvm_unreachable("Unknown OpenMP directive");
4771 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004772
Roman Lebedevb5700602019-03-20 16:32:36 +00004773 ErrorFound = Res.isInvalid() || ErrorFound;
4774
Alexey Bataev412254a2019-05-09 18:44:53 +00004775 // Check variables in the clauses if default(none) was specified.
4776 if (DSAStack->getDefaultDSA() == DSA_none) {
4777 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4778 for (OMPClause *C : Clauses) {
4779 switch (C->getClauseKind()) {
4780 case OMPC_num_threads:
4781 case OMPC_dist_schedule:
4782 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004783 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004784 break;
4785 continue;
4786 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004787 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004788 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4789 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004790 if (isOpenMPParallelDirective(Kind) &&
4791 isOpenMPTaskLoopDirective(Kind) &&
4792 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4793 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004794 continue;
4795 case OMPC_schedule:
4796 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004797 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004798 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004799 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004800 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004801 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004802 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004803 break;
4804 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004805 case OMPC_ordered:
4806 case OMPC_device:
4807 case OMPC_num_teams:
4808 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004809 case OMPC_hint:
4810 case OMPC_collapse:
4811 case OMPC_safelen:
4812 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004813 case OMPC_default:
4814 case OMPC_proc_bind:
4815 case OMPC_private:
4816 case OMPC_firstprivate:
4817 case OMPC_lastprivate:
4818 case OMPC_shared:
4819 case OMPC_reduction:
4820 case OMPC_task_reduction:
4821 case OMPC_in_reduction:
4822 case OMPC_linear:
4823 case OMPC_aligned:
4824 case OMPC_copyin:
4825 case OMPC_copyprivate:
4826 case OMPC_nowait:
4827 case OMPC_untied:
4828 case OMPC_mergeable:
4829 case OMPC_allocate:
4830 case OMPC_read:
4831 case OMPC_write:
4832 case OMPC_update:
4833 case OMPC_capture:
4834 case OMPC_seq_cst:
4835 case OMPC_depend:
4836 case OMPC_threads:
4837 case OMPC_simd:
4838 case OMPC_map:
4839 case OMPC_nogroup:
4840 case OMPC_defaultmap:
4841 case OMPC_to:
4842 case OMPC_from:
4843 case OMPC_use_device_ptr:
4844 case OMPC_is_device_ptr:
4845 continue;
4846 case OMPC_allocator:
4847 case OMPC_flush:
4848 case OMPC_threadprivate:
4849 case OMPC_uniform:
4850 case OMPC_unknown:
4851 case OMPC_unified_address:
4852 case OMPC_unified_shared_memory:
4853 case OMPC_reverse_offload:
4854 case OMPC_dynamic_allocators:
4855 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004856 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004857 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004858 llvm_unreachable("Unexpected clause");
4859 }
4860 for (Stmt *CC : C->children()) {
4861 if (CC)
4862 DSAChecker.Visit(CC);
4863 }
4864 }
4865 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4866 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4867 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004868 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004869 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4870 continue;
4871 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004872 if (DSAStack->getDefaultDSA() == DSA_none) {
4873 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4874 << P.first << P.second->getSourceRange();
4875 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4876 } else if (getLangOpts().OpenMP >= 50) {
4877 Diag(P.second->getExprLoc(),
4878 diag::err_omp_defaultmap_no_attr_for_variable)
4879 << P.first << P.second->getSourceRange();
4880 Diag(DSAStack->getDefaultDSALocation(),
4881 diag::note_omp_defaultmap_attr_none);
4882 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00004883 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004884
4885 if (!AllowedNameModifiers.empty())
4886 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4887 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004888
Alexey Bataeved09d242014-05-28 05:53:51 +00004889 if (ErrorFound)
4890 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004891
4892 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4893 Res.getAs<OMPExecutableDirective>()
4894 ->getStructuredBlock()
4895 ->setIsOMPStructuredBlock(true);
4896 }
4897
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004898 if (!CurContext->isDependentContext() &&
4899 isOpenMPTargetExecutionDirective(Kind) &&
4900 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4901 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4902 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4903 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4904 // Register target to DSA Stack.
4905 DSAStack->addTargetDirLocation(StartLoc);
4906 }
4907
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004908 return Res;
4909}
4910
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004911Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4912 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004913 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004914 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4915 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004916 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004917 assert(Linears.size() == LinModifiers.size());
4918 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004919 if (!DG || DG.get().isNull())
4920 return DeclGroupPtrTy();
4921
Alexey Bataevd158cf62019-09-13 20:18:17 +00004922 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004923 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004924 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4925 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004926 return DG;
4927 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004928 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004929 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4930 ADecl = FTD->getTemplatedDecl();
4931
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004932 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4933 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004934 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004935 return DeclGroupPtrTy();
4936 }
4937
Alexey Bataev2af33e32016-04-07 12:45:37 +00004938 // OpenMP [2.8.2, declare simd construct, Description]
4939 // The parameter of the simdlen clause must be a constant positive integer
4940 // expression.
4941 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004942 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004943 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004944 // OpenMP [2.8.2, declare simd construct, Description]
4945 // The special this pointer can be used as if was one of the arguments to the
4946 // function in any of the linear, aligned, or uniform clauses.
4947 // The uniform clause declares one or more arguments to have an invariant
4948 // value for all concurrent invocations of the function in the execution of a
4949 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004950 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4951 const Expr *UniformedLinearThis = nullptr;
4952 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004953 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004954 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4955 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004956 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4957 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004958 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004959 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004960 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004961 }
4962 if (isa<CXXThisExpr>(E)) {
4963 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004964 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004965 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004966 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4967 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004968 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004969 // OpenMP [2.8.2, declare simd construct, Description]
4970 // The aligned clause declares that the object to which each list item points
4971 // is aligned to the number of bytes expressed in the optional parameter of
4972 // the aligned clause.
4973 // The special this pointer can be used as if was one of the arguments to the
4974 // function in any of the linear, aligned, or uniform clauses.
4975 // The type of list items appearing in the aligned clause must be array,
4976 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004977 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4978 const Expr *AlignedThis = nullptr;
4979 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004980 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004981 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4982 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4983 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004984 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4985 FD->getParamDecl(PVD->getFunctionScopeIndex())
4986 ->getCanonicalDecl() == CanonPVD) {
4987 // OpenMP [2.8.1, simd construct, Restrictions]
4988 // A list-item cannot appear in more than one aligned clause.
4989 if (AlignedArgs.count(CanonPVD) > 0) {
4990 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4991 << 1 << E->getSourceRange();
4992 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4993 diag::note_omp_explicit_dsa)
4994 << getOpenMPClauseName(OMPC_aligned);
4995 continue;
4996 }
4997 AlignedArgs[CanonPVD] = E;
4998 QualType QTy = PVD->getType()
4999 .getNonReferenceType()
5000 .getUnqualifiedType()
5001 .getCanonicalType();
5002 const Type *Ty = QTy.getTypePtrOrNull();
5003 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5004 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5005 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5006 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5007 }
5008 continue;
5009 }
5010 }
5011 if (isa<CXXThisExpr>(E)) {
5012 if (AlignedThis) {
5013 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
5014 << 2 << E->getSourceRange();
5015 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5016 << getOpenMPClauseName(OMPC_aligned);
5017 }
5018 AlignedThis = E;
5019 continue;
5020 }
5021 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5022 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5023 }
5024 // The optional parameter of the aligned clause, alignment, must be a constant
5025 // positive integer expression. If no optional parameter is specified,
5026 // implementation-defined default alignments for SIMD instructions on the
5027 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005028 SmallVector<const Expr *, 4> NewAligns;
5029 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005030 ExprResult Align;
5031 if (E)
5032 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5033 NewAligns.push_back(Align.get());
5034 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005035 // OpenMP [2.8.2, declare simd construct, Description]
5036 // The linear clause declares one or more list items to be private to a SIMD
5037 // lane and to have a linear relationship with respect to the iteration space
5038 // of a loop.
5039 // The special this pointer can be used as if was one of the arguments to the
5040 // function in any of the linear, aligned, or uniform clauses.
5041 // When a linear-step expression is specified in a linear clause it must be
5042 // either a constant integer expression or an integer-typed parameter that is
5043 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005044 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005045 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5046 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005047 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005048 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5049 ++MI;
5050 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005051 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5052 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5053 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005054 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5055 FD->getParamDecl(PVD->getFunctionScopeIndex())
5056 ->getCanonicalDecl() == CanonPVD) {
5057 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5058 // A list-item cannot appear in more than one linear clause.
5059 if (LinearArgs.count(CanonPVD) > 0) {
5060 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5061 << getOpenMPClauseName(OMPC_linear)
5062 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5063 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5064 diag::note_omp_explicit_dsa)
5065 << getOpenMPClauseName(OMPC_linear);
5066 continue;
5067 }
5068 // Each argument can appear in at most one uniform or linear clause.
5069 if (UniformedArgs.count(CanonPVD) > 0) {
5070 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5071 << getOpenMPClauseName(OMPC_linear)
5072 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5073 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5074 diag::note_omp_explicit_dsa)
5075 << getOpenMPClauseName(OMPC_uniform);
5076 continue;
5077 }
5078 LinearArgs[CanonPVD] = E;
5079 if (E->isValueDependent() || E->isTypeDependent() ||
5080 E->isInstantiationDependent() ||
5081 E->containsUnexpandedParameterPack())
5082 continue;
5083 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5084 PVD->getOriginalType());
5085 continue;
5086 }
5087 }
5088 if (isa<CXXThisExpr>(E)) {
5089 if (UniformedLinearThis) {
5090 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5091 << getOpenMPClauseName(OMPC_linear)
5092 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5093 << E->getSourceRange();
5094 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5095 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5096 : OMPC_linear);
5097 continue;
5098 }
5099 UniformedLinearThis = E;
5100 if (E->isValueDependent() || E->isTypeDependent() ||
5101 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5102 continue;
5103 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5104 E->getType());
5105 continue;
5106 }
5107 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5108 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5109 }
5110 Expr *Step = nullptr;
5111 Expr *NewStep = nullptr;
5112 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005113 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005114 // Skip the same step expression, it was checked already.
5115 if (Step == E || !E) {
5116 NewSteps.push_back(E ? NewStep : nullptr);
5117 continue;
5118 }
5119 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005120 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5121 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5122 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005123 if (UniformedArgs.count(CanonPVD) == 0) {
5124 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5125 << Step->getSourceRange();
5126 } else if (E->isValueDependent() || E->isTypeDependent() ||
5127 E->isInstantiationDependent() ||
5128 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005129 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005130 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005131 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005132 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5133 << Step->getSourceRange();
5134 }
5135 continue;
5136 }
5137 NewStep = Step;
5138 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5139 !Step->isInstantiationDependent() &&
5140 !Step->containsUnexpandedParameterPack()) {
5141 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5142 .get();
5143 if (NewStep)
5144 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5145 }
5146 NewSteps.push_back(NewStep);
5147 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005148 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5149 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005150 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005151 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5152 const_cast<Expr **>(Linears.data()), Linears.size(),
5153 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5154 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005155 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005156 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005157}
5158
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005159Optional<std::pair<FunctionDecl *, Expr *>>
5160Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5161 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005162 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005163 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005164
5165 const int VariantId = 1;
5166 // Must be applied only to single decl.
5167 if (!DG.get().isSingleDecl()) {
5168 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5169 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005170 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005171 }
5172 Decl *ADecl = DG.get().getSingleDecl();
5173 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5174 ADecl = FTD->getTemplatedDecl();
5175
5176 // Decl must be a function.
5177 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5178 if (!FD) {
5179 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5180 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005181 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005182 }
5183
5184 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5185 return FD->hasAttrs() &&
5186 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5187 FD->hasAttr<TargetAttr>());
5188 };
5189 // OpenMP is not compatible with CPU-specific attributes.
5190 if (HasMultiVersionAttributes(FD)) {
5191 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5192 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005193 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005194 }
5195
5196 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005197 if (FD->isUsed(false))
5198 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005199 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005200
5201 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005202 const FunctionDecl *Definition;
5203 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5204 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005205 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5206 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005207
5208 // The VariantRef must point to function.
5209 if (!VariantRef) {
5210 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005211 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005212 }
5213
5214 // Do not check templates, wait until instantiation.
5215 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5216 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005217 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5218 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005219
5220 // Convert VariantRef expression to the type of the original function to
5221 // resolve possible conflicts.
5222 ExprResult VariantRefCast;
5223 if (LangOpts.CPlusPlus) {
5224 QualType FnPtrType;
5225 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5226 if (Method && !Method->isStatic()) {
5227 const Type *ClassType =
5228 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5229 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5230 ExprResult ER;
5231 {
5232 // Build adrr_of unary op to correctly handle type checks for member
5233 // functions.
5234 Sema::TentativeAnalysisScope Trap(*this);
5235 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5236 VariantRef);
5237 }
5238 if (!ER.isUsable()) {
5239 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5240 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005241 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005242 }
5243 VariantRef = ER.get();
5244 } else {
5245 FnPtrType = Context.getPointerType(FD->getType());
5246 }
5247 ImplicitConversionSequence ICS =
5248 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5249 /*SuppressUserConversions=*/false,
5250 /*AllowExplicit=*/false,
5251 /*InOverloadResolution=*/false,
5252 /*CStyle=*/false,
5253 /*AllowObjCWritebackConversion=*/false);
5254 if (ICS.isFailure()) {
5255 Diag(VariantRef->getExprLoc(),
5256 diag::err_omp_declare_variant_incompat_types)
5257 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005258 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005259 }
5260 VariantRefCast = PerformImplicitConversion(
5261 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5262 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005263 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005264 // Drop previously built artificial addr_of unary op for member functions.
5265 if (Method && !Method->isStatic()) {
5266 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5267 if (auto *UO = dyn_cast<UnaryOperator>(
5268 PossibleAddrOfVariantRef->IgnoreImplicit()))
5269 VariantRefCast = UO->getSubExpr();
5270 }
5271 } else {
5272 VariantRefCast = VariantRef;
5273 }
5274
5275 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5276 if (!ER.isUsable() ||
5277 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5278 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5279 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005280 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005281 }
5282
5283 // The VariantRef must point to function.
5284 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5285 if (!DRE) {
5286 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5287 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005288 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005289 }
5290 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5291 if (!NewFD) {
5292 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5293 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005294 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005295 }
5296
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005297 // Check if variant function is not marked with declare variant directive.
5298 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5299 Diag(VariantRef->getExprLoc(),
5300 diag::warn_omp_declare_variant_marked_as_declare_variant)
5301 << VariantRef->getSourceRange();
5302 SourceRange SR =
5303 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5304 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005305 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005306 }
5307
Alexey Bataevd158cf62019-09-13 20:18:17 +00005308 enum DoesntSupport {
5309 VirtFuncs = 1,
5310 Constructors = 3,
5311 Destructors = 4,
5312 DeletedFuncs = 5,
5313 DefaultedFuncs = 6,
5314 ConstexprFuncs = 7,
5315 ConstevalFuncs = 8,
5316 };
5317 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5318 if (CXXFD->isVirtual()) {
5319 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5320 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005321 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005322 }
5323
5324 if (isa<CXXConstructorDecl>(FD)) {
5325 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5326 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005327 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005328 }
5329
5330 if (isa<CXXDestructorDecl>(FD)) {
5331 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5332 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005333 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005334 }
5335 }
5336
5337 if (FD->isDeleted()) {
5338 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5339 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005340 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005341 }
5342
5343 if (FD->isDefaulted()) {
5344 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5345 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005346 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005347 }
5348
5349 if (FD->isConstexpr()) {
5350 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5351 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005352 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005353 }
5354
5355 // Check general compatibility.
5356 if (areMultiversionVariantFunctionsCompatible(
5357 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5358 PartialDiagnosticAt(
5359 SR.getBegin(),
5360 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5361 PartialDiagnosticAt(
5362 VariantRef->getExprLoc(),
5363 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5364 PartialDiagnosticAt(VariantRef->getExprLoc(),
5365 PDiag(diag::err_omp_declare_variant_diff)
5366 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005367 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5368 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005369 return None;
5370 return std::make_pair(FD, cast<Expr>(DRE));
5371}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005372
Alexey Bataev9ff34742019-09-25 19:43:37 +00005373void Sema::ActOnOpenMPDeclareVariantDirective(
5374 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005375 ArrayRef<OMPCtxSelectorData> Data) {
5376 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005377 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005378 SmallVector<Expr *, 4> CtxScores;
5379 SmallVector<unsigned, 4> CtxSets;
5380 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005381 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005382 bool IsError = false;
5383 for (const OMPCtxSelectorData &D : Data) {
5384 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5385 OpenMPContextSelectorKind Ctx = D.Ctx;
5386 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5387 return;
5388 Expr *Score = nullptr;
5389 if (D.Score.isUsable()) {
5390 Score = D.Score.get();
5391 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5392 !Score->isInstantiationDependent() &&
5393 !Score->containsUnexpandedParameterPack()) {
5394 Score =
5395 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5396 .get();
5397 if (Score)
5398 Score = VerifyIntegerConstantExpression(Score).get();
5399 }
5400 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005401 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5402 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5403 // 2^(l+2), respectively, where l is the number of traits in the construct
5404 // set.
5405 // TODO: implement correct logic for isa and arch traits.
5406 // TODO: take the construct context set into account when it is
5407 // implemented.
5408 int L = 0; // Currently set the number of traits in construct set to 0,
5409 // since the construct trait set in not supported yet.
5410 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5411 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5412 else
5413 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005414 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005415 switch (Ctx) {
5416 case OMP_CTX_vendor:
5417 assert(CtxSet == OMP_CTX_SET_implementation &&
5418 "Expected implementation context selector set.");
5419 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005420 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005421 case OMP_CTX_kind:
5422 assert(CtxSet == OMP_CTX_SET_device &&
5423 "Expected device context selector set.");
5424 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005425 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005426 case OMP_CTX_unknown:
5427 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005428 }
5429 IsError = IsError || !Score;
5430 CtxSets.push_back(CtxSet);
5431 Ctxs.push_back(Ctx);
5432 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005433 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005434 if (!IsError) {
5435 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5436 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5437 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005438 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5439 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005440 FD->addAttr(NewAttr);
5441 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005442}
5443
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005444void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5445 FunctionDecl *Func,
5446 bool MightBeOdrUse) {
5447 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5448
5449 if (!Func->isDependentContext() && Func->hasAttrs()) {
5450 for (OMPDeclareVariantAttr *A :
5451 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5452 // TODO: add checks for active OpenMP context where possible.
5453 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005454 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005455 auto *F = cast<FunctionDecl>(DRE->getDecl());
5456 if (!F->isDefined() && F->isTemplateInstantiation())
5457 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5458 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5459 }
5460 }
5461}
5462
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005463StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5464 Stmt *AStmt,
5465 SourceLocation StartLoc,
5466 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005467 if (!AStmt)
5468 return StmtError();
5469
Alexey Bataeve3727102018-04-18 15:57:46 +00005470 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005471 // 1.2.2 OpenMP Language Terminology
5472 // Structured block - An executable statement with a single entry at the
5473 // top and a single exit at the bottom.
5474 // The point of exit cannot be a branch out of the structured block.
5475 // longjmp() and throw() must not violate the entry/exit criteria.
5476 CS->getCapturedDecl()->setNothrow();
5477
Reid Kleckner87a31802018-03-12 21:43:02 +00005478 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005479
Alexey Bataev25e5b442015-09-15 12:52:43 +00005480 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5481 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005482}
5483
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005484namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005485/// Iteration space of a single for loop.
5486struct LoopIterationSpace final {
5487 /// True if the condition operator is the strict compare operator (<, > or
5488 /// !=).
5489 bool IsStrictCompare = false;
5490 /// Condition of the loop.
5491 Expr *PreCond = nullptr;
5492 /// This expression calculates the number of iterations in the loop.
5493 /// It is always possible to calculate it before starting the loop.
5494 Expr *NumIterations = nullptr;
5495 /// The loop counter variable.
5496 Expr *CounterVar = nullptr;
5497 /// Private loop counter variable.
5498 Expr *PrivateCounterVar = nullptr;
5499 /// This is initializer for the initial value of #CounterVar.
5500 Expr *CounterInit = nullptr;
5501 /// This is step for the #CounterVar used to generate its update:
5502 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5503 Expr *CounterStep = nullptr;
5504 /// Should step be subtracted?
5505 bool Subtract = false;
5506 /// Source range of the loop init.
5507 SourceRange InitSrcRange;
5508 /// Source range of the loop condition.
5509 SourceRange CondSrcRange;
5510 /// Source range of the loop increment.
5511 SourceRange IncSrcRange;
5512 /// Minimum value that can have the loop control variable. Used to support
5513 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5514 /// since only such variables can be used in non-loop invariant expressions.
5515 Expr *MinValue = nullptr;
5516 /// Maximum value that can have the loop control variable. Used to support
5517 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5518 /// since only such variables can be used in non-loop invariant expressions.
5519 Expr *MaxValue = nullptr;
5520 /// true, if the lower bound depends on the outer loop control var.
5521 bool IsNonRectangularLB = false;
5522 /// true, if the upper bound depends on the outer loop control var.
5523 bool IsNonRectangularUB = false;
5524 /// Index of the loop this loop depends on and forms non-rectangular loop
5525 /// nest.
5526 unsigned LoopDependentIdx = 0;
5527 /// Final condition for the non-rectangular loop nest support. It is used to
5528 /// check that the number of iterations for this particular counter must be
5529 /// finished.
5530 Expr *FinalCondition = nullptr;
5531};
5532
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005533/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005534/// extracting iteration space of each loop in the loop nest, that will be used
5535/// for IR generation.
5536class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005537 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005538 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005539 /// Data-sharing stack.
5540 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005541 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005542 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005543 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005544 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005545 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005546 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005547 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005548 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005550 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005551 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005552 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005553 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005554 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005555 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005556 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005557 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005558 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005559 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005560 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005561 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005562 /// Var < UB
5563 /// Var <= UB
5564 /// UB > Var
5565 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005566 /// This will have no value when the condition is !=
5567 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005568 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005569 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005570 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005571 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005572 /// The outer loop counter this loop depends on (if any).
5573 const ValueDecl *DepDecl = nullptr;
5574 /// Contains number of loop (starts from 1) on which loop counter init
5575 /// expression of this loop depends on.
5576 Optional<unsigned> InitDependOnLC;
5577 /// Contains number of loop (starts from 1) on which loop counter condition
5578 /// expression of this loop depends on.
5579 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005580 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005581 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005582 /// Original condition required for checking of the exit condition for
5583 /// non-rectangular loop.
5584 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005585
5586public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005587 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5588 SourceLocation DefaultLoc)
5589 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5590 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005591 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005592 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005593 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005594 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005595 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005596 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005597 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005598 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005599 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005600 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005601 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005602 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005603 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005604 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005605 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005607 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005608 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005609 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005610 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005611 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005612 /// True, if the compare operator is strict (<, > or !=).
5613 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005614 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005615 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005616 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005617 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005618 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005619 Expr *
5620 buildPreCond(Scope *S, Expr *Cond,
5621 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005622 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005623 DeclRefExpr *
5624 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5625 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005626 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005627 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005628 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005629 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005630 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005631 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005632 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005633 /// Build loop data with counter value for depend clauses in ordered
5634 /// directives.
5635 Expr *
5636 buildOrderedLoopData(Scope *S, Expr *Counter,
5637 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5638 SourceLocation Loc, Expr *Inc = nullptr,
5639 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005640 /// Builds the minimum value for the loop counter.
5641 std::pair<Expr *, Expr *> buildMinMaxValues(
5642 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5643 /// Builds final condition for the non-rectangular loops.
5644 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005645 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005646 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005647 /// Returns true if the initializer forms non-rectangular loop.
5648 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5649 /// Returns true if the condition forms non-rectangular loop.
5650 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5651 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5652 unsigned getLoopDependentIdx() const {
5653 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5654 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005655
5656private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005657 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005658 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005659 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005660 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005661 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5662 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005663 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005664 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5665 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005666 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005667 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005668};
5669
Alexey Bataeve3727102018-04-18 15:57:46 +00005670bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005671 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005672 assert(!LB && !UB && !Step);
5673 return false;
5674 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005675 return LCDecl->getType()->isDependentType() ||
5676 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5677 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005678}
5679
Alexey Bataeve3727102018-04-18 15:57:46 +00005680bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005681 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005682 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005683 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005684 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005685 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005686 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005687 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005688 LCDecl = getCanonicalDecl(NewLCDecl);
5689 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005690 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5691 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005692 if ((Ctor->isCopyOrMoveConstructor() ||
5693 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5694 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005695 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005696 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005697 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005698 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005699 return false;
5700}
5701
Alexey Bataev316ccf62019-01-29 18:51:58 +00005702bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5703 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005704 bool StrictOp, SourceRange SR,
5705 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005706 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005707 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5708 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005709 if (!NewUB)
5710 return true;
5711 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005712 if (LessOp)
5713 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005714 TestIsStrictOp = StrictOp;
5715 ConditionSrcRange = SR;
5716 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005717 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005718 return false;
5719}
5720
Alexey Bataeve3727102018-04-18 15:57:46 +00005721bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005722 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005723 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005724 if (!NewStep)
5725 return true;
5726 if (!NewStep->isValueDependent()) {
5727 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005728 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005729 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5730 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005731 if (Val.isInvalid())
5732 return true;
5733 NewStep = Val.get();
5734
5735 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5736 // If test-expr is of form var relational-op b and relational-op is < or
5737 // <= then incr-expr must cause var to increase on each iteration of the
5738 // loop. If test-expr is of form var relational-op b and relational-op is
5739 // > or >= then incr-expr must cause var to decrease on each iteration of
5740 // the loop.
5741 // If test-expr is of form b relational-op var and relational-op is < or
5742 // <= then incr-expr must cause var to decrease on each iteration of the
5743 // loop. If test-expr is of form b relational-op var and relational-op is
5744 // > or >= then incr-expr must cause var to increase on each iteration of
5745 // the loop.
5746 llvm::APSInt Result;
5747 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5748 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5749 bool IsConstNeg =
5750 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005751 bool IsConstPos =
5752 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005753 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005754
5755 // != with increment is treated as <; != with decrement is treated as >
5756 if (!TestIsLessOp.hasValue())
5757 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005758 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005759 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005760 (IsConstNeg || (IsUnsigned && Subtract)) :
5761 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005762 SemaRef.Diag(NewStep->getExprLoc(),
5763 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005764 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005765 SemaRef.Diag(ConditionLoc,
5766 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005767 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005768 return true;
5769 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005770 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005771 NewStep =
5772 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5773 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005774 Subtract = !Subtract;
5775 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005776 }
5777
5778 Step = NewStep;
5779 SubtractStep = Subtract;
5780 return false;
5781}
5782
Alexey Bataev622af1d2019-04-24 19:58:30 +00005783namespace {
5784/// Checker for the non-rectangular loops. Checks if the initializer or
5785/// condition expression references loop counter variable.
5786class LoopCounterRefChecker final
5787 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5788 Sema &SemaRef;
5789 DSAStackTy &Stack;
5790 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005791 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005792 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005793 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005794 unsigned BaseLoopId = 0;
5795 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5796 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5797 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5798 << (IsInitializer ? 0 : 1);
5799 return false;
5800 }
5801 const auto &&Data = Stack.isLoopControlVariable(VD);
5802 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5803 // The type of the loop iterator on which we depend may not have a random
5804 // access iterator type.
5805 if (Data.first && VD->getType()->isRecordType()) {
5806 SmallString<128> Name;
5807 llvm::raw_svector_ostream OS(Name);
5808 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5809 /*Qualified=*/true);
5810 SemaRef.Diag(E->getExprLoc(),
5811 diag::err_omp_wrong_dependency_iterator_type)
5812 << OS.str();
5813 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5814 return false;
5815 }
5816 if (Data.first &&
5817 (DepDecl || (PrevDepDecl &&
5818 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5819 if (!DepDecl && PrevDepDecl)
5820 DepDecl = PrevDepDecl;
5821 SmallString<128> Name;
5822 llvm::raw_svector_ostream OS(Name);
5823 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5824 /*Qualified=*/true);
5825 SemaRef.Diag(E->getExprLoc(),
5826 diag::err_omp_invariant_or_linear_dependency)
5827 << OS.str();
5828 return false;
5829 }
5830 if (Data.first) {
5831 DepDecl = VD;
5832 BaseLoopId = Data.first;
5833 }
5834 return Data.first;
5835 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005836
5837public:
5838 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5839 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005840 if (isa<VarDecl>(VD))
5841 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005842 return false;
5843 }
5844 bool VisitMemberExpr(const MemberExpr *E) {
5845 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5846 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005847 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5848 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005849 }
5850 return false;
5851 }
5852 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005853 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005854 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005855 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005856 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005857 }
5858 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005859 const ValueDecl *CurLCDecl, bool IsInitializer,
5860 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005861 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005862 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5863 unsigned getBaseLoopId() const {
5864 assert(CurLCDecl && "Expected loop dependency.");
5865 return BaseLoopId;
5866 }
5867 const ValueDecl *getDepDecl() const {
5868 assert(CurLCDecl && "Expected loop dependency.");
5869 return DepDecl;
5870 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005871};
5872} // namespace
5873
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005874Optional<unsigned>
5875OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5876 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005877 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005878 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5879 DepDecl);
5880 if (LoopStmtChecker.Visit(S)) {
5881 DepDecl = LoopStmtChecker.getDepDecl();
5882 return LoopStmtChecker.getBaseLoopId();
5883 }
5884 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005885}
5886
Alexey Bataeve3727102018-04-18 15:57:46 +00005887bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005888 // Check init-expr for canonical loop form and save loop counter
5889 // variable - #Var and its initialization value - #LB.
5890 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5891 // var = lb
5892 // integer-type var = lb
5893 // random-access-iterator-type var = lb
5894 // pointer-type var = lb
5895 //
5896 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005897 if (EmitDiags) {
5898 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5899 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005900 return true;
5901 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005902 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5903 if (!ExprTemp->cleanupsHaveSideEffects())
5904 S = ExprTemp->getSubExpr();
5905
Alexander Musmana5f070a2014-10-01 06:03:56 +00005906 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005907 if (Expr *E = dyn_cast<Expr>(S))
5908 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005909 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005910 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005911 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005912 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5913 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5914 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005915 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5916 EmitDiags);
5917 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005918 }
5919 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5920 if (ME->isArrow() &&
5921 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005922 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5923 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005924 }
5925 }
David Majnemer9d168222016-08-05 17:44:54 +00005926 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005927 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005928 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005929 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005930 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005931 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005932 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005933 diag::ext_omp_loop_not_canonical_init)
5934 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005935 return setLCDeclAndLB(
5936 Var,
5937 buildDeclRefExpr(SemaRef, Var,
5938 Var->getType().getNonReferenceType(),
5939 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005940 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005941 }
5942 }
5943 }
David Majnemer9d168222016-08-05 17:44:54 +00005944 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005945 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005946 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005947 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005948 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5949 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005950 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5951 EmitDiags);
5952 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005953 }
5954 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5955 if (ME->isArrow() &&
5956 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005957 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5958 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005959 }
5960 }
5961 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005962
Alexey Bataeve3727102018-04-18 15:57:46 +00005963 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005964 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005965 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005966 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005967 << S->getSourceRange();
5968 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005969 return true;
5970}
5971
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005972/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005973/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005974static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005975 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005976 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005977 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005978 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005979 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005980 if ((Ctor->isCopyOrMoveConstructor() ||
5981 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5982 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005983 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005984 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5985 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005986 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005987 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005988 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005989 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5990 return getCanonicalDecl(ME->getMemberDecl());
5991 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005992}
5993
Alexey Bataeve3727102018-04-18 15:57:46 +00005994bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005995 // Check test-expr for canonical form, save upper-bound UB, flags for
5996 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005997 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005998 // var relational-op b
5999 // b relational-op var
6000 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006001 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006002 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006003 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6004 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006005 return true;
6006 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006007 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006008 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006009 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006010 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006011 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006012 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6013 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006014 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6015 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6016 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006017 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6018 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006019 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6020 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6021 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006022 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6023 return setUB(
6024 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6025 /*LessOp=*/llvm::None,
6026 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006027 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006028 if (CE->getNumArgs() == 2) {
6029 auto Op = CE->getOperator();
6030 switch (Op) {
6031 case OO_Greater:
6032 case OO_GreaterEqual:
6033 case OO_Less:
6034 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006035 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6036 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006037 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6038 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006039 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6040 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006041 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6042 CE->getOperatorLoc());
6043 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006044 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006045 if (IneqCondIsCanonical)
6046 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6047 : CE->getArg(0),
6048 /*LessOp=*/llvm::None,
6049 /*StrictOp=*/true, CE->getSourceRange(),
6050 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006051 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006052 default:
6053 break;
6054 }
6055 }
6056 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006057 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006058 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006059 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006060 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006061 return true;
6062}
6063
Alexey Bataeve3727102018-04-18 15:57:46 +00006064bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006065 // RHS of canonical loop form increment can be:
6066 // var + incr
6067 // incr + var
6068 // var - incr
6069 //
6070 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006071 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006072 if (BO->isAdditiveOp()) {
6073 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006074 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6075 return setStep(BO->getRHS(), !IsAdd);
6076 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6077 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006078 }
David Majnemer9d168222016-08-05 17:44:54 +00006079 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006080 bool IsAdd = CE->getOperator() == OO_Plus;
6081 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006082 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6083 return setStep(CE->getArg(1), !IsAdd);
6084 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6085 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006086 }
6087 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006088 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006089 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006090 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006091 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006092 return true;
6093}
6094
Alexey Bataeve3727102018-04-18 15:57:46 +00006095bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006096 // Check incr-expr for canonical loop form and return true if it
6097 // does not conform.
6098 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6099 // ++var
6100 // var++
6101 // --var
6102 // var--
6103 // var += incr
6104 // var -= incr
6105 // var = var + incr
6106 // var = incr + var
6107 // var = var - incr
6108 //
6109 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006110 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006111 return true;
6112 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006113 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6114 if (!ExprTemp->cleanupsHaveSideEffects())
6115 S = ExprTemp->getSubExpr();
6116
Alexander Musmana5f070a2014-10-01 06:03:56 +00006117 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006118 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006119 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006120 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006121 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6122 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006123 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006124 (UO->isDecrementOp() ? -1 : 1))
6125 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006126 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006127 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006128 switch (BO->getOpcode()) {
6129 case BO_AddAssign:
6130 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006131 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6132 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006133 break;
6134 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006135 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6136 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006137 break;
6138 default:
6139 break;
6140 }
David Majnemer9d168222016-08-05 17:44:54 +00006141 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006142 switch (CE->getOperator()) {
6143 case OO_PlusPlus:
6144 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006145 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6146 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006147 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006148 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006149 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6150 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006151 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006152 break;
6153 case OO_PlusEqual:
6154 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006155 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6156 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006157 break;
6158 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006159 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6160 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006161 break;
6162 default:
6163 break;
6164 }
6165 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006166 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006167 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006168 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006169 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006170 return true;
6171}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006172
Alexey Bataev5a3af132016-03-29 08:58:54 +00006173static ExprResult
6174tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006175 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006176 if (SemaRef.CurContext->isDependentContext())
6177 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006178 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6179 return SemaRef.PerformImplicitConversion(
6180 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6181 /*AllowExplicit=*/true);
6182 auto I = Captures.find(Capture);
6183 if (I != Captures.end())
6184 return buildCapture(SemaRef, Capture, I->second);
6185 DeclRefExpr *Ref = nullptr;
6186 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6187 Captures[Capture] = Ref;
6188 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006189}
6190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006191/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006192Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006193 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006194 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006195 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006196 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006197 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006198 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006199 Expr *LBVal = LB;
6200 Expr *UBVal = UB;
6201 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6202 // max(LB(MinVal), LB(MaxVal))
6203 if (InitDependOnLC) {
6204 const LoopIterationSpace &IS =
6205 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6206 InitDependOnLC.getValueOr(
6207 CondDependOnLC.getValueOr(0))];
6208 if (!IS.MinValue || !IS.MaxValue)
6209 return nullptr;
6210 // OuterVar = Min
6211 ExprResult MinValue =
6212 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6213 if (!MinValue.isUsable())
6214 return nullptr;
6215
6216 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6217 IS.CounterVar, MinValue.get());
6218 if (!LBMinVal.isUsable())
6219 return nullptr;
6220 // OuterVar = Min, LBVal
6221 LBMinVal =
6222 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6223 if (!LBMinVal.isUsable())
6224 return nullptr;
6225 // (OuterVar = Min, LBVal)
6226 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6227 if (!LBMinVal.isUsable())
6228 return nullptr;
6229
6230 // OuterVar = Max
6231 ExprResult MaxValue =
6232 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6233 if (!MaxValue.isUsable())
6234 return nullptr;
6235
6236 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6237 IS.CounterVar, MaxValue.get());
6238 if (!LBMaxVal.isUsable())
6239 return nullptr;
6240 // OuterVar = Max, LBVal
6241 LBMaxVal =
6242 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6243 if (!LBMaxVal.isUsable())
6244 return nullptr;
6245 // (OuterVar = Max, LBVal)
6246 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6247 if (!LBMaxVal.isUsable())
6248 return nullptr;
6249
6250 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6251 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6252 if (!LBMin || !LBMax)
6253 return nullptr;
6254 // LB(MinVal) < LB(MaxVal)
6255 ExprResult MinLessMaxRes =
6256 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6257 if (!MinLessMaxRes.isUsable())
6258 return nullptr;
6259 Expr *MinLessMax =
6260 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6261 if (!MinLessMax)
6262 return nullptr;
6263 if (TestIsLessOp.getValue()) {
6264 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6265 // LB(MaxVal))
6266 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6267 MinLessMax, LBMin, LBMax);
6268 if (!MinLB.isUsable())
6269 return nullptr;
6270 LBVal = MinLB.get();
6271 } else {
6272 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6273 // LB(MaxVal))
6274 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6275 MinLessMax, LBMax, LBMin);
6276 if (!MaxLB.isUsable())
6277 return nullptr;
6278 LBVal = MaxLB.get();
6279 }
6280 }
6281 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6282 // min(UB(MinVal), UB(MaxVal))
6283 if (CondDependOnLC) {
6284 const LoopIterationSpace &IS =
6285 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6286 InitDependOnLC.getValueOr(
6287 CondDependOnLC.getValueOr(0))];
6288 if (!IS.MinValue || !IS.MaxValue)
6289 return nullptr;
6290 // OuterVar = Min
6291 ExprResult MinValue =
6292 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6293 if (!MinValue.isUsable())
6294 return nullptr;
6295
6296 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6297 IS.CounterVar, MinValue.get());
6298 if (!UBMinVal.isUsable())
6299 return nullptr;
6300 // OuterVar = Min, UBVal
6301 UBMinVal =
6302 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6303 if (!UBMinVal.isUsable())
6304 return nullptr;
6305 // (OuterVar = Min, UBVal)
6306 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6307 if (!UBMinVal.isUsable())
6308 return nullptr;
6309
6310 // OuterVar = Max
6311 ExprResult MaxValue =
6312 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6313 if (!MaxValue.isUsable())
6314 return nullptr;
6315
6316 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6317 IS.CounterVar, MaxValue.get());
6318 if (!UBMaxVal.isUsable())
6319 return nullptr;
6320 // OuterVar = Max, UBVal
6321 UBMaxVal =
6322 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6323 if (!UBMaxVal.isUsable())
6324 return nullptr;
6325 // (OuterVar = Max, UBVal)
6326 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6327 if (!UBMaxVal.isUsable())
6328 return nullptr;
6329
6330 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6331 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6332 if (!UBMin || !UBMax)
6333 return nullptr;
6334 // UB(MinVal) > UB(MaxVal)
6335 ExprResult MinGreaterMaxRes =
6336 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6337 if (!MinGreaterMaxRes.isUsable())
6338 return nullptr;
6339 Expr *MinGreaterMax =
6340 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6341 if (!MinGreaterMax)
6342 return nullptr;
6343 if (TestIsLessOp.getValue()) {
6344 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6345 // UB(MaxVal))
6346 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6347 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6348 if (!MaxUB.isUsable())
6349 return nullptr;
6350 UBVal = MaxUB.get();
6351 } else {
6352 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6353 // UB(MaxVal))
6354 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6355 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6356 if (!MinUB.isUsable())
6357 return nullptr;
6358 UBVal = MinUB.get();
6359 }
6360 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006361 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006362 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6363 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006364 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6365 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006366 if (!Upper || !Lower)
6367 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006368
6369 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6370
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006371 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006372 // BuildBinOp already emitted error, this one is to point user to upper
6373 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006374 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006375 << Upper->getSourceRange() << Lower->getSourceRange();
6376 return nullptr;
6377 }
6378 }
6379
6380 if (!Diff.isUsable())
6381 return nullptr;
6382
6383 // Upper - Lower [- 1]
6384 if (TestIsStrictOp)
6385 Diff = SemaRef.BuildBinOp(
6386 S, DefaultLoc, BO_Sub, Diff.get(),
6387 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6388 if (!Diff.isUsable())
6389 return nullptr;
6390
6391 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006392 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006393 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006394 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006395 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006396 if (!Diff.isUsable())
6397 return nullptr;
6398
6399 // Parentheses (for dumping/debugging purposes only).
6400 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6401 if (!Diff.isUsable())
6402 return nullptr;
6403
6404 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006405 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006406 if (!Diff.isUsable())
6407 return nullptr;
6408
Alexander Musman174b3ca2014-10-06 11:16:29 +00006409 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006410 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006411 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006412 bool UseVarType = VarType->hasIntegerRepresentation() &&
6413 C.getTypeSize(Type) > C.getTypeSize(VarType);
6414 if (!Type->isIntegerType() || UseVarType) {
6415 unsigned NewSize =
6416 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6417 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6418 : Type->hasSignedIntegerRepresentation();
6419 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006420 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6421 Diff = SemaRef.PerformImplicitConversion(
6422 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6423 if (!Diff.isUsable())
6424 return nullptr;
6425 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006426 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006427 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006428 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6429 if (NewSize != C.getTypeSize(Type)) {
6430 if (NewSize < C.getTypeSize(Type)) {
6431 assert(NewSize == 64 && "incorrect loop var size");
6432 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6433 << InitSrcRange << ConditionSrcRange;
6434 }
6435 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006436 NewSize, Type->hasSignedIntegerRepresentation() ||
6437 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006438 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6439 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6440 Sema::AA_Converting, true);
6441 if (!Diff.isUsable())
6442 return nullptr;
6443 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006444 }
6445 }
6446
Alexander Musmana5f070a2014-10-01 06:03:56 +00006447 return Diff.get();
6448}
6449
Alexey Bataevf8be4762019-08-14 19:30:06 +00006450std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6451 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6452 // Do not build for iterators, they cannot be used in non-rectangular loop
6453 // nests.
6454 if (LCDecl->getType()->isRecordType())
6455 return std::make_pair(nullptr, nullptr);
6456 // If we subtract, the min is in the condition, otherwise the min is in the
6457 // init value.
6458 Expr *MinExpr = nullptr;
6459 Expr *MaxExpr = nullptr;
6460 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6461 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6462 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6463 : CondDependOnLC.hasValue();
6464 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6465 : InitDependOnLC.hasValue();
6466 Expr *Lower =
6467 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6468 Expr *Upper =
6469 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6470 if (!Upper || !Lower)
6471 return std::make_pair(nullptr, nullptr);
6472
6473 if (TestIsLessOp.getValue())
6474 MinExpr = Lower;
6475 else
6476 MaxExpr = Upper;
6477
6478 // Build minimum/maximum value based on number of iterations.
6479 ExprResult Diff;
6480 QualType VarType = LCDecl->getType().getNonReferenceType();
6481
6482 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6483 if (!Diff.isUsable())
6484 return std::make_pair(nullptr, nullptr);
6485
6486 // Upper - Lower [- 1]
6487 if (TestIsStrictOp)
6488 Diff = SemaRef.BuildBinOp(
6489 S, DefaultLoc, BO_Sub, Diff.get(),
6490 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6491 if (!Diff.isUsable())
6492 return std::make_pair(nullptr, nullptr);
6493
6494 // Upper - Lower [- 1] + Step
6495 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6496 if (!NewStep.isUsable())
6497 return std::make_pair(nullptr, nullptr);
6498
6499 // Parentheses (for dumping/debugging purposes only).
6500 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6501 if (!Diff.isUsable())
6502 return std::make_pair(nullptr, nullptr);
6503
6504 // (Upper - Lower [- 1]) / Step
6505 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6506 if (!Diff.isUsable())
6507 return std::make_pair(nullptr, nullptr);
6508
6509 // ((Upper - Lower [- 1]) / Step) * Step
6510 // Parentheses (for dumping/debugging purposes only).
6511 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6512 if (!Diff.isUsable())
6513 return std::make_pair(nullptr, nullptr);
6514
6515 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6516 if (!Diff.isUsable())
6517 return std::make_pair(nullptr, nullptr);
6518
6519 // Convert to the original type or ptrdiff_t, if original type is pointer.
6520 if (!VarType->isAnyPointerType() &&
6521 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6522 Diff = SemaRef.PerformImplicitConversion(
6523 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6524 } else if (VarType->isAnyPointerType() &&
6525 !SemaRef.Context.hasSameType(
6526 Diff.get()->getType(),
6527 SemaRef.Context.getUnsignedPointerDiffType())) {
6528 Diff = SemaRef.PerformImplicitConversion(
6529 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6530 Sema::AA_Converting, /*AllowExplicit=*/true);
6531 }
6532 if (!Diff.isUsable())
6533 return std::make_pair(nullptr, nullptr);
6534
6535 // Parentheses (for dumping/debugging purposes only).
6536 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6537 if (!Diff.isUsable())
6538 return std::make_pair(nullptr, nullptr);
6539
6540 if (TestIsLessOp.getValue()) {
6541 // MinExpr = Lower;
6542 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6543 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6544 if (!Diff.isUsable())
6545 return std::make_pair(nullptr, nullptr);
6546 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6547 if (!Diff.isUsable())
6548 return std::make_pair(nullptr, nullptr);
6549 MaxExpr = Diff.get();
6550 } else {
6551 // MaxExpr = Upper;
6552 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6553 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6554 if (!Diff.isUsable())
6555 return std::make_pair(nullptr, nullptr);
6556 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6557 if (!Diff.isUsable())
6558 return std::make_pair(nullptr, nullptr);
6559 MinExpr = Diff.get();
6560 }
6561
6562 return std::make_pair(MinExpr, MaxExpr);
6563}
6564
6565Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6566 if (InitDependOnLC || CondDependOnLC)
6567 return Condition;
6568 return nullptr;
6569}
6570
Alexey Bataeve3727102018-04-18 15:57:46 +00006571Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006572 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006573 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006574 // Do not build a precondition when the condition/initialization is dependent
6575 // to prevent pessimistic early loop exit.
6576 // TODO: this can be improved by calculating min/max values but not sure that
6577 // it will be very effective.
6578 if (CondDependOnLC || InitDependOnLC)
6579 return SemaRef.PerformImplicitConversion(
6580 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6581 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6582 /*AllowExplicit=*/true).get();
6583
Alexey Bataev62dbb972015-04-22 11:59:37 +00006584 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006585 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006586
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006587 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6588 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006589 if (!NewLB.isUsable() || !NewUB.isUsable())
6590 return nullptr;
6591
Alexey Bataeve3727102018-04-18 15:57:46 +00006592 ExprResult CondExpr =
6593 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006594 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006595 (TestIsStrictOp ? BO_LT : BO_LE) :
6596 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006597 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006598 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006599 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6600 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006601 CondExpr = SemaRef.PerformImplicitConversion(
6602 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6603 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006604 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006605
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006606 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006607 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6608}
6609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006610/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006611DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006612 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6613 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006614 auto *VD = dyn_cast<VarDecl>(LCDecl);
6615 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006616 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6617 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006618 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006619 const DSAStackTy::DSAVarData Data =
6620 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006621 // If the loop control decl is explicitly marked as private, do not mark it
6622 // as captured again.
6623 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6624 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006625 return Ref;
6626 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006627 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006628}
6629
Alexey Bataeve3727102018-04-18 15:57:46 +00006630Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006631 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006632 QualType Type = LCDecl->getType().getNonReferenceType();
6633 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006634 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6635 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6636 isa<VarDecl>(LCDecl)
6637 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6638 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006639 if (PrivateVar->isInvalidDecl())
6640 return nullptr;
6641 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6642 }
6643 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006644}
6645
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006646/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006647Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006649/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006650Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006651
Alexey Bataevf138fda2018-08-13 19:04:24 +00006652Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6653 Scope *S, Expr *Counter,
6654 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6655 Expr *Inc, OverloadedOperatorKind OOK) {
6656 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6657 if (!Cnt)
6658 return nullptr;
6659 if (Inc) {
6660 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6661 "Expected only + or - operations for depend clauses.");
6662 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6663 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6664 if (!Cnt)
6665 return nullptr;
6666 }
6667 ExprResult Diff;
6668 QualType VarType = LCDecl->getType().getNonReferenceType();
6669 if (VarType->isIntegerType() || VarType->isPointerType() ||
6670 SemaRef.getLangOpts().CPlusPlus) {
6671 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006672 Expr *Upper = TestIsLessOp.getValue()
6673 ? Cnt
6674 : tryBuildCapture(SemaRef, UB, Captures).get();
6675 Expr *Lower = TestIsLessOp.getValue()
6676 ? tryBuildCapture(SemaRef, LB, Captures).get()
6677 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006678 if (!Upper || !Lower)
6679 return nullptr;
6680
6681 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6682
6683 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6684 // BuildBinOp already emitted error, this one is to point user to upper
6685 // and lower bound, and to tell what is passed to 'operator-'.
6686 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6687 << Upper->getSourceRange() << Lower->getSourceRange();
6688 return nullptr;
6689 }
6690 }
6691
6692 if (!Diff.isUsable())
6693 return nullptr;
6694
6695 // Parentheses (for dumping/debugging purposes only).
6696 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6697 if (!Diff.isUsable())
6698 return nullptr;
6699
6700 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6701 if (!NewStep.isUsable())
6702 return nullptr;
6703 // (Upper - Lower) / Step
6704 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6705 if (!Diff.isUsable())
6706 return nullptr;
6707
6708 return Diff.get();
6709}
Alexey Bataev23b69422014-06-18 07:08:49 +00006710} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006711
Alexey Bataev9c821032015-04-30 04:23:23 +00006712void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6713 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6714 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006715 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6716 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006717 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006718 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006719 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006720 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6721 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006722 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006723 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006724 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006725 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006726 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006727 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006728 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6729 /*WithInit=*/false);
6730 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006731 }
6732 }
6733 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006734 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6735 if (LD != D->getCanonicalDecl()) {
6736 DSAStack->resetPossibleLoopCounter();
6737 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6738 MarkDeclarationsReferencedInExpr(
6739 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6740 Var->getType().getNonLValueExprType(Context),
6741 ForLoc, /*RefersToCapture=*/true));
6742 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006743 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6744 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6745 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6746 // associated for-loop of a simd construct with just one associated
6747 // for-loop may be listed in a linear clause with a constant-linear-step
6748 // that is the increment of the associated for-loop. The loop iteration
6749 // variable(s) in the associated for-loop(s) of a for or parallel for
6750 // construct may be listed in a private or lastprivate clause.
6751 DSAStackTy::DSAVarData DVar =
6752 DSAStack->getTopDSA(D, /*FromParent=*/false);
6753 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6754 // is declared in the loop and it is predetermined as a private.
6755 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6756 OpenMPClauseKind PredeterminedCKind =
6757 isOpenMPSimdDirective(DKind)
6758 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6759 : OMPC_private;
6760 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6761 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6762 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6763 DVar.CKind != OMPC_private))) ||
6764 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006765 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006766 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006767 isOpenMPDistributeDirective(DKind)) &&
6768 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6769 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6770 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6771 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6772 << getOpenMPClauseName(DVar.CKind)
6773 << getOpenMPDirectiveName(DKind)
6774 << getOpenMPClauseName(PredeterminedCKind);
6775 if (DVar.RefExpr == nullptr)
6776 DVar.CKind = PredeterminedCKind;
6777 reportOriginalDsa(*this, DSAStack, D, DVar,
6778 /*IsLoopIterVar=*/true);
6779 } else if (LoopDeclRefExpr) {
6780 // Make the loop iteration variable private (for worksharing
6781 // constructs), linear (for simd directives with the only one
6782 // associated loop) or lastprivate (for simd directives with several
6783 // collapsed or ordered loops).
6784 if (DVar.CKind == OMPC_unknown)
6785 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6786 PrivateRef);
6787 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006788 }
6789 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006790 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006791 }
6792}
6793
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006794/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006795/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006796static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006797 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6798 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006799 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6800 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006801 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006802 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006803 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006804 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006805 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006806 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006807 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006808 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6809 // Ranged for is supported only in OpenMP 5.0.
6810 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006811 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006812 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006813 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006814 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006815 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006816 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6817 SemaRef.Diag(DSA.getConstructLoc(),
6818 diag::note_omp_collapse_ordered_expr)
6819 << 2 << CollapseLoopCountExpr->getSourceRange()
6820 << OrderedLoopCountExpr->getSourceRange();
6821 else if (CollapseLoopCountExpr)
6822 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6823 diag::note_omp_collapse_ordered_expr)
6824 << 0 << CollapseLoopCountExpr->getSourceRange();
6825 else
6826 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6827 diag::note_omp_collapse_ordered_expr)
6828 << 1 << OrderedLoopCountExpr->getSourceRange();
6829 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006830 return true;
6831 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006832 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6833 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006834
Alexey Bataevbef93a92019-10-07 18:54:57 +00006835 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6836 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006837
6838 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006839 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006840 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006841 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006842
6843 bool HasErrors = false;
6844
6845 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006846 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006847 // OpenMP [2.6, Canonical Loop Form]
6848 // Var is one of the following:
6849 // A variable of signed or unsigned integer type.
6850 // For C++, a variable of a random access iterator type.
6851 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006852 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006853 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6854 !VarType->isPointerType() &&
6855 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006856 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006857 << SemaRef.getLangOpts().CPlusPlus;
6858 HasErrors = true;
6859 }
6860
6861 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6862 // a Construct
6863 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6864 // parallel for construct is (are) private.
6865 // The loop iteration variable in the associated for-loop of a simd
6866 // construct with just one associated for-loop is linear with a
6867 // constant-linear-step that is the increment of the associated for-loop.
6868 // Exclude loop var from the list of variables with implicitly defined data
6869 // sharing attributes.
6870 VarsWithImplicitDSA.erase(LCDecl);
6871
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006872 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6873
6874 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006875 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006876
6877 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006878 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006879 }
6880
Alexey Bataeve3727102018-04-18 15:57:46 +00006881 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006882 return HasErrors;
6883
Alexander Musmana5f070a2014-10-01 06:03:56 +00006884 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006885 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6886 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006887 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6888 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6889 (isOpenMPWorksharingDirective(DKind) ||
6890 isOpenMPTaskLoopDirective(DKind) ||
6891 isOpenMPDistributeDirective(DKind)),
6892 Captures);
6893 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6894 ISC.buildCounterVar(Captures, DSA);
6895 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6896 ISC.buildPrivateCounterVar();
6897 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6898 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6899 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6900 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6901 ISC.getConditionSrcRange();
6902 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6903 ISC.getIncrementSrcRange();
6904 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6905 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6906 ISC.isStrictTestOp();
6907 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6908 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6909 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6910 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6911 ISC.buildFinalCondition(DSA.getCurScope());
6912 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6913 ISC.doesInitDependOnLC();
6914 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6915 ISC.doesCondDependOnLC();
6916 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6917 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006918
Alexey Bataevf8be4762019-08-14 19:30:06 +00006919 HasErrors |=
6920 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6921 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6922 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6923 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6924 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6925 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006926 if (!HasErrors && DSA.isOrderedRegion()) {
6927 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6928 if (CurrentNestedLoopCount <
6929 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6930 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006931 CurrentNestedLoopCount,
6932 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006933 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006934 CurrentNestedLoopCount,
6935 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006936 }
6937 }
6938 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6939 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6940 // Erroneous case - clause has some problems.
6941 continue;
6942 }
6943 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6944 Pair.second.size() <= CurrentNestedLoopCount) {
6945 // Erroneous case - clause has some problems.
6946 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6947 continue;
6948 }
6949 Expr *CntValue;
6950 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6951 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006952 DSA.getCurScope(),
6953 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006954 Pair.first->getDependencyLoc());
6955 else
6956 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006957 DSA.getCurScope(),
6958 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006959 Pair.first->getDependencyLoc(),
6960 Pair.second[CurrentNestedLoopCount].first,
6961 Pair.second[CurrentNestedLoopCount].second);
6962 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6963 }
6964 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006965
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006966 return HasErrors;
6967}
6968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006969/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006970static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006971buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006972 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006973 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006974 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006975 ExprResult NewStart = IsNonRectangularLB
6976 ? Start.get()
6977 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006978 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006979 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006980 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006981 VarRef.get()->getType())) {
6982 NewStart = SemaRef.PerformImplicitConversion(
6983 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6984 /*AllowExplicit=*/true);
6985 if (!NewStart.isUsable())
6986 return ExprError();
6987 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006988
Alexey Bataeve3727102018-04-18 15:57:46 +00006989 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006990 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6991 return Init;
6992}
6993
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006994/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006995static ExprResult buildCounterUpdate(
6996 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6997 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006998 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006999 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007000 // Add parentheses (for debugging purposes only).
7001 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7002 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7003 !Step.isUsable())
7004 return ExprError();
7005
Alexey Bataev5a3af132016-03-29 08:58:54 +00007006 ExprResult NewStep = Step;
7007 if (Captures)
7008 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007009 if (NewStep.isInvalid())
7010 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007011 ExprResult Update =
7012 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007013 if (!Update.isUsable())
7014 return ExprError();
7015
Alexey Bataevc0214e02016-02-16 12:13:49 +00007016 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7017 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007018 if (!Start.isUsable())
7019 return ExprError();
7020 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7021 if (!NewStart.isUsable())
7022 return ExprError();
7023 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007024 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007025 if (NewStart.isInvalid())
7026 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007027
Alexey Bataevc0214e02016-02-16 12:13:49 +00007028 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7029 ExprResult SavedUpdate = Update;
7030 ExprResult UpdateVal;
7031 if (VarRef.get()->getType()->isOverloadableType() ||
7032 NewStart.get()->getType()->isOverloadableType() ||
7033 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007034 Sema::TentativeAnalysisScope Trap(SemaRef);
7035
Alexey Bataevc0214e02016-02-16 12:13:49 +00007036 Update =
7037 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7038 if (Update.isUsable()) {
7039 UpdateVal =
7040 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7041 VarRef.get(), SavedUpdate.get());
7042 if (UpdateVal.isUsable()) {
7043 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7044 UpdateVal.get());
7045 }
7046 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007047 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007048
Alexey Bataevc0214e02016-02-16 12:13:49 +00007049 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7050 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7051 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7052 NewStart.get(), SavedUpdate.get());
7053 if (!Update.isUsable())
7054 return ExprError();
7055
Alexey Bataev11481f52016-02-17 10:29:05 +00007056 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7057 VarRef.get()->getType())) {
7058 Update = SemaRef.PerformImplicitConversion(
7059 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7060 if (!Update.isUsable())
7061 return ExprError();
7062 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007063
7064 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7065 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007066 return Update;
7067}
7068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007069/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007070/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007071static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007072 if (E == nullptr)
7073 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007074 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007075 QualType OldType = E->getType();
7076 unsigned HasBits = C.getTypeSize(OldType);
7077 if (HasBits >= Bits)
7078 return ExprResult(E);
7079 // OK to convert to signed, because new type has more bits than old.
7080 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7081 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7082 true);
7083}
7084
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007085/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007086/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007087static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007088 if (E == nullptr)
7089 return false;
7090 llvm::APSInt Result;
7091 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7092 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7093 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007094}
7095
Alexey Bataev5a3af132016-03-29 08:58:54 +00007096/// Build preinits statement for the given declarations.
7097static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007098 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007099 if (!PreInits.empty()) {
7100 return new (Context) DeclStmt(
7101 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7102 SourceLocation(), SourceLocation());
7103 }
7104 return nullptr;
7105}
7106
7107/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007108static Stmt *
7109buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007110 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007111 if (!Captures.empty()) {
7112 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007113 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007114 PreInits.push_back(Pair.second->getDecl());
7115 return buildPreInits(Context, PreInits);
7116 }
7117 return nullptr;
7118}
7119
7120/// Build postupdate expression for the given list of postupdates expressions.
7121static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7122 Expr *PostUpdate = nullptr;
7123 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007124 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007125 Expr *ConvE = S.BuildCStyleCastExpr(
7126 E->getExprLoc(),
7127 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7128 E->getExprLoc(), E)
7129 .get();
7130 PostUpdate = PostUpdate
7131 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7132 PostUpdate, ConvE)
7133 .get()
7134 : ConvE;
7135 }
7136 }
7137 return PostUpdate;
7138}
7139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007140/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007141/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7142/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007143static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007144checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007145 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7146 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007147 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007148 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007149 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007150 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007151 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007152 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007153 if (!CollapseLoopCountExpr->isValueDependent() &&
7154 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007155 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007156 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007157 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007158 return 1;
7159 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007160 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007161 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007162 if (OrderedLoopCountExpr) {
7163 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007164 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007165 if (!OrderedLoopCountExpr->isValueDependent() &&
7166 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7167 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007168 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007169 if (Result.getLimitedValue() < NestedLoopCount) {
7170 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7171 diag::err_omp_wrong_ordered_loop_count)
7172 << OrderedLoopCountExpr->getSourceRange();
7173 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7174 diag::note_collapse_loop_count)
7175 << CollapseLoopCountExpr->getSourceRange();
7176 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007177 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007178 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007179 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007180 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007181 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007182 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007183 // This is helper routine for loop directives (e.g., 'for', 'simd',
7184 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007185 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007186 SmallVector<LoopIterationSpace, 4> IterSpaces(
7187 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007188 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007189 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007190 if (checkOpenMPIterationSpace(
7191 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7192 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007193 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007194 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007195 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007196 // OpenMP [2.8.1, simd construct, Restrictions]
7197 // All loops associated with the construct must be perfectly nested; that
7198 // is, there must be no intervening code nor any OpenMP directive between
7199 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007200 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7201 CurStmt = For->getBody();
7202 } else {
7203 assert(isa<CXXForRangeStmt>(CurStmt) &&
7204 "Expected canonical for or range-based for loops.");
7205 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7206 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007207 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7208 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007209 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007210 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7211 if (checkOpenMPIterationSpace(
7212 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7213 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007214 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007215 return 0;
7216 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7217 // Handle initialization of captured loop iterator variables.
7218 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7219 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7220 Captures[DRE] = DRE;
7221 }
7222 }
7223 // Move on to the next nested for loop, or to the loop body.
7224 // OpenMP [2.8.1, simd construct, Restrictions]
7225 // All loops associated with the construct must be perfectly nested; that
7226 // is, there must be no intervening code nor any OpenMP directive between
7227 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007228 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7229 CurStmt = For->getBody();
7230 } else {
7231 assert(isa<CXXForRangeStmt>(CurStmt) &&
7232 "Expected canonical for or range-based for loops.");
7233 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7234 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007235 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7236 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007237 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007238
Alexander Musmana5f070a2014-10-01 06:03:56 +00007239 Built.clear(/* size */ NestedLoopCount);
7240
7241 if (SemaRef.CurContext->isDependentContext())
7242 return NestedLoopCount;
7243
7244 // An example of what is generated for the following code:
7245 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007246 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007247 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007248 // for (k = 0; k < NK; ++k)
7249 // for (j = J0; j < NJ; j+=2) {
7250 // <loop body>
7251 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007252 //
7253 // We generate the code below.
7254 // Note: the loop body may be outlined in CodeGen.
7255 // Note: some counters may be C++ classes, operator- is used to find number of
7256 // iterations and operator+= to calculate counter value.
7257 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7258 // or i64 is currently supported).
7259 //
7260 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7261 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7262 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7263 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7264 // // similar updates for vars in clauses (e.g. 'linear')
7265 // <loop body (using local i and j)>
7266 // }
7267 // i = NI; // assign final values of counters
7268 // j = NJ;
7269 //
7270
7271 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7272 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007273 // Precondition tests if there is at least one iteration (all conditions are
7274 // true).
7275 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007276 Expr *N0 = IterSpaces[0].NumIterations;
7277 ExprResult LastIteration32 =
7278 widenIterationCount(/*Bits=*/32,
7279 SemaRef
7280 .PerformImplicitConversion(
7281 N0->IgnoreImpCasts(), N0->getType(),
7282 Sema::AA_Converting, /*AllowExplicit=*/true)
7283 .get(),
7284 SemaRef);
7285 ExprResult LastIteration64 = widenIterationCount(
7286 /*Bits=*/64,
7287 SemaRef
7288 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7289 Sema::AA_Converting,
7290 /*AllowExplicit=*/true)
7291 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007292 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007293
7294 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7295 return NestedLoopCount;
7296
Alexey Bataeve3727102018-04-18 15:57:46 +00007297 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007298 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7299
7300 Scope *CurScope = DSA.getCurScope();
7301 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007302 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007303 PreCond =
7304 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7305 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007306 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007307 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007308 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007309 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7310 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007311 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007312 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007313 SemaRef
7314 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7315 Sema::AA_Converting,
7316 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007317 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007318 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007319 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007320 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007321 SemaRef
7322 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7323 Sema::AA_Converting,
7324 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007325 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007326 }
7327
7328 // Choose either the 32-bit or 64-bit version.
7329 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007330 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7331 (LastIteration32.isUsable() &&
7332 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7333 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7334 fitsInto(
7335 /*Bits=*/32,
7336 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7337 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007338 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007339 QualType VType = LastIteration.get()->getType();
7340 QualType RealVType = VType;
7341 QualType StrideVType = VType;
7342 if (isOpenMPTaskLoopDirective(DKind)) {
7343 VType =
7344 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7345 StrideVType =
7346 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7347 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007348
7349 if (!LastIteration.isUsable())
7350 return 0;
7351
7352 // Save the number of iterations.
7353 ExprResult NumIterations = LastIteration;
7354 {
7355 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007356 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7357 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007358 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7359 if (!LastIteration.isUsable())
7360 return 0;
7361 }
7362
7363 // Calculate the last iteration number beforehand instead of doing this on
7364 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7365 llvm::APSInt Result;
7366 bool IsConstant =
7367 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7368 ExprResult CalcLastIteration;
7369 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007370 ExprResult SaveRef =
7371 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007372 LastIteration = SaveRef;
7373
7374 // Prepare SaveRef + 1.
7375 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007376 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007377 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7378 if (!NumIterations.isUsable())
7379 return 0;
7380 }
7381
7382 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7383
David Majnemer9d168222016-08-05 17:44:54 +00007384 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007385 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007386 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7387 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007388 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007389 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7390 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007391 SemaRef.AddInitializerToDecl(LBDecl,
7392 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7393 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007394
7395 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007396 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7397 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007398 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007399 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007400
7401 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7402 // This will be used to implement clause 'lastprivate'.
7403 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007404 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7405 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007406 SemaRef.AddInitializerToDecl(ILDecl,
7407 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7408 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007409
7410 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007411 VarDecl *STDecl =
7412 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7413 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007414 SemaRef.AddInitializerToDecl(STDecl,
7415 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7416 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007417
7418 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007419 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007420 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7421 UB.get(), LastIteration.get());
7422 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007423 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7424 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007425 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7426 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007427 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007428
7429 // If we have a combined directive that combines 'distribute', 'for' or
7430 // 'simd' we need to be able to access the bounds of the schedule of the
7431 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7432 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7433 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007434 // Lower bound variable, initialized with zero.
7435 VarDecl *CombLBDecl =
7436 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7437 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7438 SemaRef.AddInitializerToDecl(
7439 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7440 /*DirectInit*/ false);
7441
7442 // Upper bound variable, initialized with last iteration number.
7443 VarDecl *CombUBDecl =
7444 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7445 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7446 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7447 /*DirectInit*/ false);
7448
7449 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7450 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7451 ExprResult CombCondOp =
7452 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7453 LastIteration.get(), CombUB.get());
7454 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7455 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007456 CombEUB =
7457 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007458
Alexey Bataeve3727102018-04-18 15:57:46 +00007459 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007460 // We expect to have at least 2 more parameters than the 'parallel'
7461 // directive does - the lower and upper bounds of the previous schedule.
7462 assert(CD->getNumParams() >= 4 &&
7463 "Unexpected number of parameters in loop combined directive");
7464
7465 // Set the proper type for the bounds given what we learned from the
7466 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007467 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7468 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007469
7470 // Previous lower and upper bounds are obtained from the region
7471 // parameters.
7472 PrevLB =
7473 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7474 PrevUB =
7475 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7476 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007477 }
7478
7479 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007480 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007481 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007482 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007483 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7484 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007485 Expr *RHS =
7486 (isOpenMPWorksharingDirective(DKind) ||
7487 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7488 ? LB.get()
7489 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007490 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007491 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007492
7493 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7494 Expr *CombRHS =
7495 (isOpenMPWorksharingDirective(DKind) ||
7496 isOpenMPTaskLoopDirective(DKind) ||
7497 isOpenMPDistributeDirective(DKind))
7498 ? CombLB.get()
7499 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7500 CombInit =
7501 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007502 CombInit =
7503 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007504 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007505 }
7506
Alexey Bataev316ccf62019-01-29 18:51:58 +00007507 bool UseStrictCompare =
7508 RealVType->hasUnsignedIntegerRepresentation() &&
7509 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7510 return LIS.IsStrictCompare;
7511 });
7512 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7513 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007514 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007515 Expr *BoundUB = UB.get();
7516 if (UseStrictCompare) {
7517 BoundUB =
7518 SemaRef
7519 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7520 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7521 .get();
7522 BoundUB =
7523 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7524 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007525 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007526 (isOpenMPWorksharingDirective(DKind) ||
7527 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007528 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7529 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7530 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007531 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7532 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007533 ExprResult CombDistCond;
7534 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007535 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7536 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007537 }
7538
Carlo Bertolliffafe102017-04-20 00:39:39 +00007539 ExprResult CombCond;
7540 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007541 Expr *BoundCombUB = CombUB.get();
7542 if (UseStrictCompare) {
7543 BoundCombUB =
7544 SemaRef
7545 .BuildBinOp(
7546 CurScope, CondLoc, BO_Add, BoundCombUB,
7547 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7548 .get();
7549 BoundCombUB =
7550 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7551 .get();
7552 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007553 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007554 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7555 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007556 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007557 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007558 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007559 ExprResult Inc =
7560 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7561 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7562 if (!Inc.isUsable())
7563 return 0;
7564 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007565 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007566 if (!Inc.isUsable())
7567 return 0;
7568
7569 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7570 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007571 // In combined construct, add combined version that use CombLB and CombUB
7572 // base variables for the update
7573 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007574 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7575 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007576 // LB + ST
7577 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7578 if (!NextLB.isUsable())
7579 return 0;
7580 // LB = LB + ST
7581 NextLB =
7582 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007583 NextLB =
7584 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007585 if (!NextLB.isUsable())
7586 return 0;
7587 // UB + ST
7588 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7589 if (!NextUB.isUsable())
7590 return 0;
7591 // UB = UB + ST
7592 NextUB =
7593 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007594 NextUB =
7595 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007596 if (!NextUB.isUsable())
7597 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007598 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7599 CombNextLB =
7600 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7601 if (!NextLB.isUsable())
7602 return 0;
7603 // LB = LB + ST
7604 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7605 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007606 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7607 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007608 if (!CombNextLB.isUsable())
7609 return 0;
7610 // UB + ST
7611 CombNextUB =
7612 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7613 if (!CombNextUB.isUsable())
7614 return 0;
7615 // UB = UB + ST
7616 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7617 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007618 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7619 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007620 if (!CombNextUB.isUsable())
7621 return 0;
7622 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007623 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007624
Carlo Bertolliffafe102017-04-20 00:39:39 +00007625 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007626 // directive with for as IV = IV + ST; ensure upper bound expression based
7627 // on PrevUB instead of NumIterations - used to implement 'for' when found
7628 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007629 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007630 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007631 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007632 DistCond = SemaRef.BuildBinOp(
7633 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007634 assert(DistCond.isUsable() && "distribute cond expr was not built");
7635
7636 DistInc =
7637 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7638 assert(DistInc.isUsable() && "distribute inc expr was not built");
7639 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7640 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007641 DistInc =
7642 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007643 assert(DistInc.isUsable() && "distribute inc expr was not built");
7644
7645 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7646 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007647 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007648 ExprResult IsUBGreater =
7649 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7650 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7651 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7652 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7653 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007654 PrevEUB =
7655 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007656
Alexey Bataev316ccf62019-01-29 18:51:58 +00007657 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7658 // parallel for is in combination with a distribute directive with
7659 // schedule(static, 1)
7660 Expr *BoundPrevUB = PrevUB.get();
7661 if (UseStrictCompare) {
7662 BoundPrevUB =
7663 SemaRef
7664 .BuildBinOp(
7665 CurScope, CondLoc, BO_Add, BoundPrevUB,
7666 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7667 .get();
7668 BoundPrevUB =
7669 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7670 .get();
7671 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007672 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007673 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7674 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007675 }
7676
Alexander Musmana5f070a2014-10-01 06:03:56 +00007677 // Build updates and final values of the loop counters.
7678 bool HasErrors = false;
7679 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007680 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007681 Built.Updates.resize(NestedLoopCount);
7682 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007683 Built.DependentCounters.resize(NestedLoopCount);
7684 Built.DependentInits.resize(NestedLoopCount);
7685 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007686 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007687 // We implement the following algorithm for obtaining the
7688 // original loop iteration variable values based on the
7689 // value of the collapsed loop iteration variable IV.
7690 //
7691 // Let n+1 be the number of collapsed loops in the nest.
7692 // Iteration variables (I0, I1, .... In)
7693 // Iteration counts (N0, N1, ... Nn)
7694 //
7695 // Acc = IV;
7696 //
7697 // To compute Ik for loop k, 0 <= k <= n, generate:
7698 // Prod = N(k+1) * N(k+2) * ... * Nn;
7699 // Ik = Acc / Prod;
7700 // Acc -= Ik * Prod;
7701 //
7702 ExprResult Acc = IV;
7703 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007704 LoopIterationSpace &IS = IterSpaces[Cnt];
7705 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007706 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007707
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007708 // Compute prod
7709 ExprResult Prod =
7710 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7711 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7712 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7713 IterSpaces[K].NumIterations);
7714
7715 // Iter = Acc / Prod
7716 // If there is at least one more inner loop to avoid
7717 // multiplication by 1.
7718 if (Cnt + 1 < NestedLoopCount)
7719 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7720 Acc.get(), Prod.get());
7721 else
7722 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007723 if (!Iter.isUsable()) {
7724 HasErrors = true;
7725 break;
7726 }
7727
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007728 // Update Acc:
7729 // Acc -= Iter * Prod
7730 // Check if there is at least one more inner loop to avoid
7731 // multiplication by 1.
7732 if (Cnt + 1 < NestedLoopCount)
7733 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7734 Iter.get(), Prod.get());
7735 else
7736 Prod = Iter;
7737 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7738 Acc.get(), Prod.get());
7739
Alexey Bataev39f915b82015-05-08 10:41:21 +00007740 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007741 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007742 DeclRefExpr *CounterVar = buildDeclRefExpr(
7743 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7744 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007745 ExprResult Init =
7746 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7747 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007748 if (!Init.isUsable()) {
7749 HasErrors = true;
7750 break;
7751 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007752 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007753 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007754 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007755 if (!Update.isUsable()) {
7756 HasErrors = true;
7757 break;
7758 }
7759
7760 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007761 ExprResult Final =
7762 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7763 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7764 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007765 if (!Final.isUsable()) {
7766 HasErrors = true;
7767 break;
7768 }
7769
Alexander Musmana5f070a2014-10-01 06:03:56 +00007770 if (!Update.isUsable() || !Final.isUsable()) {
7771 HasErrors = true;
7772 break;
7773 }
7774 // Save results
7775 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007776 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007777 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007778 Built.Updates[Cnt] = Update.get();
7779 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007780 Built.DependentCounters[Cnt] = nullptr;
7781 Built.DependentInits[Cnt] = nullptr;
7782 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007783 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007784 Built.DependentCounters[Cnt] =
7785 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7786 Built.DependentInits[Cnt] =
7787 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7788 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7789 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007790 }
7791 }
7792
7793 if (HasErrors)
7794 return 0;
7795
7796 // Save results
7797 Built.IterationVarRef = IV.get();
7798 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007799 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007800 Built.CalcLastIteration = SemaRef
7801 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007802 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007803 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007804 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007805 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007806 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007807 Built.Init = Init.get();
7808 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007809 Built.LB = LB.get();
7810 Built.UB = UB.get();
7811 Built.IL = IL.get();
7812 Built.ST = ST.get();
7813 Built.EUB = EUB.get();
7814 Built.NLB = NextLB.get();
7815 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007816 Built.PrevLB = PrevLB.get();
7817 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007818 Built.DistInc = DistInc.get();
7819 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007820 Built.DistCombinedFields.LB = CombLB.get();
7821 Built.DistCombinedFields.UB = CombUB.get();
7822 Built.DistCombinedFields.EUB = CombEUB.get();
7823 Built.DistCombinedFields.Init = CombInit.get();
7824 Built.DistCombinedFields.Cond = CombCond.get();
7825 Built.DistCombinedFields.NLB = CombNextLB.get();
7826 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007827 Built.DistCombinedFields.DistCond = CombDistCond.get();
7828 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007829
Alexey Bataevabfc0692014-06-25 06:52:00 +00007830 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007831}
7832
Alexey Bataev10e775f2015-07-30 11:36:16 +00007833static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007834 auto CollapseClauses =
7835 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7836 if (CollapseClauses.begin() != CollapseClauses.end())
7837 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007838 return nullptr;
7839}
7840
Alexey Bataev10e775f2015-07-30 11:36:16 +00007841static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007842 auto OrderedClauses =
7843 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7844 if (OrderedClauses.begin() != OrderedClauses.end())
7845 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007846 return nullptr;
7847}
7848
Kelvin Lic5609492016-07-15 04:39:07 +00007849static bool checkSimdlenSafelenSpecified(Sema &S,
7850 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007851 const OMPSafelenClause *Safelen = nullptr;
7852 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007853
Alexey Bataeve3727102018-04-18 15:57:46 +00007854 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007855 if (Clause->getClauseKind() == OMPC_safelen)
7856 Safelen = cast<OMPSafelenClause>(Clause);
7857 else if (Clause->getClauseKind() == OMPC_simdlen)
7858 Simdlen = cast<OMPSimdlenClause>(Clause);
7859 if (Safelen && Simdlen)
7860 break;
7861 }
7862
7863 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007864 const Expr *SimdlenLength = Simdlen->getSimdlen();
7865 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007866 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7867 SimdlenLength->isInstantiationDependent() ||
7868 SimdlenLength->containsUnexpandedParameterPack())
7869 return false;
7870 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7871 SafelenLength->isInstantiationDependent() ||
7872 SafelenLength->containsUnexpandedParameterPack())
7873 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007874 Expr::EvalResult SimdlenResult, SafelenResult;
7875 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7876 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7877 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7878 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007879 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7880 // If both simdlen and safelen clauses are specified, the value of the
7881 // simdlen parameter must be less than or equal to the value of the safelen
7882 // parameter.
7883 if (SimdlenRes > SafelenRes) {
7884 S.Diag(SimdlenLength->getExprLoc(),
7885 diag::err_omp_wrong_simdlen_safelen_values)
7886 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7887 return true;
7888 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007889 }
7890 return false;
7891}
7892
Alexey Bataeve3727102018-04-18 15:57:46 +00007893StmtResult
7894Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7895 SourceLocation StartLoc, SourceLocation EndLoc,
7896 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007897 if (!AStmt)
7898 return StmtError();
7899
7900 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007901 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007902 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7903 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007904 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007905 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7906 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007907 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007908 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007909
Alexander Musmana5f070a2014-10-01 06:03:56 +00007910 assert((CurContext->isDependentContext() || B.builtAll()) &&
7911 "omp simd loop exprs were not built");
7912
Alexander Musman3276a272015-03-21 10:12:56 +00007913 if (!CurContext->isDependentContext()) {
7914 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007915 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007916 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007917 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007918 B.NumIterations, *this, CurScope,
7919 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007920 return StmtError();
7921 }
7922 }
7923
Kelvin Lic5609492016-07-15 04:39:07 +00007924 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007925 return StmtError();
7926
Reid Kleckner87a31802018-03-12 21:43:02 +00007927 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007928 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7929 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007930}
7931
Alexey Bataeve3727102018-04-18 15:57:46 +00007932StmtResult
7933Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7934 SourceLocation StartLoc, SourceLocation EndLoc,
7935 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007936 if (!AStmt)
7937 return StmtError();
7938
7939 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007940 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007941 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7942 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007943 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007944 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7945 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007946 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007947 return StmtError();
7948
Alexander Musmana5f070a2014-10-01 06:03:56 +00007949 assert((CurContext->isDependentContext() || B.builtAll()) &&
7950 "omp for loop exprs were not built");
7951
Alexey Bataev54acd402015-08-04 11:18:19 +00007952 if (!CurContext->isDependentContext()) {
7953 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007954 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007955 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007956 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007957 B.NumIterations, *this, CurScope,
7958 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007959 return StmtError();
7960 }
7961 }
7962
Reid Kleckner87a31802018-03-12 21:43:02 +00007963 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007964 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007965 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007966}
7967
Alexander Musmanf82886e2014-09-18 05:12:34 +00007968StmtResult Sema::ActOnOpenMPForSimdDirective(
7969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007970 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007971 if (!AStmt)
7972 return StmtError();
7973
7974 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007975 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007976 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7977 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007978 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007979 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007980 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7981 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007982 if (NestedLoopCount == 0)
7983 return StmtError();
7984
Alexander Musmanc6388682014-12-15 07:07:06 +00007985 assert((CurContext->isDependentContext() || B.builtAll()) &&
7986 "omp for simd loop exprs were not built");
7987
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007988 if (!CurContext->isDependentContext()) {
7989 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007990 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007991 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007993 B.NumIterations, *this, CurScope,
7994 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007995 return StmtError();
7996 }
7997 }
7998
Kelvin Lic5609492016-07-15 04:39:07 +00007999 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008000 return StmtError();
8001
Reid Kleckner87a31802018-03-12 21:43:02 +00008002 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008003 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8004 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008005}
8006
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008007StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8008 Stmt *AStmt,
8009 SourceLocation StartLoc,
8010 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008011 if (!AStmt)
8012 return StmtError();
8013
8014 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008015 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008016 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008017 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008018 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008019 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008020 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008021 return StmtError();
8022 // All associated statements must be '#pragma omp section' except for
8023 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008024 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008025 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8026 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008027 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008028 diag::err_omp_sections_substmt_not_section);
8029 return StmtError();
8030 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008031 cast<OMPSectionDirective>(SectionStmt)
8032 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008033 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008034 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008035 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008036 return StmtError();
8037 }
8038
Reid Kleckner87a31802018-03-12 21:43:02 +00008039 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008040
Alexey Bataev25e5b442015-09-15 12:52:43 +00008041 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8042 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008043}
8044
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008045StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8046 SourceLocation StartLoc,
8047 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008048 if (!AStmt)
8049 return StmtError();
8050
8051 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008052
Reid Kleckner87a31802018-03-12 21:43:02 +00008053 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008054 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008055
Alexey Bataev25e5b442015-09-15 12:52:43 +00008056 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8057 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008058}
8059
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008060StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8061 Stmt *AStmt,
8062 SourceLocation StartLoc,
8063 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008064 if (!AStmt)
8065 return StmtError();
8066
8067 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008068
Reid Kleckner87a31802018-03-12 21:43:02 +00008069 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008070
Alexey Bataev3255bf32015-01-19 05:20:46 +00008071 // OpenMP [2.7.3, single Construct, Restrictions]
8072 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008073 const OMPClause *Nowait = nullptr;
8074 const OMPClause *Copyprivate = nullptr;
8075 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008076 if (Clause->getClauseKind() == OMPC_nowait)
8077 Nowait = Clause;
8078 else if (Clause->getClauseKind() == OMPC_copyprivate)
8079 Copyprivate = Clause;
8080 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008081 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008082 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008083 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008084 return StmtError();
8085 }
8086 }
8087
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008088 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8089}
8090
Alexander Musman80c22892014-07-17 08:54:58 +00008091StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8092 SourceLocation StartLoc,
8093 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008094 if (!AStmt)
8095 return StmtError();
8096
8097 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008098
Reid Kleckner87a31802018-03-12 21:43:02 +00008099 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008100
8101 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8102}
8103
Alexey Bataev28c75412015-12-15 08:19:24 +00008104StmtResult Sema::ActOnOpenMPCriticalDirective(
8105 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8106 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008107 if (!AStmt)
8108 return StmtError();
8109
8110 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008111
Alexey Bataev28c75412015-12-15 08:19:24 +00008112 bool ErrorFound = false;
8113 llvm::APSInt Hint;
8114 SourceLocation HintLoc;
8115 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008116 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008117 if (C->getClauseKind() == OMPC_hint) {
8118 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008119 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008120 ErrorFound = true;
8121 }
8122 Expr *E = cast<OMPHintClause>(C)->getHint();
8123 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008124 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008125 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008126 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008127 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008128 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008129 }
8130 }
8131 }
8132 if (ErrorFound)
8133 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008134 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008135 if (Pair.first && DirName.getName() && !DependentHint) {
8136 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8137 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008138 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008139 Diag(HintLoc, diag::note_omp_critical_hint_here)
8140 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008141 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008142 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008143 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008144 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008145 << 1
8146 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8147 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008148 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008149 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008150 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008151 }
8152 }
8153
Reid Kleckner87a31802018-03-12 21:43:02 +00008154 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008155
Alexey Bataev28c75412015-12-15 08:19:24 +00008156 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8157 Clauses, AStmt);
8158 if (!Pair.first && DirName.getName() && !DependentHint)
8159 DSAStack->addCriticalWithHint(Dir, Hint);
8160 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008161}
8162
Alexey Bataev4acb8592014-07-07 13:01:15 +00008163StmtResult Sema::ActOnOpenMPParallelForDirective(
8164 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008165 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008166 if (!AStmt)
8167 return StmtError();
8168
Alexey Bataeve3727102018-04-18 15:57:46 +00008169 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008170 // 1.2.2 OpenMP Language Terminology
8171 // Structured block - An executable statement with a single entry at the
8172 // top and a single exit at the bottom.
8173 // The point of exit cannot be a branch out of the structured block.
8174 // longjmp() and throw() must not violate the entry/exit criteria.
8175 CS->getCapturedDecl()->setNothrow();
8176
Alexander Musmanc6388682014-12-15 07:07:06 +00008177 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008178 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8179 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008180 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008181 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008182 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8183 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008184 if (NestedLoopCount == 0)
8185 return StmtError();
8186
Alexander Musmana5f070a2014-10-01 06:03:56 +00008187 assert((CurContext->isDependentContext() || B.builtAll()) &&
8188 "omp parallel for loop exprs were not built");
8189
Alexey Bataev54acd402015-08-04 11:18:19 +00008190 if (!CurContext->isDependentContext()) {
8191 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008192 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008193 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008194 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008195 B.NumIterations, *this, CurScope,
8196 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008197 return StmtError();
8198 }
8199 }
8200
Reid Kleckner87a31802018-03-12 21:43:02 +00008201 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008202 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008203 NestedLoopCount, Clauses, AStmt, B,
8204 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008205}
8206
Alexander Musmane4e893b2014-09-23 09:33:00 +00008207StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8208 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008209 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008210 if (!AStmt)
8211 return StmtError();
8212
Alexey Bataeve3727102018-04-18 15:57:46 +00008213 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008214 // 1.2.2 OpenMP Language Terminology
8215 // Structured block - An executable statement with a single entry at the
8216 // top and a single exit at the bottom.
8217 // The point of exit cannot be a branch out of the structured block.
8218 // longjmp() and throw() must not violate the entry/exit criteria.
8219 CS->getCapturedDecl()->setNothrow();
8220
Alexander Musmanc6388682014-12-15 07:07:06 +00008221 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008222 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8223 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008224 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008225 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008226 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8227 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008228 if (NestedLoopCount == 0)
8229 return StmtError();
8230
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008231 if (!CurContext->isDependentContext()) {
8232 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008233 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008234 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008235 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008236 B.NumIterations, *this, CurScope,
8237 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008238 return StmtError();
8239 }
8240 }
8241
Kelvin Lic5609492016-07-15 04:39:07 +00008242 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008243 return StmtError();
8244
Reid Kleckner87a31802018-03-12 21:43:02 +00008245 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008246 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008247 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008248}
8249
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008250StmtResult
8251Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8252 Stmt *AStmt, SourceLocation StartLoc,
8253 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008254 if (!AStmt)
8255 return StmtError();
8256
8257 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008258 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008259 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008260 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008261 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008262 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008263 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008264 return StmtError();
8265 // All associated statements must be '#pragma omp section' except for
8266 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008267 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008268 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8269 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008270 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008271 diag::err_omp_parallel_sections_substmt_not_section);
8272 return StmtError();
8273 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008274 cast<OMPSectionDirective>(SectionStmt)
8275 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008276 }
8277 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008278 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008279 diag::err_omp_parallel_sections_not_compound_stmt);
8280 return StmtError();
8281 }
8282
Reid Kleckner87a31802018-03-12 21:43:02 +00008283 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008284
Alexey Bataev25e5b442015-09-15 12:52:43 +00008285 return OMPParallelSectionsDirective::Create(
8286 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008287}
8288
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008289StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8290 Stmt *AStmt, SourceLocation StartLoc,
8291 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008292 if (!AStmt)
8293 return StmtError();
8294
David Majnemer9d168222016-08-05 17:44:54 +00008295 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008296 // 1.2.2 OpenMP Language Terminology
8297 // Structured block - An executable statement with a single entry at the
8298 // top and a single exit at the bottom.
8299 // The point of exit cannot be a branch out of the structured block.
8300 // longjmp() and throw() must not violate the entry/exit criteria.
8301 CS->getCapturedDecl()->setNothrow();
8302
Reid Kleckner87a31802018-03-12 21:43:02 +00008303 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008304
Alexey Bataev25e5b442015-09-15 12:52:43 +00008305 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8306 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008307}
8308
Alexey Bataev68446b72014-07-18 07:47:19 +00008309StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8310 SourceLocation EndLoc) {
8311 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8312}
8313
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008314StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8315 SourceLocation EndLoc) {
8316 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8317}
8318
Alexey Bataev2df347a2014-07-18 10:17:07 +00008319StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8320 SourceLocation EndLoc) {
8321 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8322}
8323
Alexey Bataev169d96a2017-07-18 20:17:46 +00008324StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8325 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008326 SourceLocation StartLoc,
8327 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008328 if (!AStmt)
8329 return StmtError();
8330
8331 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008332
Reid Kleckner87a31802018-03-12 21:43:02 +00008333 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008334
Alexey Bataev169d96a2017-07-18 20:17:46 +00008335 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008336 AStmt,
8337 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008338}
8339
Alexey Bataev6125da92014-07-21 11:26:11 +00008340StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8341 SourceLocation StartLoc,
8342 SourceLocation EndLoc) {
8343 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8344 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8345}
8346
Alexey Bataev346265e2015-09-25 10:37:12 +00008347StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8348 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008349 SourceLocation StartLoc,
8350 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008351 const OMPClause *DependFound = nullptr;
8352 const OMPClause *DependSourceClause = nullptr;
8353 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008354 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008355 const OMPThreadsClause *TC = nullptr;
8356 const OMPSIMDClause *SC = nullptr;
8357 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008358 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8359 DependFound = C;
8360 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8361 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008362 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008363 << getOpenMPDirectiveName(OMPD_ordered)
8364 << getOpenMPClauseName(OMPC_depend) << 2;
8365 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008366 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008367 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008368 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008369 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008370 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008371 << 0;
8372 ErrorFound = true;
8373 }
8374 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8375 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008376 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008377 << 1;
8378 ErrorFound = true;
8379 }
8380 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008381 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008382 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008383 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008385 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008386 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008387 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008388 if (!ErrorFound && !SC &&
8389 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008390 // OpenMP [2.8.1,simd Construct, Restrictions]
8391 // An ordered construct with the simd clause is the only OpenMP construct
8392 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008393 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8394 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008395 ErrorFound = true;
8396 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008397 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008398 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8399 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008400 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008401 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008402 diag::err_omp_ordered_directive_without_param);
8403 ErrorFound = true;
8404 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008405 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008406 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008407 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8408 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008409 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008410 ErrorFound = true;
8411 }
8412 }
8413 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008414 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008415
8416 if (AStmt) {
8417 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8418
Reid Kleckner87a31802018-03-12 21:43:02 +00008419 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008420 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008421
8422 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008423}
8424
Alexey Bataev1d160b12015-03-13 12:27:31 +00008425namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008426/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008427/// construct.
8428class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008429 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008430 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008431 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008432 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008433 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008434 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008435 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008436 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008437 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008438 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008439 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008440 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008441 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008442 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008443 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008444 /// expression.
8445 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008446 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008447 /// part.
8448 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008449 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008450 NoError
8451 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008452 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008453 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008454 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008455 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008456 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008457 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008458 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008459 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008460 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008461 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8462 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8463 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008464 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008465 /// important for non-associative operations.
8466 bool IsXLHSInRHSPart;
8467 BinaryOperatorKind Op;
8468 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008469 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008470 /// if it is a prefix unary operation.
8471 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008472
8473public:
8474 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008475 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008476 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008477 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008478 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008479 /// expression. If DiagId and NoteId == 0, then only check is performed
8480 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008481 /// \param DiagId Diagnostic which should be emitted if error is found.
8482 /// \param NoteId Diagnostic note for the main error message.
8483 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008484 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008485 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008486 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008487 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008488 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008489 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008490 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8491 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8492 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008493 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008494 /// false otherwise.
8495 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8496
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008497 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008498 /// if it is a prefix unary operation.
8499 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8500
Alexey Bataev1d160b12015-03-13 12:27:31 +00008501private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008502 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8503 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008504};
8505} // namespace
8506
8507bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8508 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8509 ExprAnalysisErrorCode ErrorFound = NoError;
8510 SourceLocation ErrorLoc, NoteLoc;
8511 SourceRange ErrorRange, NoteRange;
8512 // Allowed constructs are:
8513 // x = x binop expr;
8514 // x = expr binop x;
8515 if (AtomicBinOp->getOpcode() == BO_Assign) {
8516 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008517 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008518 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8519 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8520 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8521 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008522 Op = AtomicInnerBinOp->getOpcode();
8523 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008524 Expr *LHS = AtomicInnerBinOp->getLHS();
8525 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008526 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8527 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8528 /*Canonical=*/true);
8529 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8530 /*Canonical=*/true);
8531 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8532 /*Canonical=*/true);
8533 if (XId == LHSId) {
8534 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008535 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008536 } else if (XId == RHSId) {
8537 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008538 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008539 } else {
8540 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8541 ErrorRange = AtomicInnerBinOp->getSourceRange();
8542 NoteLoc = X->getExprLoc();
8543 NoteRange = X->getSourceRange();
8544 ErrorFound = NotAnUpdateExpression;
8545 }
8546 } else {
8547 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8548 ErrorRange = AtomicInnerBinOp->getSourceRange();
8549 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8550 NoteRange = SourceRange(NoteLoc, NoteLoc);
8551 ErrorFound = NotABinaryOperator;
8552 }
8553 } else {
8554 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8555 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8556 ErrorFound = NotABinaryExpression;
8557 }
8558 } else {
8559 ErrorLoc = AtomicBinOp->getExprLoc();
8560 ErrorRange = AtomicBinOp->getSourceRange();
8561 NoteLoc = AtomicBinOp->getOperatorLoc();
8562 NoteRange = SourceRange(NoteLoc, NoteLoc);
8563 ErrorFound = NotAnAssignmentOp;
8564 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008565 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008566 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8567 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8568 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008569 }
8570 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008571 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008572 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008573}
8574
8575bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8576 unsigned NoteId) {
8577 ExprAnalysisErrorCode ErrorFound = NoError;
8578 SourceLocation ErrorLoc, NoteLoc;
8579 SourceRange ErrorRange, NoteRange;
8580 // Allowed constructs are:
8581 // x++;
8582 // x--;
8583 // ++x;
8584 // --x;
8585 // x binop= expr;
8586 // x = x binop expr;
8587 // x = expr binop x;
8588 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8589 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8590 if (AtomicBody->getType()->isScalarType() ||
8591 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008592 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008593 AtomicBody->IgnoreParenImpCasts())) {
8594 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008595 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008596 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008597 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008598 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008599 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008600 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008601 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8602 AtomicBody->IgnoreParenImpCasts())) {
8603 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008604 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008605 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008606 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008607 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008608 // Check for Unary Operation
8609 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008610 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008611 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8612 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008613 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008614 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8615 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008616 } else {
8617 ErrorFound = NotAnUnaryIncDecExpression;
8618 ErrorLoc = AtomicUnaryOp->getExprLoc();
8619 ErrorRange = AtomicUnaryOp->getSourceRange();
8620 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8621 NoteRange = SourceRange(NoteLoc, NoteLoc);
8622 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008623 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008624 ErrorFound = NotABinaryOrUnaryExpression;
8625 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8626 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8627 }
8628 } else {
8629 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008630 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008631 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8632 }
8633 } else {
8634 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008635 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008636 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8637 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008638 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008639 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8640 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8641 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008642 }
8643 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008644 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008645 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008646 // Build an update expression of form 'OpaqueValueExpr(x) binop
8647 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8648 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8649 auto *OVEX = new (SemaRef.getASTContext())
8650 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8651 auto *OVEExpr = new (SemaRef.getASTContext())
8652 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008653 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008654 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8655 IsXLHSInRHSPart ? OVEExpr : OVEX);
8656 if (Update.isInvalid())
8657 return true;
8658 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8659 Sema::AA_Casting);
8660 if (Update.isInvalid())
8661 return true;
8662 UpdateExpr = Update.get();
8663 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008664 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008665}
8666
Alexey Bataev0162e452014-07-22 10:10:35 +00008667StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8668 Stmt *AStmt,
8669 SourceLocation StartLoc,
8670 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008671 if (!AStmt)
8672 return StmtError();
8673
David Majnemer9d168222016-08-05 17:44:54 +00008674 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008675 // 1.2.2 OpenMP Language Terminology
8676 // Structured block - An executable statement with a single entry at the
8677 // top and a single exit at the bottom.
8678 // The point of exit cannot be a branch out of the structured block.
8679 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008680 OpenMPClauseKind AtomicKind = OMPC_unknown;
8681 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008682 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008683 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008684 C->getClauseKind() == OMPC_update ||
8685 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008686 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008687 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008688 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008689 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8690 << getOpenMPClauseName(AtomicKind);
8691 } else {
8692 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008693 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008694 }
8695 }
8696 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008697
Alexey Bataeve3727102018-04-18 15:57:46 +00008698 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008699 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8700 Body = EWC->getSubExpr();
8701
Alexey Bataev62cec442014-11-18 10:14:22 +00008702 Expr *X = nullptr;
8703 Expr *V = nullptr;
8704 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008705 Expr *UE = nullptr;
8706 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008707 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008708 // OpenMP [2.12.6, atomic Construct]
8709 // In the next expressions:
8710 // * x and v (as applicable) are both l-value expressions with scalar type.
8711 // * During the execution of an atomic region, multiple syntactic
8712 // occurrences of x must designate the same storage location.
8713 // * Neither of v and expr (as applicable) may access the storage location
8714 // designated by x.
8715 // * Neither of x and expr (as applicable) may access the storage location
8716 // designated by v.
8717 // * expr is an expression with scalar type.
8718 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8719 // * binop, binop=, ++, and -- are not overloaded operators.
8720 // * The expression x binop expr must be numerically equivalent to x binop
8721 // (expr). This requirement is satisfied if the operators in expr have
8722 // precedence greater than binop, or by using parentheses around expr or
8723 // subexpressions of expr.
8724 // * The expression expr binop x must be numerically equivalent to (expr)
8725 // binop x. This requirement is satisfied if the operators in expr have
8726 // precedence equal to or greater than binop, or by using parentheses around
8727 // expr or subexpressions of expr.
8728 // * For forms that allow multiple occurrences of x, the number of times
8729 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008730 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008731 enum {
8732 NotAnExpression,
8733 NotAnAssignmentOp,
8734 NotAScalarType,
8735 NotAnLValue,
8736 NoError
8737 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008738 SourceLocation ErrorLoc, NoteLoc;
8739 SourceRange ErrorRange, NoteRange;
8740 // If clause is read:
8741 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008742 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8743 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008744 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8745 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8746 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8747 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8748 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8749 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8750 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008751 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008752 ErrorFound = NotAnLValue;
8753 ErrorLoc = AtomicBinOp->getExprLoc();
8754 ErrorRange = AtomicBinOp->getSourceRange();
8755 NoteLoc = NotLValueExpr->getExprLoc();
8756 NoteRange = NotLValueExpr->getSourceRange();
8757 }
8758 } else if (!X->isInstantiationDependent() ||
8759 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008760 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008761 (X->isInstantiationDependent() || X->getType()->isScalarType())
8762 ? V
8763 : X;
8764 ErrorFound = NotAScalarType;
8765 ErrorLoc = AtomicBinOp->getExprLoc();
8766 ErrorRange = AtomicBinOp->getSourceRange();
8767 NoteLoc = NotScalarExpr->getExprLoc();
8768 NoteRange = NotScalarExpr->getSourceRange();
8769 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008770 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008771 ErrorFound = NotAnAssignmentOp;
8772 ErrorLoc = AtomicBody->getExprLoc();
8773 ErrorRange = AtomicBody->getSourceRange();
8774 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8775 : AtomicBody->getExprLoc();
8776 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8777 : AtomicBody->getSourceRange();
8778 }
8779 } else {
8780 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008781 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008782 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008783 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008784 if (ErrorFound != NoError) {
8785 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8786 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008787 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8788 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008789 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008790 }
8791 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008792 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008793 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008794 enum {
8795 NotAnExpression,
8796 NotAnAssignmentOp,
8797 NotAScalarType,
8798 NotAnLValue,
8799 NoError
8800 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008801 SourceLocation ErrorLoc, NoteLoc;
8802 SourceRange ErrorRange, NoteRange;
8803 // If clause is write:
8804 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008805 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8806 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008807 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8808 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008809 X = AtomicBinOp->getLHS();
8810 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008811 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8812 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8813 if (!X->isLValue()) {
8814 ErrorFound = NotAnLValue;
8815 ErrorLoc = AtomicBinOp->getExprLoc();
8816 ErrorRange = AtomicBinOp->getSourceRange();
8817 NoteLoc = X->getExprLoc();
8818 NoteRange = X->getSourceRange();
8819 }
8820 } else if (!X->isInstantiationDependent() ||
8821 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008822 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008823 (X->isInstantiationDependent() || X->getType()->isScalarType())
8824 ? E
8825 : X;
8826 ErrorFound = NotAScalarType;
8827 ErrorLoc = AtomicBinOp->getExprLoc();
8828 ErrorRange = AtomicBinOp->getSourceRange();
8829 NoteLoc = NotScalarExpr->getExprLoc();
8830 NoteRange = NotScalarExpr->getSourceRange();
8831 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008832 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008833 ErrorFound = NotAnAssignmentOp;
8834 ErrorLoc = AtomicBody->getExprLoc();
8835 ErrorRange = AtomicBody->getSourceRange();
8836 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8837 : AtomicBody->getExprLoc();
8838 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8839 : AtomicBody->getSourceRange();
8840 }
8841 } else {
8842 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008843 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008844 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008845 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008846 if (ErrorFound != NoError) {
8847 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8848 << ErrorRange;
8849 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8850 << NoteRange;
8851 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008852 }
8853 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008854 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008855 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008856 // If clause is update:
8857 // x++;
8858 // x--;
8859 // ++x;
8860 // --x;
8861 // x binop= expr;
8862 // x = x binop expr;
8863 // x = expr binop x;
8864 OpenMPAtomicUpdateChecker Checker(*this);
8865 if (Checker.checkStatement(
8866 Body, (AtomicKind == OMPC_update)
8867 ? diag::err_omp_atomic_update_not_expression_statement
8868 : diag::err_omp_atomic_not_expression_statement,
8869 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008870 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008871 if (!CurContext->isDependentContext()) {
8872 E = Checker.getExpr();
8873 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008874 UE = Checker.getUpdateExpr();
8875 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008876 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008877 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008878 enum {
8879 NotAnAssignmentOp,
8880 NotACompoundStatement,
8881 NotTwoSubstatements,
8882 NotASpecificExpression,
8883 NoError
8884 } ErrorFound = NoError;
8885 SourceLocation ErrorLoc, NoteLoc;
8886 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008887 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008888 // If clause is a capture:
8889 // v = x++;
8890 // v = x--;
8891 // v = ++x;
8892 // v = --x;
8893 // v = x binop= expr;
8894 // v = x = x binop expr;
8895 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008896 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008897 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8898 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8899 V = AtomicBinOp->getLHS();
8900 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8901 OpenMPAtomicUpdateChecker Checker(*this);
8902 if (Checker.checkStatement(
8903 Body, diag::err_omp_atomic_capture_not_expression_statement,
8904 diag::note_omp_atomic_update))
8905 return StmtError();
8906 E = Checker.getExpr();
8907 X = Checker.getX();
8908 UE = Checker.getUpdateExpr();
8909 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8910 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008911 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008912 ErrorLoc = AtomicBody->getExprLoc();
8913 ErrorRange = AtomicBody->getSourceRange();
8914 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8915 : AtomicBody->getExprLoc();
8916 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8917 : AtomicBody->getSourceRange();
8918 ErrorFound = NotAnAssignmentOp;
8919 }
8920 if (ErrorFound != NoError) {
8921 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8922 << ErrorRange;
8923 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8924 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008925 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008926 if (CurContext->isDependentContext())
8927 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008928 } else {
8929 // If clause is a capture:
8930 // { v = x; x = expr; }
8931 // { v = x; x++; }
8932 // { v = x; x--; }
8933 // { v = x; ++x; }
8934 // { v = x; --x; }
8935 // { v = x; x binop= expr; }
8936 // { v = x; x = x binop expr; }
8937 // { v = x; x = expr binop x; }
8938 // { x++; v = x; }
8939 // { x--; v = x; }
8940 // { ++x; v = x; }
8941 // { --x; v = x; }
8942 // { x binop= expr; v = x; }
8943 // { x = x binop expr; v = x; }
8944 // { x = expr binop x; v = x; }
8945 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8946 // Check that this is { expr1; expr2; }
8947 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008948 Stmt *First = CS->body_front();
8949 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008950 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8951 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8952 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8953 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8954 // Need to find what subexpression is 'v' and what is 'x'.
8955 OpenMPAtomicUpdateChecker Checker(*this);
8956 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8957 BinaryOperator *BinOp = nullptr;
8958 if (IsUpdateExprFound) {
8959 BinOp = dyn_cast<BinaryOperator>(First);
8960 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8961 }
8962 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8963 // { v = x; x++; }
8964 // { v = x; x--; }
8965 // { v = x; ++x; }
8966 // { v = x; --x; }
8967 // { v = x; x binop= expr; }
8968 // { v = x; x = x binop expr; }
8969 // { v = x; x = expr binop x; }
8970 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008971 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008972 llvm::FoldingSetNodeID XId, PossibleXId;
8973 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8974 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8975 IsUpdateExprFound = XId == PossibleXId;
8976 if (IsUpdateExprFound) {
8977 V = BinOp->getLHS();
8978 X = Checker.getX();
8979 E = Checker.getExpr();
8980 UE = Checker.getUpdateExpr();
8981 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008982 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008983 }
8984 }
8985 if (!IsUpdateExprFound) {
8986 IsUpdateExprFound = !Checker.checkStatement(First);
8987 BinOp = nullptr;
8988 if (IsUpdateExprFound) {
8989 BinOp = dyn_cast<BinaryOperator>(Second);
8990 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8991 }
8992 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8993 // { x++; v = x; }
8994 // { x--; v = x; }
8995 // { ++x; v = x; }
8996 // { --x; v = x; }
8997 // { x binop= expr; v = x; }
8998 // { x = x binop expr; v = x; }
8999 // { x = expr binop x; v = x; }
9000 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009001 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009002 llvm::FoldingSetNodeID XId, PossibleXId;
9003 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9004 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9005 IsUpdateExprFound = XId == PossibleXId;
9006 if (IsUpdateExprFound) {
9007 V = BinOp->getLHS();
9008 X = Checker.getX();
9009 E = Checker.getExpr();
9010 UE = Checker.getUpdateExpr();
9011 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009012 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009013 }
9014 }
9015 }
9016 if (!IsUpdateExprFound) {
9017 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009018 auto *FirstExpr = dyn_cast<Expr>(First);
9019 auto *SecondExpr = dyn_cast<Expr>(Second);
9020 if (!FirstExpr || !SecondExpr ||
9021 !(FirstExpr->isInstantiationDependent() ||
9022 SecondExpr->isInstantiationDependent())) {
9023 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9024 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009025 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009026 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009027 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009028 NoteRange = ErrorRange = FirstBinOp
9029 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009030 : SourceRange(ErrorLoc, ErrorLoc);
9031 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009032 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9033 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9034 ErrorFound = NotAnAssignmentOp;
9035 NoteLoc = ErrorLoc = SecondBinOp
9036 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009037 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009038 NoteRange = ErrorRange =
9039 SecondBinOp ? SecondBinOp->getSourceRange()
9040 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009041 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009042 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009043 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009044 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009045 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9046 llvm::FoldingSetNodeID X1Id, X2Id;
9047 PossibleXRHSInFirst->Profile(X1Id, Context,
9048 /*Canonical=*/true);
9049 PossibleXLHSInSecond->Profile(X2Id, Context,
9050 /*Canonical=*/true);
9051 IsUpdateExprFound = X1Id == X2Id;
9052 if (IsUpdateExprFound) {
9053 V = FirstBinOp->getLHS();
9054 X = SecondBinOp->getLHS();
9055 E = SecondBinOp->getRHS();
9056 UE = nullptr;
9057 IsXLHSInRHSPart = false;
9058 IsPostfixUpdate = true;
9059 } else {
9060 ErrorFound = NotASpecificExpression;
9061 ErrorLoc = FirstBinOp->getExprLoc();
9062 ErrorRange = FirstBinOp->getSourceRange();
9063 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9064 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9065 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009066 }
9067 }
9068 }
9069 }
9070 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009071 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009072 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009073 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009074 ErrorFound = NotTwoSubstatements;
9075 }
9076 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009077 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009078 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009079 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009080 ErrorFound = NotACompoundStatement;
9081 }
9082 if (ErrorFound != NoError) {
9083 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9084 << ErrorRange;
9085 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9086 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009087 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009088 if (CurContext->isDependentContext())
9089 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009090 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009091 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009092
Reid Kleckner87a31802018-03-12 21:43:02 +00009093 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009094
Alexey Bataev62cec442014-11-18 10:14:22 +00009095 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009096 X, V, E, UE, IsXLHSInRHSPart,
9097 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009098}
9099
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009100StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9101 Stmt *AStmt,
9102 SourceLocation StartLoc,
9103 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009104 if (!AStmt)
9105 return StmtError();
9106
Alexey Bataeve3727102018-04-18 15:57:46 +00009107 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009108 // 1.2.2 OpenMP Language Terminology
9109 // Structured block - An executable statement with a single entry at the
9110 // top and a single exit at the bottom.
9111 // The point of exit cannot be a branch out of the structured block.
9112 // longjmp() and throw() must not violate the entry/exit criteria.
9113 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009114 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9115 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9116 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9117 // 1.2.2 OpenMP Language Terminology
9118 // Structured block - An executable statement with a single entry at the
9119 // top and a single exit at the bottom.
9120 // The point of exit cannot be a branch out of the structured block.
9121 // longjmp() and throw() must not violate the entry/exit criteria.
9122 CS->getCapturedDecl()->setNothrow();
9123 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009124
Alexey Bataev13314bf2014-10-09 04:18:56 +00009125 // OpenMP [2.16, Nesting of Regions]
9126 // If specified, a teams construct must be contained within a target
9127 // construct. That target construct must contain no statements or directives
9128 // outside of the teams construct.
9129 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009130 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009131 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009132 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009133 auto I = CS->body_begin();
9134 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009135 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009136 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9137 OMPTeamsFound) {
9138
Alexey Bataev13314bf2014-10-09 04:18:56 +00009139 OMPTeamsFound = false;
9140 break;
9141 }
9142 ++I;
9143 }
9144 assert(I != CS->body_end() && "Not found statement");
9145 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009146 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009147 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009148 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009149 }
9150 if (!OMPTeamsFound) {
9151 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9152 Diag(DSAStack->getInnerTeamsRegionLoc(),
9153 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009154 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009155 << isa<OMPExecutableDirective>(S);
9156 return StmtError();
9157 }
9158 }
9159
Reid Kleckner87a31802018-03-12 21:43:02 +00009160 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009161
9162 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9163}
9164
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009165StmtResult
9166Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9167 Stmt *AStmt, SourceLocation StartLoc,
9168 SourceLocation EndLoc) {
9169 if (!AStmt)
9170 return StmtError();
9171
Alexey Bataeve3727102018-04-18 15:57:46 +00009172 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009173 // 1.2.2 OpenMP Language Terminology
9174 // Structured block - An executable statement with a single entry at the
9175 // top and a single exit at the bottom.
9176 // The point of exit cannot be a branch out of the structured block.
9177 // longjmp() and throw() must not violate the entry/exit criteria.
9178 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009179 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9180 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9181 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9182 // 1.2.2 OpenMP Language Terminology
9183 // Structured block - An executable statement with a single entry at the
9184 // top and a single exit at the bottom.
9185 // The point of exit cannot be a branch out of the structured block.
9186 // longjmp() and throw() must not violate the entry/exit criteria.
9187 CS->getCapturedDecl()->setNothrow();
9188 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009189
Reid Kleckner87a31802018-03-12 21:43:02 +00009190 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009191
9192 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9193 AStmt);
9194}
9195
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009196StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9197 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009198 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009199 if (!AStmt)
9200 return StmtError();
9201
Alexey Bataeve3727102018-04-18 15:57:46 +00009202 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009203 // 1.2.2 OpenMP Language Terminology
9204 // Structured block - An executable statement with a single entry at the
9205 // top and a single exit at the bottom.
9206 // The point of exit cannot be a branch out of the structured block.
9207 // longjmp() and throw() must not violate the entry/exit criteria.
9208 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009209 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9210 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9211 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9212 // 1.2.2 OpenMP Language Terminology
9213 // Structured block - An executable statement with a single entry at the
9214 // top and a single exit at the bottom.
9215 // The point of exit cannot be a branch out of the structured block.
9216 // longjmp() and throw() must not violate the entry/exit criteria.
9217 CS->getCapturedDecl()->setNothrow();
9218 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009219
9220 OMPLoopDirective::HelperExprs B;
9221 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9222 // define the nested loops number.
9223 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009224 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009225 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009226 VarsWithImplicitDSA, B);
9227 if (NestedLoopCount == 0)
9228 return StmtError();
9229
9230 assert((CurContext->isDependentContext() || B.builtAll()) &&
9231 "omp target parallel for loop exprs were not built");
9232
9233 if (!CurContext->isDependentContext()) {
9234 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009235 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009236 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009237 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009238 B.NumIterations, *this, CurScope,
9239 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009240 return StmtError();
9241 }
9242 }
9243
Reid Kleckner87a31802018-03-12 21:43:02 +00009244 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009245 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9246 NestedLoopCount, Clauses, AStmt,
9247 B, DSAStack->isCancelRegion());
9248}
9249
Alexey Bataev95b64a92017-05-30 16:00:04 +00009250/// Check for existence of a map clause in the list of clauses.
9251static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9252 const OpenMPClauseKind K) {
9253 return llvm::any_of(
9254 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9255}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009256
Alexey Bataev95b64a92017-05-30 16:00:04 +00009257template <typename... Params>
9258static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9259 const Params... ClauseTypes) {
9260 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009261}
9262
Michael Wong65f367f2015-07-21 13:44:28 +00009263StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9264 Stmt *AStmt,
9265 SourceLocation StartLoc,
9266 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009267 if (!AStmt)
9268 return StmtError();
9269
9270 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9271
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009272 // OpenMP [2.10.1, Restrictions, p. 97]
9273 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009274 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9275 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9276 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009277 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009278 return StmtError();
9279 }
9280
Reid Kleckner87a31802018-03-12 21:43:02 +00009281 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009282
9283 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9284 AStmt);
9285}
9286
Samuel Antaodf67fc42016-01-19 19:15:56 +00009287StmtResult
9288Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9289 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009290 SourceLocation EndLoc, Stmt *AStmt) {
9291 if (!AStmt)
9292 return StmtError();
9293
Alexey Bataeve3727102018-04-18 15:57:46 +00009294 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009295 // 1.2.2 OpenMP Language Terminology
9296 // Structured block - An executable statement with a single entry at the
9297 // top and a single exit at the bottom.
9298 // The point of exit cannot be a branch out of the structured block.
9299 // longjmp() and throw() must not violate the entry/exit criteria.
9300 CS->getCapturedDecl()->setNothrow();
9301 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9302 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9303 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9304 // 1.2.2 OpenMP Language Terminology
9305 // Structured block - An executable statement with a single entry at the
9306 // top and a single exit at the bottom.
9307 // The point of exit cannot be a branch out of the structured block.
9308 // longjmp() and throw() must not violate the entry/exit criteria.
9309 CS->getCapturedDecl()->setNothrow();
9310 }
9311
Samuel Antaodf67fc42016-01-19 19:15:56 +00009312 // OpenMP [2.10.2, Restrictions, p. 99]
9313 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009314 if (!hasClauses(Clauses, OMPC_map)) {
9315 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9316 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009317 return StmtError();
9318 }
9319
Alexey Bataev7828b252017-11-21 17:08:48 +00009320 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9321 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009322}
9323
Samuel Antao72590762016-01-19 20:04:50 +00009324StmtResult
9325Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9326 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009327 SourceLocation EndLoc, Stmt *AStmt) {
9328 if (!AStmt)
9329 return StmtError();
9330
Alexey Bataeve3727102018-04-18 15:57:46 +00009331 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009332 // 1.2.2 OpenMP Language Terminology
9333 // Structured block - An executable statement with a single entry at the
9334 // top and a single exit at the bottom.
9335 // The point of exit cannot be a branch out of the structured block.
9336 // longjmp() and throw() must not violate the entry/exit criteria.
9337 CS->getCapturedDecl()->setNothrow();
9338 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9339 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9340 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9341 // 1.2.2 OpenMP Language Terminology
9342 // Structured block - An executable statement with a single entry at the
9343 // top and a single exit at the bottom.
9344 // The point of exit cannot be a branch out of the structured block.
9345 // longjmp() and throw() must not violate the entry/exit criteria.
9346 CS->getCapturedDecl()->setNothrow();
9347 }
9348
Samuel Antao72590762016-01-19 20:04:50 +00009349 // OpenMP [2.10.3, Restrictions, p. 102]
9350 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009351 if (!hasClauses(Clauses, OMPC_map)) {
9352 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9353 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009354 return StmtError();
9355 }
9356
Alexey Bataev7828b252017-11-21 17:08:48 +00009357 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9358 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009359}
9360
Samuel Antao686c70c2016-05-26 17:30:50 +00009361StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9362 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009363 SourceLocation EndLoc,
9364 Stmt *AStmt) {
9365 if (!AStmt)
9366 return StmtError();
9367
Alexey Bataeve3727102018-04-18 15:57:46 +00009368 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009369 // 1.2.2 OpenMP Language Terminology
9370 // Structured block - An executable statement with a single entry at the
9371 // top and a single exit at the bottom.
9372 // The point of exit cannot be a branch out of the structured block.
9373 // longjmp() and throw() must not violate the entry/exit criteria.
9374 CS->getCapturedDecl()->setNothrow();
9375 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9376 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9377 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9378 // 1.2.2 OpenMP Language Terminology
9379 // Structured block - An executable statement with a single entry at the
9380 // top and a single exit at the bottom.
9381 // The point of exit cannot be a branch out of the structured block.
9382 // longjmp() and throw() must not violate the entry/exit criteria.
9383 CS->getCapturedDecl()->setNothrow();
9384 }
9385
Alexey Bataev95b64a92017-05-30 16:00:04 +00009386 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009387 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9388 return StmtError();
9389 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009390 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9391 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009392}
9393
Alexey Bataev13314bf2014-10-09 04:18:56 +00009394StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9395 Stmt *AStmt, SourceLocation StartLoc,
9396 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009397 if (!AStmt)
9398 return StmtError();
9399
Alexey Bataeve3727102018-04-18 15:57:46 +00009400 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009401 // 1.2.2 OpenMP Language Terminology
9402 // Structured block - An executable statement with a single entry at the
9403 // top and a single exit at the bottom.
9404 // The point of exit cannot be a branch out of the structured block.
9405 // longjmp() and throw() must not violate the entry/exit criteria.
9406 CS->getCapturedDecl()->setNothrow();
9407
Reid Kleckner87a31802018-03-12 21:43:02 +00009408 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009409
Alexey Bataevceabd412017-11-30 18:01:54 +00009410 DSAStack->setParentTeamsRegionLoc(StartLoc);
9411
Alexey Bataev13314bf2014-10-09 04:18:56 +00009412 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9413}
9414
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009415StmtResult
9416Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9417 SourceLocation EndLoc,
9418 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009419 if (DSAStack->isParentNowaitRegion()) {
9420 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9421 return StmtError();
9422 }
9423 if (DSAStack->isParentOrderedRegion()) {
9424 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9425 return StmtError();
9426 }
9427 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9428 CancelRegion);
9429}
9430
Alexey Bataev87933c72015-09-18 08:07:34 +00009431StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9432 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009433 SourceLocation EndLoc,
9434 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009435 if (DSAStack->isParentNowaitRegion()) {
9436 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9437 return StmtError();
9438 }
9439 if (DSAStack->isParentOrderedRegion()) {
9440 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9441 return StmtError();
9442 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009443 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009444 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9445 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009446}
9447
Alexey Bataev382967a2015-12-08 12:06:20 +00009448static bool checkGrainsizeNumTasksClauses(Sema &S,
9449 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009450 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009451 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009452 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009453 if (C->getClauseKind() == OMPC_grainsize ||
9454 C->getClauseKind() == OMPC_num_tasks) {
9455 if (!PrevClause)
9456 PrevClause = C;
9457 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009458 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009459 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9460 << getOpenMPClauseName(C->getClauseKind())
9461 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009462 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009463 diag::note_omp_previous_grainsize_num_tasks)
9464 << getOpenMPClauseName(PrevClause->getClauseKind());
9465 ErrorFound = true;
9466 }
9467 }
9468 }
9469 return ErrorFound;
9470}
9471
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009472static bool checkReductionClauseWithNogroup(Sema &S,
9473 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009474 const OMPClause *ReductionClause = nullptr;
9475 const OMPClause *NogroupClause = nullptr;
9476 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009477 if (C->getClauseKind() == OMPC_reduction) {
9478 ReductionClause = C;
9479 if (NogroupClause)
9480 break;
9481 continue;
9482 }
9483 if (C->getClauseKind() == OMPC_nogroup) {
9484 NogroupClause = C;
9485 if (ReductionClause)
9486 break;
9487 continue;
9488 }
9489 }
9490 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009491 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9492 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009493 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009494 return true;
9495 }
9496 return false;
9497}
9498
Alexey Bataev49f6e782015-12-01 04:18:41 +00009499StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9500 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009501 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009502 if (!AStmt)
9503 return StmtError();
9504
9505 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9506 OMPLoopDirective::HelperExprs B;
9507 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9508 // define the nested loops number.
9509 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009510 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009511 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009512 VarsWithImplicitDSA, B);
9513 if (NestedLoopCount == 0)
9514 return StmtError();
9515
9516 assert((CurContext->isDependentContext() || B.builtAll()) &&
9517 "omp for loop exprs were not built");
9518
Alexey Bataev382967a2015-12-08 12:06:20 +00009519 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9520 // The grainsize clause and num_tasks clause are mutually exclusive and may
9521 // not appear on the same taskloop directive.
9522 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9523 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009524 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9525 // If a reduction clause is present on the taskloop directive, the nogroup
9526 // clause must not be specified.
9527 if (checkReductionClauseWithNogroup(*this, Clauses))
9528 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009529
Reid Kleckner87a31802018-03-12 21:43:02 +00009530 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009531 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9532 NestedLoopCount, Clauses, AStmt, B);
9533}
9534
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009535StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009537 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009538 if (!AStmt)
9539 return StmtError();
9540
9541 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9542 OMPLoopDirective::HelperExprs B;
9543 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9544 // define the nested loops number.
9545 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009546 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009547 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9548 VarsWithImplicitDSA, B);
9549 if (NestedLoopCount == 0)
9550 return StmtError();
9551
9552 assert((CurContext->isDependentContext() || B.builtAll()) &&
9553 "omp for loop exprs were not built");
9554
Alexey Bataev5a3af132016-03-29 08:58:54 +00009555 if (!CurContext->isDependentContext()) {
9556 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009557 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009558 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009559 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009560 B.NumIterations, *this, CurScope,
9561 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009562 return StmtError();
9563 }
9564 }
9565
Alexey Bataev382967a2015-12-08 12:06:20 +00009566 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9567 // The grainsize clause and num_tasks clause are mutually exclusive and may
9568 // not appear on the same taskloop directive.
9569 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9570 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009571 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9572 // If a reduction clause is present on the taskloop directive, the nogroup
9573 // clause must not be specified.
9574 if (checkReductionClauseWithNogroup(*this, Clauses))
9575 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009576 if (checkSimdlenSafelenSpecified(*this, Clauses))
9577 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009578
Reid Kleckner87a31802018-03-12 21:43:02 +00009579 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009580 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9581 NestedLoopCount, Clauses, AStmt, B);
9582}
9583
Alexey Bataev60e51c42019-10-10 20:13:02 +00009584StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9585 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9586 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9587 if (!AStmt)
9588 return StmtError();
9589
9590 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9591 OMPLoopDirective::HelperExprs B;
9592 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9593 // define the nested loops number.
9594 unsigned NestedLoopCount =
9595 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9596 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9597 VarsWithImplicitDSA, B);
9598 if (NestedLoopCount == 0)
9599 return StmtError();
9600
9601 assert((CurContext->isDependentContext() || B.builtAll()) &&
9602 "omp for loop exprs were not built");
9603
9604 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9605 // The grainsize clause and num_tasks clause are mutually exclusive and may
9606 // not appear on the same taskloop directive.
9607 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9608 return StmtError();
9609 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9610 // If a reduction clause is present on the taskloop directive, the nogroup
9611 // clause must not be specified.
9612 if (checkReductionClauseWithNogroup(*this, Clauses))
9613 return StmtError();
9614
9615 setFunctionHasBranchProtectedScope();
9616 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9617 NestedLoopCount, Clauses, AStmt, B);
9618}
9619
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009620StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9622 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9623 if (!AStmt)
9624 return StmtError();
9625
9626 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9627 OMPLoopDirective::HelperExprs B;
9628 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9629 // define the nested loops number.
9630 unsigned NestedLoopCount =
9631 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9632 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9633 VarsWithImplicitDSA, B);
9634 if (NestedLoopCount == 0)
9635 return StmtError();
9636
9637 assert((CurContext->isDependentContext() || B.builtAll()) &&
9638 "omp for loop exprs were not built");
9639
9640 if (!CurContext->isDependentContext()) {
9641 // Finalize the clauses that need pre-built expressions for CodeGen.
9642 for (OMPClause *C : Clauses) {
9643 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9644 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9645 B.NumIterations, *this, CurScope,
9646 DSAStack))
9647 return StmtError();
9648 }
9649 }
9650
9651 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9652 // The grainsize clause and num_tasks clause are mutually exclusive and may
9653 // not appear on the same taskloop directive.
9654 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9655 return StmtError();
9656 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9657 // If a reduction clause is present on the taskloop directive, the nogroup
9658 // clause must not be specified.
9659 if (checkReductionClauseWithNogroup(*this, Clauses))
9660 return StmtError();
9661 if (checkSimdlenSafelenSpecified(*this, Clauses))
9662 return StmtError();
9663
9664 setFunctionHasBranchProtectedScope();
9665 return OMPMasterTaskLoopSimdDirective::Create(
9666 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9667}
9668
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009669StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9670 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9671 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9672 if (!AStmt)
9673 return StmtError();
9674
9675 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9676 auto *CS = cast<CapturedStmt>(AStmt);
9677 // 1.2.2 OpenMP Language Terminology
9678 // Structured block - An executable statement with a single entry at the
9679 // top and a single exit at the bottom.
9680 // The point of exit cannot be a branch out of the structured block.
9681 // longjmp() and throw() must not violate the entry/exit criteria.
9682 CS->getCapturedDecl()->setNothrow();
9683 for (int ThisCaptureLevel =
9684 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9685 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9686 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9687 // 1.2.2 OpenMP Language Terminology
9688 // Structured block - An executable statement with a single entry at the
9689 // top and a single exit at the bottom.
9690 // The point of exit cannot be a branch out of the structured block.
9691 // longjmp() and throw() must not violate the entry/exit criteria.
9692 CS->getCapturedDecl()->setNothrow();
9693 }
9694
9695 OMPLoopDirective::HelperExprs B;
9696 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9697 // define the nested loops number.
9698 unsigned NestedLoopCount = checkOpenMPLoop(
9699 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9700 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9701 VarsWithImplicitDSA, B);
9702 if (NestedLoopCount == 0)
9703 return StmtError();
9704
9705 assert((CurContext->isDependentContext() || B.builtAll()) &&
9706 "omp for loop exprs were not built");
9707
9708 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9709 // The grainsize clause and num_tasks clause are mutually exclusive and may
9710 // not appear on the same taskloop directive.
9711 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9712 return StmtError();
9713 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9714 // If a reduction clause is present on the taskloop directive, the nogroup
9715 // clause must not be specified.
9716 if (checkReductionClauseWithNogroup(*this, Clauses))
9717 return StmtError();
9718
9719 setFunctionHasBranchProtectedScope();
9720 return OMPParallelMasterTaskLoopDirective::Create(
9721 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9722}
9723
Alexey Bataev14a388f2019-10-25 10:27:13 -04009724StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9725 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9726 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9727 if (!AStmt)
9728 return StmtError();
9729
9730 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9731 auto *CS = cast<CapturedStmt>(AStmt);
9732 // 1.2.2 OpenMP Language Terminology
9733 // Structured block - An executable statement with a single entry at the
9734 // top and a single exit at the bottom.
9735 // The point of exit cannot be a branch out of the structured block.
9736 // longjmp() and throw() must not violate the entry/exit criteria.
9737 CS->getCapturedDecl()->setNothrow();
9738 for (int ThisCaptureLevel =
9739 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9740 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9741 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9742 // 1.2.2 OpenMP Language Terminology
9743 // Structured block - An executable statement with a single entry at the
9744 // top and a single exit at the bottom.
9745 // The point of exit cannot be a branch out of the structured block.
9746 // longjmp() and throw() must not violate the entry/exit criteria.
9747 CS->getCapturedDecl()->setNothrow();
9748 }
9749
9750 OMPLoopDirective::HelperExprs B;
9751 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9752 // define the nested loops number.
9753 unsigned NestedLoopCount = checkOpenMPLoop(
9754 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9755 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9756 VarsWithImplicitDSA, B);
9757 if (NestedLoopCount == 0)
9758 return StmtError();
9759
9760 assert((CurContext->isDependentContext() || B.builtAll()) &&
9761 "omp for loop exprs were not built");
9762
9763 if (!CurContext->isDependentContext()) {
9764 // Finalize the clauses that need pre-built expressions for CodeGen.
9765 for (OMPClause *C : Clauses) {
9766 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9767 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9768 B.NumIterations, *this, CurScope,
9769 DSAStack))
9770 return StmtError();
9771 }
9772 }
9773
9774 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9775 // The grainsize clause and num_tasks clause are mutually exclusive and may
9776 // not appear on the same taskloop directive.
9777 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9778 return StmtError();
9779 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9780 // If a reduction clause is present on the taskloop directive, the nogroup
9781 // clause must not be specified.
9782 if (checkReductionClauseWithNogroup(*this, Clauses))
9783 return StmtError();
9784 if (checkSimdlenSafelenSpecified(*this, Clauses))
9785 return StmtError();
9786
9787 setFunctionHasBranchProtectedScope();
9788 return OMPParallelMasterTaskLoopSimdDirective::Create(
9789 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9790}
9791
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009792StmtResult Sema::ActOnOpenMPDistributeDirective(
9793 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009794 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009795 if (!AStmt)
9796 return StmtError();
9797
9798 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9799 OMPLoopDirective::HelperExprs B;
9800 // In presence of clause 'collapse' with number of loops, it will
9801 // define the nested loops number.
9802 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009803 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009804 nullptr /*ordered not a clause on distribute*/, AStmt,
9805 *this, *DSAStack, VarsWithImplicitDSA, B);
9806 if (NestedLoopCount == 0)
9807 return StmtError();
9808
9809 assert((CurContext->isDependentContext() || B.builtAll()) &&
9810 "omp for loop exprs were not built");
9811
Reid Kleckner87a31802018-03-12 21:43:02 +00009812 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009813 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9814 NestedLoopCount, Clauses, AStmt, B);
9815}
9816
Carlo Bertolli9925f152016-06-27 14:55:37 +00009817StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9818 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009819 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009820 if (!AStmt)
9821 return StmtError();
9822
Alexey Bataeve3727102018-04-18 15:57:46 +00009823 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009824 // 1.2.2 OpenMP Language Terminology
9825 // Structured block - An executable statement with a single entry at the
9826 // top and a single exit at the bottom.
9827 // The point of exit cannot be a branch out of the structured block.
9828 // longjmp() and throw() must not violate the entry/exit criteria.
9829 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009830 for (int ThisCaptureLevel =
9831 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9832 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9833 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9834 // 1.2.2 OpenMP Language Terminology
9835 // Structured block - An executable statement with a single entry at the
9836 // top and a single exit at the bottom.
9837 // The point of exit cannot be a branch out of the structured block.
9838 // longjmp() and throw() must not violate the entry/exit criteria.
9839 CS->getCapturedDecl()->setNothrow();
9840 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009841
9842 OMPLoopDirective::HelperExprs B;
9843 // In presence of clause 'collapse' with number of loops, it will
9844 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009845 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009846 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009847 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009848 VarsWithImplicitDSA, B);
9849 if (NestedLoopCount == 0)
9850 return StmtError();
9851
9852 assert((CurContext->isDependentContext() || B.builtAll()) &&
9853 "omp for loop exprs were not built");
9854
Reid Kleckner87a31802018-03-12 21:43:02 +00009855 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009856 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009857 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9858 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009859}
9860
Kelvin Li4a39add2016-07-05 05:00:15 +00009861StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9862 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009863 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009864 if (!AStmt)
9865 return StmtError();
9866
Alexey Bataeve3727102018-04-18 15:57:46 +00009867 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009868 // 1.2.2 OpenMP Language Terminology
9869 // Structured block - An executable statement with a single entry at the
9870 // top and a single exit at the bottom.
9871 // The point of exit cannot be a branch out of the structured block.
9872 // longjmp() and throw() must not violate the entry/exit criteria.
9873 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009874 for (int ThisCaptureLevel =
9875 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9876 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9877 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9878 // 1.2.2 OpenMP Language Terminology
9879 // Structured block - An executable statement with a single entry at the
9880 // top and a single exit at the bottom.
9881 // The point of exit cannot be a branch out of the structured block.
9882 // longjmp() and throw() must not violate the entry/exit criteria.
9883 CS->getCapturedDecl()->setNothrow();
9884 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009885
9886 OMPLoopDirective::HelperExprs B;
9887 // In presence of clause 'collapse' with number of loops, it will
9888 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009889 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009890 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009891 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009892 VarsWithImplicitDSA, B);
9893 if (NestedLoopCount == 0)
9894 return StmtError();
9895
9896 assert((CurContext->isDependentContext() || B.builtAll()) &&
9897 "omp for loop exprs were not built");
9898
Alexey Bataev438388c2017-11-22 18:34:02 +00009899 if (!CurContext->isDependentContext()) {
9900 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009901 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009902 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9903 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9904 B.NumIterations, *this, CurScope,
9905 DSAStack))
9906 return StmtError();
9907 }
9908 }
9909
Kelvin Lic5609492016-07-15 04:39:07 +00009910 if (checkSimdlenSafelenSpecified(*this, Clauses))
9911 return StmtError();
9912
Reid Kleckner87a31802018-03-12 21:43:02 +00009913 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009914 return OMPDistributeParallelForSimdDirective::Create(
9915 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9916}
9917
Kelvin Li787f3fc2016-07-06 04:45:38 +00009918StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9919 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009920 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009921 if (!AStmt)
9922 return StmtError();
9923
Alexey Bataeve3727102018-04-18 15:57:46 +00009924 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009925 // 1.2.2 OpenMP Language Terminology
9926 // Structured block - An executable statement with a single entry at the
9927 // top and a single exit at the bottom.
9928 // The point of exit cannot be a branch out of the structured block.
9929 // longjmp() and throw() must not violate the entry/exit criteria.
9930 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009931 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9932 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9933 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9934 // 1.2.2 OpenMP Language Terminology
9935 // Structured block - An executable statement with a single entry at the
9936 // top and a single exit at the bottom.
9937 // The point of exit cannot be a branch out of the structured block.
9938 // longjmp() and throw() must not violate the entry/exit criteria.
9939 CS->getCapturedDecl()->setNothrow();
9940 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009941
9942 OMPLoopDirective::HelperExprs B;
9943 // In presence of clause 'collapse' with number of loops, it will
9944 // define the nested loops number.
9945 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009946 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009947 nullptr /*ordered not a clause on distribute*/, CS, *this,
9948 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009949 if (NestedLoopCount == 0)
9950 return StmtError();
9951
9952 assert((CurContext->isDependentContext() || B.builtAll()) &&
9953 "omp for loop exprs were not built");
9954
Alexey Bataev438388c2017-11-22 18:34:02 +00009955 if (!CurContext->isDependentContext()) {
9956 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009957 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009958 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9959 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9960 B.NumIterations, *this, CurScope,
9961 DSAStack))
9962 return StmtError();
9963 }
9964 }
9965
Kelvin Lic5609492016-07-15 04:39:07 +00009966 if (checkSimdlenSafelenSpecified(*this, Clauses))
9967 return StmtError();
9968
Reid Kleckner87a31802018-03-12 21:43:02 +00009969 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009970 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9971 NestedLoopCount, Clauses, AStmt, B);
9972}
9973
Kelvin Lia579b912016-07-14 02:54:56 +00009974StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9975 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009976 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009977 if (!AStmt)
9978 return StmtError();
9979
Alexey Bataeve3727102018-04-18 15:57:46 +00009980 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009981 // 1.2.2 OpenMP Language Terminology
9982 // Structured block - An executable statement with a single entry at the
9983 // top and a single exit at the bottom.
9984 // The point of exit cannot be a branch out of the structured block.
9985 // longjmp() and throw() must not violate the entry/exit criteria.
9986 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009987 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9988 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9989 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9990 // 1.2.2 OpenMP Language Terminology
9991 // Structured block - An executable statement with a single entry at the
9992 // top and a single exit at the bottom.
9993 // The point of exit cannot be a branch out of the structured block.
9994 // longjmp() and throw() must not violate the entry/exit criteria.
9995 CS->getCapturedDecl()->setNothrow();
9996 }
Kelvin Lia579b912016-07-14 02:54:56 +00009997
9998 OMPLoopDirective::HelperExprs B;
9999 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10000 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010001 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010002 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010003 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010004 VarsWithImplicitDSA, B);
10005 if (NestedLoopCount == 0)
10006 return StmtError();
10007
10008 assert((CurContext->isDependentContext() || B.builtAll()) &&
10009 "omp target parallel for simd loop exprs were not built");
10010
10011 if (!CurContext->isDependentContext()) {
10012 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010013 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010014 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010015 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10016 B.NumIterations, *this, CurScope,
10017 DSAStack))
10018 return StmtError();
10019 }
10020 }
Kelvin Lic5609492016-07-15 04:39:07 +000010021 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010022 return StmtError();
10023
Reid Kleckner87a31802018-03-12 21:43:02 +000010024 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010025 return OMPTargetParallelForSimdDirective::Create(
10026 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10027}
10028
Kelvin Li986330c2016-07-20 22:57:10 +000010029StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10030 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010031 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010032 if (!AStmt)
10033 return StmtError();
10034
Alexey Bataeve3727102018-04-18 15:57:46 +000010035 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010036 // 1.2.2 OpenMP Language Terminology
10037 // Structured block - An executable statement with a single entry at the
10038 // top and a single exit at the bottom.
10039 // The point of exit cannot be a branch out of the structured block.
10040 // longjmp() and throw() must not violate the entry/exit criteria.
10041 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010042 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10043 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10044 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10045 // 1.2.2 OpenMP Language Terminology
10046 // Structured block - An executable statement with a single entry at the
10047 // top and a single exit at the bottom.
10048 // The point of exit cannot be a branch out of the structured block.
10049 // longjmp() and throw() must not violate the entry/exit criteria.
10050 CS->getCapturedDecl()->setNothrow();
10051 }
10052
Kelvin Li986330c2016-07-20 22:57:10 +000010053 OMPLoopDirective::HelperExprs B;
10054 // In presence of clause 'collapse' with number of loops, it will define the
10055 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010056 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010057 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010058 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010059 VarsWithImplicitDSA, B);
10060 if (NestedLoopCount == 0)
10061 return StmtError();
10062
10063 assert((CurContext->isDependentContext() || B.builtAll()) &&
10064 "omp target simd loop exprs were not built");
10065
10066 if (!CurContext->isDependentContext()) {
10067 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010068 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010069 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010070 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10071 B.NumIterations, *this, CurScope,
10072 DSAStack))
10073 return StmtError();
10074 }
10075 }
10076
10077 if (checkSimdlenSafelenSpecified(*this, Clauses))
10078 return StmtError();
10079
Reid Kleckner87a31802018-03-12 21:43:02 +000010080 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010081 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10082 NestedLoopCount, Clauses, AStmt, B);
10083}
10084
Kelvin Li02532872016-08-05 14:37:37 +000010085StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10086 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010087 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010088 if (!AStmt)
10089 return StmtError();
10090
Alexey Bataeve3727102018-04-18 15:57:46 +000010091 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010092 // 1.2.2 OpenMP Language Terminology
10093 // Structured block - An executable statement with a single entry at the
10094 // top and a single exit at the bottom.
10095 // The point of exit cannot be a branch out of the structured block.
10096 // longjmp() and throw() must not violate the entry/exit criteria.
10097 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010098 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10099 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10100 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10101 // 1.2.2 OpenMP Language Terminology
10102 // Structured block - An executable statement with a single entry at the
10103 // top and a single exit at the bottom.
10104 // The point of exit cannot be a branch out of the structured block.
10105 // longjmp() and throw() must not violate the entry/exit criteria.
10106 CS->getCapturedDecl()->setNothrow();
10107 }
Kelvin Li02532872016-08-05 14:37:37 +000010108
10109 OMPLoopDirective::HelperExprs B;
10110 // In presence of clause 'collapse' with number of loops, it will
10111 // define the nested loops number.
10112 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010113 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010114 nullptr /*ordered not a clause on distribute*/, CS, *this,
10115 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010116 if (NestedLoopCount == 0)
10117 return StmtError();
10118
10119 assert((CurContext->isDependentContext() || B.builtAll()) &&
10120 "omp teams distribute loop exprs were not built");
10121
Reid Kleckner87a31802018-03-12 21:43:02 +000010122 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010123
10124 DSAStack->setParentTeamsRegionLoc(StartLoc);
10125
David Majnemer9d168222016-08-05 17:44:54 +000010126 return OMPTeamsDistributeDirective::Create(
10127 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010128}
10129
Kelvin Li4e325f72016-10-25 12:50:55 +000010130StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010132 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010133 if (!AStmt)
10134 return StmtError();
10135
Alexey Bataeve3727102018-04-18 15:57:46 +000010136 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010137 // 1.2.2 OpenMP Language Terminology
10138 // Structured block - An executable statement with a single entry at the
10139 // top and a single exit at the bottom.
10140 // The point of exit cannot be a branch out of the structured block.
10141 // longjmp() and throw() must not violate the entry/exit criteria.
10142 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010143 for (int ThisCaptureLevel =
10144 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10145 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10146 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10147 // 1.2.2 OpenMP Language Terminology
10148 // Structured block - An executable statement with a single entry at the
10149 // top and a single exit at the bottom.
10150 // The point of exit cannot be a branch out of the structured block.
10151 // longjmp() and throw() must not violate the entry/exit criteria.
10152 CS->getCapturedDecl()->setNothrow();
10153 }
10154
Kelvin Li4e325f72016-10-25 12:50:55 +000010155
10156 OMPLoopDirective::HelperExprs B;
10157 // In presence of clause 'collapse' with number of loops, it will
10158 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010159 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010160 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010161 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010162 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010163
10164 if (NestedLoopCount == 0)
10165 return StmtError();
10166
10167 assert((CurContext->isDependentContext() || B.builtAll()) &&
10168 "omp teams distribute simd loop exprs were not built");
10169
10170 if (!CurContext->isDependentContext()) {
10171 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010172 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010173 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10174 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10175 B.NumIterations, *this, CurScope,
10176 DSAStack))
10177 return StmtError();
10178 }
10179 }
10180
10181 if (checkSimdlenSafelenSpecified(*this, Clauses))
10182 return StmtError();
10183
Reid Kleckner87a31802018-03-12 21:43:02 +000010184 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010185
10186 DSAStack->setParentTeamsRegionLoc(StartLoc);
10187
Kelvin Li4e325f72016-10-25 12:50:55 +000010188 return OMPTeamsDistributeSimdDirective::Create(
10189 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10190}
10191
Kelvin Li579e41c2016-11-30 23:51:03 +000010192StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10193 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010194 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010195 if (!AStmt)
10196 return StmtError();
10197
Alexey Bataeve3727102018-04-18 15:57:46 +000010198 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010199 // 1.2.2 OpenMP Language Terminology
10200 // Structured block - An executable statement with a single entry at the
10201 // top and a single exit at the bottom.
10202 // The point of exit cannot be a branch out of the structured block.
10203 // longjmp() and throw() must not violate the entry/exit criteria.
10204 CS->getCapturedDecl()->setNothrow();
10205
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010206 for (int ThisCaptureLevel =
10207 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10208 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10209 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10210 // 1.2.2 OpenMP Language Terminology
10211 // Structured block - An executable statement with a single entry at the
10212 // top and a single exit at the bottom.
10213 // The point of exit cannot be a branch out of the structured block.
10214 // longjmp() and throw() must not violate the entry/exit criteria.
10215 CS->getCapturedDecl()->setNothrow();
10216 }
10217
Kelvin Li579e41c2016-11-30 23:51:03 +000010218 OMPLoopDirective::HelperExprs B;
10219 // In presence of clause 'collapse' with number of loops, it will
10220 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010221 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010222 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010223 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010224 VarsWithImplicitDSA, B);
10225
10226 if (NestedLoopCount == 0)
10227 return StmtError();
10228
10229 assert((CurContext->isDependentContext() || B.builtAll()) &&
10230 "omp for loop exprs were not built");
10231
10232 if (!CurContext->isDependentContext()) {
10233 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010234 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010235 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10236 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10237 B.NumIterations, *this, CurScope,
10238 DSAStack))
10239 return StmtError();
10240 }
10241 }
10242
10243 if (checkSimdlenSafelenSpecified(*this, Clauses))
10244 return StmtError();
10245
Reid Kleckner87a31802018-03-12 21:43:02 +000010246 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010247
10248 DSAStack->setParentTeamsRegionLoc(StartLoc);
10249
Kelvin Li579e41c2016-11-30 23:51:03 +000010250 return OMPTeamsDistributeParallelForSimdDirective::Create(
10251 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10252}
10253
Kelvin Li7ade93f2016-12-09 03:24:30 +000010254StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10255 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010256 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010257 if (!AStmt)
10258 return StmtError();
10259
Alexey Bataeve3727102018-04-18 15:57:46 +000010260 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010261 // 1.2.2 OpenMP Language Terminology
10262 // Structured block - An executable statement with a single entry at the
10263 // top and a single exit at the bottom.
10264 // The point of exit cannot be a branch out of the structured block.
10265 // longjmp() and throw() must not violate the entry/exit criteria.
10266 CS->getCapturedDecl()->setNothrow();
10267
Carlo Bertolli62fae152017-11-20 20:46:39 +000010268 for (int ThisCaptureLevel =
10269 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10270 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10271 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10272 // 1.2.2 OpenMP Language Terminology
10273 // Structured block - An executable statement with a single entry at the
10274 // top and a single exit at the bottom.
10275 // The point of exit cannot be a branch out of the structured block.
10276 // longjmp() and throw() must not violate the entry/exit criteria.
10277 CS->getCapturedDecl()->setNothrow();
10278 }
10279
Kelvin Li7ade93f2016-12-09 03:24:30 +000010280 OMPLoopDirective::HelperExprs B;
10281 // In presence of clause 'collapse' with number of loops, it will
10282 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010283 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010284 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010285 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010286 VarsWithImplicitDSA, B);
10287
10288 if (NestedLoopCount == 0)
10289 return StmtError();
10290
10291 assert((CurContext->isDependentContext() || B.builtAll()) &&
10292 "omp for loop exprs were not built");
10293
Reid Kleckner87a31802018-03-12 21:43:02 +000010294 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010295
10296 DSAStack->setParentTeamsRegionLoc(StartLoc);
10297
Kelvin Li7ade93f2016-12-09 03:24:30 +000010298 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010299 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10300 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010301}
10302
Kelvin Libf594a52016-12-17 05:48:59 +000010303StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10304 Stmt *AStmt,
10305 SourceLocation StartLoc,
10306 SourceLocation EndLoc) {
10307 if (!AStmt)
10308 return StmtError();
10309
Alexey Bataeve3727102018-04-18 15:57:46 +000010310 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010311 // 1.2.2 OpenMP Language Terminology
10312 // Structured block - An executable statement with a single entry at the
10313 // top and a single exit at the bottom.
10314 // The point of exit cannot be a branch out of the structured block.
10315 // longjmp() and throw() must not violate the entry/exit criteria.
10316 CS->getCapturedDecl()->setNothrow();
10317
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010318 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10319 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10320 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10321 // 1.2.2 OpenMP Language Terminology
10322 // Structured block - An executable statement with a single entry at the
10323 // top and a single exit at the bottom.
10324 // The point of exit cannot be a branch out of the structured block.
10325 // longjmp() and throw() must not violate the entry/exit criteria.
10326 CS->getCapturedDecl()->setNothrow();
10327 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010328 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010329
10330 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10331 AStmt);
10332}
10333
Kelvin Li83c451e2016-12-25 04:52:54 +000010334StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10335 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010336 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010337 if (!AStmt)
10338 return StmtError();
10339
Alexey Bataeve3727102018-04-18 15:57:46 +000010340 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010341 // 1.2.2 OpenMP Language Terminology
10342 // Structured block - An executable statement with a single entry at the
10343 // top and a single exit at the bottom.
10344 // The point of exit cannot be a branch out of the structured block.
10345 // longjmp() and throw() must not violate the entry/exit criteria.
10346 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010347 for (int ThisCaptureLevel =
10348 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10349 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10350 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10351 // 1.2.2 OpenMP Language Terminology
10352 // Structured block - An executable statement with a single entry at the
10353 // top and a single exit at the bottom.
10354 // The point of exit cannot be a branch out of the structured block.
10355 // longjmp() and throw() must not violate the entry/exit criteria.
10356 CS->getCapturedDecl()->setNothrow();
10357 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010358
10359 OMPLoopDirective::HelperExprs B;
10360 // In presence of clause 'collapse' with number of loops, it will
10361 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010362 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010363 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10364 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010365 VarsWithImplicitDSA, B);
10366 if (NestedLoopCount == 0)
10367 return StmtError();
10368
10369 assert((CurContext->isDependentContext() || B.builtAll()) &&
10370 "omp target teams distribute loop exprs were not built");
10371
Reid Kleckner87a31802018-03-12 21:43:02 +000010372 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010373 return OMPTargetTeamsDistributeDirective::Create(
10374 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10375}
10376
Kelvin Li80e8f562016-12-29 22:16:30 +000010377StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10378 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010379 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010380 if (!AStmt)
10381 return StmtError();
10382
Alexey Bataeve3727102018-04-18 15:57:46 +000010383 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010384 // 1.2.2 OpenMP Language Terminology
10385 // Structured block - An executable statement with a single entry at the
10386 // top and a single exit at the bottom.
10387 // The point of exit cannot be a branch out of the structured block.
10388 // longjmp() and throw() must not violate the entry/exit criteria.
10389 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010390 for (int ThisCaptureLevel =
10391 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10392 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10393 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10394 // 1.2.2 OpenMP Language Terminology
10395 // Structured block - An executable statement with a single entry at the
10396 // top and a single exit at the bottom.
10397 // The point of exit cannot be a branch out of the structured block.
10398 // longjmp() and throw() must not violate the entry/exit criteria.
10399 CS->getCapturedDecl()->setNothrow();
10400 }
10401
Kelvin Li80e8f562016-12-29 22:16:30 +000010402 OMPLoopDirective::HelperExprs B;
10403 // In presence of clause 'collapse' with number of loops, it will
10404 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010405 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010406 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10407 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010408 VarsWithImplicitDSA, B);
10409 if (NestedLoopCount == 0)
10410 return StmtError();
10411
10412 assert((CurContext->isDependentContext() || B.builtAll()) &&
10413 "omp target teams distribute parallel for loop exprs were not built");
10414
Alexey Bataev647dd842018-01-15 20:59:40 +000010415 if (!CurContext->isDependentContext()) {
10416 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010417 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010418 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10419 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10420 B.NumIterations, *this, CurScope,
10421 DSAStack))
10422 return StmtError();
10423 }
10424 }
10425
Reid Kleckner87a31802018-03-12 21:43:02 +000010426 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010427 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010428 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10429 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010430}
10431
Kelvin Li1851df52017-01-03 05:23:48 +000010432StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10433 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010434 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010435 if (!AStmt)
10436 return StmtError();
10437
Alexey Bataeve3727102018-04-18 15:57:46 +000010438 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010439 // 1.2.2 OpenMP Language Terminology
10440 // Structured block - An executable statement with a single entry at the
10441 // top and a single exit at the bottom.
10442 // The point of exit cannot be a branch out of the structured block.
10443 // longjmp() and throw() must not violate the entry/exit criteria.
10444 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010445 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10446 OMPD_target_teams_distribute_parallel_for_simd);
10447 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10448 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10449 // 1.2.2 OpenMP Language Terminology
10450 // Structured block - An executable statement with a single entry at the
10451 // top and a single exit at the bottom.
10452 // The point of exit cannot be a branch out of the structured block.
10453 // longjmp() and throw() must not violate the entry/exit criteria.
10454 CS->getCapturedDecl()->setNothrow();
10455 }
Kelvin Li1851df52017-01-03 05:23:48 +000010456
10457 OMPLoopDirective::HelperExprs B;
10458 // In presence of clause 'collapse' with number of loops, it will
10459 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010460 unsigned NestedLoopCount =
10461 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010462 getCollapseNumberExpr(Clauses),
10463 nullptr /*ordered not a clause on distribute*/, CS, *this,
10464 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010465 if (NestedLoopCount == 0)
10466 return StmtError();
10467
10468 assert((CurContext->isDependentContext() || B.builtAll()) &&
10469 "omp target teams distribute parallel for simd loop exprs were not "
10470 "built");
10471
10472 if (!CurContext->isDependentContext()) {
10473 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010474 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010475 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10476 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10477 B.NumIterations, *this, CurScope,
10478 DSAStack))
10479 return StmtError();
10480 }
10481 }
10482
Alexey Bataev438388c2017-11-22 18:34:02 +000010483 if (checkSimdlenSafelenSpecified(*this, Clauses))
10484 return StmtError();
10485
Reid Kleckner87a31802018-03-12 21:43:02 +000010486 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010487 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10488 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10489}
10490
Kelvin Lida681182017-01-10 18:08:18 +000010491StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10492 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010493 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010494 if (!AStmt)
10495 return StmtError();
10496
10497 auto *CS = cast<CapturedStmt>(AStmt);
10498 // 1.2.2 OpenMP Language Terminology
10499 // Structured block - An executable statement with a single entry at the
10500 // top and a single exit at the bottom.
10501 // The point of exit cannot be a branch out of the structured block.
10502 // longjmp() and throw() must not violate the entry/exit criteria.
10503 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010504 for (int ThisCaptureLevel =
10505 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10506 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10507 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10508 // 1.2.2 OpenMP Language Terminology
10509 // Structured block - An executable statement with a single entry at the
10510 // top and a single exit at the bottom.
10511 // The point of exit cannot be a branch out of the structured block.
10512 // longjmp() and throw() must not violate the entry/exit criteria.
10513 CS->getCapturedDecl()->setNothrow();
10514 }
Kelvin Lida681182017-01-10 18:08:18 +000010515
10516 OMPLoopDirective::HelperExprs B;
10517 // In presence of clause 'collapse' with number of loops, it will
10518 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010519 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010520 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010521 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010522 VarsWithImplicitDSA, B);
10523 if (NestedLoopCount == 0)
10524 return StmtError();
10525
10526 assert((CurContext->isDependentContext() || B.builtAll()) &&
10527 "omp target teams distribute simd loop exprs were not built");
10528
Alexey Bataev438388c2017-11-22 18:34:02 +000010529 if (!CurContext->isDependentContext()) {
10530 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010531 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010532 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10533 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10534 B.NumIterations, *this, CurScope,
10535 DSAStack))
10536 return StmtError();
10537 }
10538 }
10539
10540 if (checkSimdlenSafelenSpecified(*this, Clauses))
10541 return StmtError();
10542
Reid Kleckner87a31802018-03-12 21:43:02 +000010543 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010544 return OMPTargetTeamsDistributeSimdDirective::Create(
10545 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10546}
10547
Alexey Bataeved09d242014-05-28 05:53:51 +000010548OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010549 SourceLocation StartLoc,
10550 SourceLocation LParenLoc,
10551 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010552 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010553 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010554 case OMPC_final:
10555 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10556 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010557 case OMPC_num_threads:
10558 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10559 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010560 case OMPC_safelen:
10561 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10562 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010563 case OMPC_simdlen:
10564 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10565 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010566 case OMPC_allocator:
10567 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10568 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010569 case OMPC_collapse:
10570 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10571 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010572 case OMPC_ordered:
10573 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10574 break;
Michael Wonge710d542015-08-07 16:16:36 +000010575 case OMPC_device:
10576 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10577 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010578 case OMPC_num_teams:
10579 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10580 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010581 case OMPC_thread_limit:
10582 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10583 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010584 case OMPC_priority:
10585 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10586 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010587 case OMPC_grainsize:
10588 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10589 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010590 case OMPC_num_tasks:
10591 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10592 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010593 case OMPC_hint:
10594 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10595 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010596 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010597 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010598 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010599 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010600 case OMPC_private:
10601 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010602 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010603 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010604 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010605 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010606 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010607 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010608 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010609 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010610 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010611 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010612 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010613 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010614 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010615 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010616 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010617 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010618 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010619 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010620 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010621 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010622 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010623 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010624 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010625 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010626 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010627 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010628 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010629 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010630 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010631 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010632 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010633 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010634 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010635 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010636 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010637 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010638 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010639 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010640 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010641 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010642 llvm_unreachable("Clause is not allowed.");
10643 }
10644 return Res;
10645}
10646
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010647// An OpenMP directive such as 'target parallel' has two captured regions:
10648// for the 'target' and 'parallel' respectively. This function returns
10649// the region in which to capture expressions associated with a clause.
10650// A return value of OMPD_unknown signifies that the expression should not
10651// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010652static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010653 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010654 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010655 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010656 switch (CKind) {
10657 case OMPC_if:
10658 switch (DKind) {
10659 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010660 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010661 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010662 // If this clause applies to the nested 'parallel' region, capture within
10663 // the 'target' region, otherwise do not capture.
10664 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10665 CaptureRegion = OMPD_target;
10666 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010667 case OMPD_target_teams_distribute_parallel_for:
10668 case OMPD_target_teams_distribute_parallel_for_simd:
10669 // If this clause applies to the nested 'parallel' region, capture within
10670 // the 'teams' region, otherwise do not capture.
10671 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10672 CaptureRegion = OMPD_teams;
10673 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010674 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010675 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010676 CaptureRegion = OMPD_teams;
10677 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010678 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010679 case OMPD_target_enter_data:
10680 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010681 CaptureRegion = OMPD_task;
10682 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010683 case OMPD_parallel_master_taskloop:
10684 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10685 CaptureRegion = OMPD_parallel;
10686 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010687 case OMPD_parallel_master_taskloop_simd:
10688 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10689 NameModifier == OMPD_taskloop) {
10690 CaptureRegion = OMPD_parallel;
10691 break;
10692 }
10693 if (OpenMPVersion <= 45)
10694 break;
10695 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10696 CaptureRegion = OMPD_taskloop;
10697 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010698 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010699 if (OpenMPVersion <= 45)
10700 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010701 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10702 CaptureRegion = OMPD_parallel;
10703 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010704 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010705 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010706 if (OpenMPVersion <= 45)
10707 break;
10708 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10709 CaptureRegion = OMPD_taskloop;
10710 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010711 case OMPD_cancel:
10712 case OMPD_parallel:
10713 case OMPD_parallel_sections:
10714 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010715 case OMPD_target:
10716 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010717 case OMPD_target_teams:
10718 case OMPD_target_teams_distribute:
10719 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010720 case OMPD_distribute_parallel_for:
10721 case OMPD_distribute_parallel_for_simd:
10722 case OMPD_task:
10723 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010724 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010725 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010726 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010727 case OMPD_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010728 // Do not capture if-clause expressions.
10729 break;
10730 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010731 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010732 case OMPD_taskyield:
10733 case OMPD_barrier:
10734 case OMPD_taskwait:
10735 case OMPD_cancellation_point:
10736 case OMPD_flush:
10737 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010738 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010739 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010740 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010741 case OMPD_declare_target:
10742 case OMPD_end_declare_target:
10743 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010744 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010745 case OMPD_sections:
10746 case OMPD_section:
10747 case OMPD_single:
10748 case OMPD_master:
10749 case OMPD_critical:
10750 case OMPD_taskgroup:
10751 case OMPD_distribute:
10752 case OMPD_ordered:
10753 case OMPD_atomic:
10754 case OMPD_distribute_simd:
10755 case OMPD_teams_distribute:
10756 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010757 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010758 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10759 case OMPD_unknown:
10760 llvm_unreachable("Unknown OpenMP directive");
10761 }
10762 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010763 case OMPC_num_threads:
10764 switch (DKind) {
10765 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010766 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010767 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010768 CaptureRegion = OMPD_target;
10769 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010770 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010771 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010772 case OMPD_target_teams_distribute_parallel_for:
10773 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010774 CaptureRegion = OMPD_teams;
10775 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010776 case OMPD_parallel:
10777 case OMPD_parallel_sections:
10778 case OMPD_parallel_for:
10779 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010780 case OMPD_distribute_parallel_for:
10781 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010782 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010783 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010784 // Do not capture num_threads-clause expressions.
10785 break;
10786 case OMPD_target_data:
10787 case OMPD_target_enter_data:
10788 case OMPD_target_exit_data:
10789 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010790 case OMPD_target:
10791 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010792 case OMPD_target_teams:
10793 case OMPD_target_teams_distribute:
10794 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010795 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010796 case OMPD_task:
10797 case OMPD_taskloop:
10798 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010799 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010800 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010801 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010802 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010803 case OMPD_taskyield:
10804 case OMPD_barrier:
10805 case OMPD_taskwait:
10806 case OMPD_cancellation_point:
10807 case OMPD_flush:
10808 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010809 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010810 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010811 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010812 case OMPD_declare_target:
10813 case OMPD_end_declare_target:
10814 case OMPD_teams:
10815 case OMPD_simd:
10816 case OMPD_for:
10817 case OMPD_for_simd:
10818 case OMPD_sections:
10819 case OMPD_section:
10820 case OMPD_single:
10821 case OMPD_master:
10822 case OMPD_critical:
10823 case OMPD_taskgroup:
10824 case OMPD_distribute:
10825 case OMPD_ordered:
10826 case OMPD_atomic:
10827 case OMPD_distribute_simd:
10828 case OMPD_teams_distribute:
10829 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010830 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010831 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10832 case OMPD_unknown:
10833 llvm_unreachable("Unknown OpenMP directive");
10834 }
10835 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010836 case OMPC_num_teams:
10837 switch (DKind) {
10838 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010839 case OMPD_target_teams_distribute:
10840 case OMPD_target_teams_distribute_simd:
10841 case OMPD_target_teams_distribute_parallel_for:
10842 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010843 CaptureRegion = OMPD_target;
10844 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010845 case OMPD_teams_distribute_parallel_for:
10846 case OMPD_teams_distribute_parallel_for_simd:
10847 case OMPD_teams:
10848 case OMPD_teams_distribute:
10849 case OMPD_teams_distribute_simd:
10850 // Do not capture num_teams-clause expressions.
10851 break;
10852 case OMPD_distribute_parallel_for:
10853 case OMPD_distribute_parallel_for_simd:
10854 case OMPD_task:
10855 case OMPD_taskloop:
10856 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010857 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010858 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010859 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010860 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010861 case OMPD_target_data:
10862 case OMPD_target_enter_data:
10863 case OMPD_target_exit_data:
10864 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010865 case OMPD_cancel:
10866 case OMPD_parallel:
10867 case OMPD_parallel_sections:
10868 case OMPD_parallel_for:
10869 case OMPD_parallel_for_simd:
10870 case OMPD_target:
10871 case OMPD_target_simd:
10872 case OMPD_target_parallel:
10873 case OMPD_target_parallel_for:
10874 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010875 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010876 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010877 case OMPD_taskyield:
10878 case OMPD_barrier:
10879 case OMPD_taskwait:
10880 case OMPD_cancellation_point:
10881 case OMPD_flush:
10882 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010883 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010884 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010885 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010886 case OMPD_declare_target:
10887 case OMPD_end_declare_target:
10888 case OMPD_simd:
10889 case OMPD_for:
10890 case OMPD_for_simd:
10891 case OMPD_sections:
10892 case OMPD_section:
10893 case OMPD_single:
10894 case OMPD_master:
10895 case OMPD_critical:
10896 case OMPD_taskgroup:
10897 case OMPD_distribute:
10898 case OMPD_ordered:
10899 case OMPD_atomic:
10900 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010901 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010902 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10903 case OMPD_unknown:
10904 llvm_unreachable("Unknown OpenMP directive");
10905 }
10906 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010907 case OMPC_thread_limit:
10908 switch (DKind) {
10909 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010910 case OMPD_target_teams_distribute:
10911 case OMPD_target_teams_distribute_simd:
10912 case OMPD_target_teams_distribute_parallel_for:
10913 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010914 CaptureRegion = OMPD_target;
10915 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010916 case OMPD_teams_distribute_parallel_for:
10917 case OMPD_teams_distribute_parallel_for_simd:
10918 case OMPD_teams:
10919 case OMPD_teams_distribute:
10920 case OMPD_teams_distribute_simd:
10921 // Do not capture thread_limit-clause expressions.
10922 break;
10923 case OMPD_distribute_parallel_for:
10924 case OMPD_distribute_parallel_for_simd:
10925 case OMPD_task:
10926 case OMPD_taskloop:
10927 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010928 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010929 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010930 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010931 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010932 case OMPD_target_data:
10933 case OMPD_target_enter_data:
10934 case OMPD_target_exit_data:
10935 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010936 case OMPD_cancel:
10937 case OMPD_parallel:
10938 case OMPD_parallel_sections:
10939 case OMPD_parallel_for:
10940 case OMPD_parallel_for_simd:
10941 case OMPD_target:
10942 case OMPD_target_simd:
10943 case OMPD_target_parallel:
10944 case OMPD_target_parallel_for:
10945 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010946 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010947 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010948 case OMPD_taskyield:
10949 case OMPD_barrier:
10950 case OMPD_taskwait:
10951 case OMPD_cancellation_point:
10952 case OMPD_flush:
10953 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010954 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010955 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010956 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010957 case OMPD_declare_target:
10958 case OMPD_end_declare_target:
10959 case OMPD_simd:
10960 case OMPD_for:
10961 case OMPD_for_simd:
10962 case OMPD_sections:
10963 case OMPD_section:
10964 case OMPD_single:
10965 case OMPD_master:
10966 case OMPD_critical:
10967 case OMPD_taskgroup:
10968 case OMPD_distribute:
10969 case OMPD_ordered:
10970 case OMPD_atomic:
10971 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010972 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010973 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10974 case OMPD_unknown:
10975 llvm_unreachable("Unknown OpenMP directive");
10976 }
10977 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010978 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010979 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010980 case OMPD_parallel_for:
10981 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010982 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010983 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010984 case OMPD_teams_distribute_parallel_for:
10985 case OMPD_teams_distribute_parallel_for_simd:
10986 case OMPD_target_parallel_for:
10987 case OMPD_target_parallel_for_simd:
10988 case OMPD_target_teams_distribute_parallel_for:
10989 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010990 CaptureRegion = OMPD_parallel;
10991 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010992 case OMPD_for:
10993 case OMPD_for_simd:
10994 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010995 break;
10996 case OMPD_task:
10997 case OMPD_taskloop:
10998 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010999 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011000 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011001 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011002 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011003 case OMPD_target_data:
11004 case OMPD_target_enter_data:
11005 case OMPD_target_exit_data:
11006 case OMPD_target_update:
11007 case OMPD_teams:
11008 case OMPD_teams_distribute:
11009 case OMPD_teams_distribute_simd:
11010 case OMPD_target_teams_distribute:
11011 case OMPD_target_teams_distribute_simd:
11012 case OMPD_target:
11013 case OMPD_target_simd:
11014 case OMPD_target_parallel:
11015 case OMPD_cancel:
11016 case OMPD_parallel:
11017 case OMPD_parallel_sections:
11018 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011019 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011020 case OMPD_taskyield:
11021 case OMPD_barrier:
11022 case OMPD_taskwait:
11023 case OMPD_cancellation_point:
11024 case OMPD_flush:
11025 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011026 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011027 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011028 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011029 case OMPD_declare_target:
11030 case OMPD_end_declare_target:
11031 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011032 case OMPD_sections:
11033 case OMPD_section:
11034 case OMPD_single:
11035 case OMPD_master:
11036 case OMPD_critical:
11037 case OMPD_taskgroup:
11038 case OMPD_distribute:
11039 case OMPD_ordered:
11040 case OMPD_atomic:
11041 case OMPD_distribute_simd:
11042 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011043 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011044 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11045 case OMPD_unknown:
11046 llvm_unreachable("Unknown OpenMP directive");
11047 }
11048 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011049 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011050 switch (DKind) {
11051 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011052 case OMPD_teams_distribute_parallel_for_simd:
11053 case OMPD_teams_distribute:
11054 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011055 case OMPD_target_teams_distribute_parallel_for:
11056 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011057 case OMPD_target_teams_distribute:
11058 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011059 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011060 break;
11061 case OMPD_distribute_parallel_for:
11062 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011063 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011064 case OMPD_distribute_simd:
11065 // Do not capture thread_limit-clause expressions.
11066 break;
11067 case OMPD_parallel_for:
11068 case OMPD_parallel_for_simd:
11069 case OMPD_target_parallel_for_simd:
11070 case OMPD_target_parallel_for:
11071 case OMPD_task:
11072 case OMPD_taskloop:
11073 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011074 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011075 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011076 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011077 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011078 case OMPD_target_data:
11079 case OMPD_target_enter_data:
11080 case OMPD_target_exit_data:
11081 case OMPD_target_update:
11082 case OMPD_teams:
11083 case OMPD_target:
11084 case OMPD_target_simd:
11085 case OMPD_target_parallel:
11086 case OMPD_cancel:
11087 case OMPD_parallel:
11088 case OMPD_parallel_sections:
11089 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011090 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011091 case OMPD_taskyield:
11092 case OMPD_barrier:
11093 case OMPD_taskwait:
11094 case OMPD_cancellation_point:
11095 case OMPD_flush:
11096 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011097 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011098 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011099 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011100 case OMPD_declare_target:
11101 case OMPD_end_declare_target:
11102 case OMPD_simd:
11103 case OMPD_for:
11104 case OMPD_for_simd:
11105 case OMPD_sections:
11106 case OMPD_section:
11107 case OMPD_single:
11108 case OMPD_master:
11109 case OMPD_critical:
11110 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011111 case OMPD_ordered:
11112 case OMPD_atomic:
11113 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011114 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011115 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11116 case OMPD_unknown:
11117 llvm_unreachable("Unknown OpenMP directive");
11118 }
11119 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011120 case OMPC_device:
11121 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011122 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011123 case OMPD_target_enter_data:
11124 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011125 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011126 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011127 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011128 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011129 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011130 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011131 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011132 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011133 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011134 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011135 CaptureRegion = OMPD_task;
11136 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011137 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011138 // Do not capture device-clause expressions.
11139 break;
11140 case OMPD_teams_distribute_parallel_for:
11141 case OMPD_teams_distribute_parallel_for_simd:
11142 case OMPD_teams:
11143 case OMPD_teams_distribute:
11144 case OMPD_teams_distribute_simd:
11145 case OMPD_distribute_parallel_for:
11146 case OMPD_distribute_parallel_for_simd:
11147 case OMPD_task:
11148 case OMPD_taskloop:
11149 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011150 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011151 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011152 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011153 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011154 case OMPD_cancel:
11155 case OMPD_parallel:
11156 case OMPD_parallel_sections:
11157 case OMPD_parallel_for:
11158 case OMPD_parallel_for_simd:
11159 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011160 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011161 case OMPD_taskyield:
11162 case OMPD_barrier:
11163 case OMPD_taskwait:
11164 case OMPD_cancellation_point:
11165 case OMPD_flush:
11166 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011167 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011168 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011169 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011170 case OMPD_declare_target:
11171 case OMPD_end_declare_target:
11172 case OMPD_simd:
11173 case OMPD_for:
11174 case OMPD_for_simd:
11175 case OMPD_sections:
11176 case OMPD_section:
11177 case OMPD_single:
11178 case OMPD_master:
11179 case OMPD_critical:
11180 case OMPD_taskgroup:
11181 case OMPD_distribute:
11182 case OMPD_ordered:
11183 case OMPD_atomic:
11184 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011185 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011186 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11187 case OMPD_unknown:
11188 llvm_unreachable("Unknown OpenMP directive");
11189 }
11190 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011191 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011192 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011193 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011194 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011195 switch (DKind) {
11196 case OMPD_task:
11197 case OMPD_taskloop:
11198 case OMPD_taskloop_simd:
11199 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011200 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011201 break;
11202 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011203 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011204 CaptureRegion = OMPD_parallel;
11205 break;
11206 case OMPD_target_update:
11207 case OMPD_target_enter_data:
11208 case OMPD_target_exit_data:
11209 case OMPD_target:
11210 case OMPD_target_simd:
11211 case OMPD_target_teams:
11212 case OMPD_target_parallel:
11213 case OMPD_target_teams_distribute:
11214 case OMPD_target_teams_distribute_simd:
11215 case OMPD_target_parallel_for:
11216 case OMPD_target_parallel_for_simd:
11217 case OMPD_target_teams_distribute_parallel_for:
11218 case OMPD_target_teams_distribute_parallel_for_simd:
11219 case OMPD_target_data:
11220 case OMPD_teams_distribute_parallel_for:
11221 case OMPD_teams_distribute_parallel_for_simd:
11222 case OMPD_teams:
11223 case OMPD_teams_distribute:
11224 case OMPD_teams_distribute_simd:
11225 case OMPD_distribute_parallel_for:
11226 case OMPD_distribute_parallel_for_simd:
11227 case OMPD_cancel:
11228 case OMPD_parallel:
11229 case OMPD_parallel_sections:
11230 case OMPD_parallel_for:
11231 case OMPD_parallel_for_simd:
11232 case OMPD_threadprivate:
11233 case OMPD_allocate:
11234 case OMPD_taskyield:
11235 case OMPD_barrier:
11236 case OMPD_taskwait:
11237 case OMPD_cancellation_point:
11238 case OMPD_flush:
11239 case OMPD_declare_reduction:
11240 case OMPD_declare_mapper:
11241 case OMPD_declare_simd:
11242 case OMPD_declare_variant:
11243 case OMPD_declare_target:
11244 case OMPD_end_declare_target:
11245 case OMPD_simd:
11246 case OMPD_for:
11247 case OMPD_for_simd:
11248 case OMPD_sections:
11249 case OMPD_section:
11250 case OMPD_single:
11251 case OMPD_master:
11252 case OMPD_critical:
11253 case OMPD_taskgroup:
11254 case OMPD_distribute:
11255 case OMPD_ordered:
11256 case OMPD_atomic:
11257 case OMPD_distribute_simd:
11258 case OMPD_requires:
11259 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11260 case OMPD_unknown:
11261 llvm_unreachable("Unknown OpenMP directive");
11262 }
11263 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011264 case OMPC_firstprivate:
11265 case OMPC_lastprivate:
11266 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011267 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011268 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011269 case OMPC_linear:
11270 case OMPC_default:
11271 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011272 case OMPC_safelen:
11273 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011274 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011275 case OMPC_collapse:
11276 case OMPC_private:
11277 case OMPC_shared:
11278 case OMPC_aligned:
11279 case OMPC_copyin:
11280 case OMPC_copyprivate:
11281 case OMPC_ordered:
11282 case OMPC_nowait:
11283 case OMPC_untied:
11284 case OMPC_mergeable:
11285 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011286 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011287 case OMPC_flush:
11288 case OMPC_read:
11289 case OMPC_write:
11290 case OMPC_update:
11291 case OMPC_capture:
11292 case OMPC_seq_cst:
11293 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011294 case OMPC_threads:
11295 case OMPC_simd:
11296 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011297 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011298 case OMPC_hint:
11299 case OMPC_defaultmap:
11300 case OMPC_unknown:
11301 case OMPC_uniform:
11302 case OMPC_to:
11303 case OMPC_from:
11304 case OMPC_use_device_ptr:
11305 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011306 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011307 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011308 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011309 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011310 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011311 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011312 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011313 llvm_unreachable("Unexpected OpenMP clause.");
11314 }
11315 return CaptureRegion;
11316}
11317
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011318OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11319 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011320 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011321 SourceLocation NameModifierLoc,
11322 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011323 SourceLocation EndLoc) {
11324 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011325 Stmt *HelperValStmt = nullptr;
11326 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011327 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11328 !Condition->isInstantiationDependent() &&
11329 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011330 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011331 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011332 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011333
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011334 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011335
11336 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011337 CaptureRegion = getOpenMPCaptureRegionForClause(
11338 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011339 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011340 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011341 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011342 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11343 HelperValStmt = buildPreInits(Context, Captures);
11344 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011345 }
11346
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011347 return new (Context)
11348 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11349 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011350}
11351
Alexey Bataev3778b602014-07-17 07:32:53 +000011352OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11353 SourceLocation StartLoc,
11354 SourceLocation LParenLoc,
11355 SourceLocation EndLoc) {
11356 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011357 Stmt *HelperValStmt = nullptr;
11358 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011359 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11360 !Condition->isInstantiationDependent() &&
11361 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011362 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011363 if (Val.isInvalid())
11364 return nullptr;
11365
Richard Smith03a4aa32016-06-23 19:02:52 +000011366 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011367
11368 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011369 CaptureRegion =
11370 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011371 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11372 ValExpr = MakeFullExpr(ValExpr).get();
11373 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11374 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11375 HelperValStmt = buildPreInits(Context, Captures);
11376 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011377 }
11378
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011379 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11380 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011381}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011382
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011383ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11384 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011385 if (!Op)
11386 return ExprError();
11387
11388 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11389 public:
11390 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011391 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011392 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11393 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011394 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11395 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011396 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11397 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011398 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11399 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011400 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11401 QualType T,
11402 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011403 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11404 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011405 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11406 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011407 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011408 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011409 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011410 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11411 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011412 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11413 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011414 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11415 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011416 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011417 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011418 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011419 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11420 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011421 llvm_unreachable("conversion functions are permitted");
11422 }
11423 } ConvertDiagnoser;
11424 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11425}
11426
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011427static bool
11428isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11429 bool StrictlyPositive, bool BuildCapture = false,
11430 OpenMPDirectiveKind DKind = OMPD_unknown,
11431 OpenMPDirectiveKind *CaptureRegion = nullptr,
11432 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011433 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11434 !ValExpr->isInstantiationDependent()) {
11435 SourceLocation Loc = ValExpr->getExprLoc();
11436 ExprResult Value =
11437 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11438 if (Value.isInvalid())
11439 return false;
11440
11441 ValExpr = Value.get();
11442 // The expression must evaluate to a non-negative integer value.
11443 llvm::APSInt Result;
11444 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011445 Result.isSigned() &&
11446 !((!StrictlyPositive && Result.isNonNegative()) ||
11447 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011448 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011449 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11450 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011451 return false;
11452 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011453 if (!BuildCapture)
11454 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011455 *CaptureRegion =
11456 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011457 if (*CaptureRegion != OMPD_unknown &&
11458 !SemaRef.CurContext->isDependentContext()) {
11459 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11460 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11461 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11462 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11463 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011464 }
11465 return true;
11466}
11467
Alexey Bataev568a8332014-03-06 06:15:19 +000011468OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11469 SourceLocation StartLoc,
11470 SourceLocation LParenLoc,
11471 SourceLocation EndLoc) {
11472 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011473 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011474
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011475 // OpenMP [2.5, Restrictions]
11476 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011477 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011478 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011479 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011480
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011481 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011482 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011483 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011484 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011485 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011486 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011487 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11488 HelperValStmt = buildPreInits(Context, Captures);
11489 }
11490
11491 return new (Context) OMPNumThreadsClause(
11492 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011493}
11494
Alexey Bataev62c87d22014-03-21 04:51:18 +000011495ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011496 OpenMPClauseKind CKind,
11497 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011498 if (!E)
11499 return ExprError();
11500 if (E->isValueDependent() || E->isTypeDependent() ||
11501 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011502 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011503 llvm::APSInt Result;
11504 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11505 if (ICE.isInvalid())
11506 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011507 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11508 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011509 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011510 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11511 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011512 return ExprError();
11513 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011514 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11515 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11516 << E->getSourceRange();
11517 return ExprError();
11518 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011519 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11520 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011521 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011522 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011523 return ICE;
11524}
11525
11526OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11527 SourceLocation LParenLoc,
11528 SourceLocation EndLoc) {
11529 // OpenMP [2.8.1, simd construct, Description]
11530 // The parameter of the safelen clause must be a constant
11531 // positive integer expression.
11532 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11533 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011534 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011535 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011536 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011537}
11538
Alexey Bataev66b15b52015-08-21 11:14:16 +000011539OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11540 SourceLocation LParenLoc,
11541 SourceLocation EndLoc) {
11542 // OpenMP [2.8.1, simd construct, Description]
11543 // The parameter of the simdlen clause must be a constant
11544 // positive integer expression.
11545 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11546 if (Simdlen.isInvalid())
11547 return nullptr;
11548 return new (Context)
11549 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11550}
11551
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011552/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011553static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11554 DSAStackTy *Stack) {
11555 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011556 if (!OMPAllocatorHandleT.isNull())
11557 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011558 // Build the predefined allocator expressions.
11559 bool ErrorFound = false;
11560 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11561 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11562 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11563 StringRef Allocator =
11564 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11565 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11566 auto *VD = dyn_cast_or_null<ValueDecl>(
11567 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11568 if (!VD) {
11569 ErrorFound = true;
11570 break;
11571 }
11572 QualType AllocatorType =
11573 VD->getType().getNonLValueExprType(S.getASTContext());
11574 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11575 if (!Res.isUsable()) {
11576 ErrorFound = true;
11577 break;
11578 }
11579 if (OMPAllocatorHandleT.isNull())
11580 OMPAllocatorHandleT = AllocatorType;
11581 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11582 ErrorFound = true;
11583 break;
11584 }
11585 Stack->setAllocator(AllocatorKind, Res.get());
11586 }
11587 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011588 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11589 return false;
11590 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011591 OMPAllocatorHandleT.addConst();
11592 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011593 return true;
11594}
11595
11596OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11597 SourceLocation LParenLoc,
11598 SourceLocation EndLoc) {
11599 // OpenMP [2.11.3, allocate Directive, Description]
11600 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011601 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011602 return nullptr;
11603
11604 ExprResult Allocator = DefaultLvalueConversion(A);
11605 if (Allocator.isInvalid())
11606 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011607 Allocator = PerformImplicitConversion(Allocator.get(),
11608 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011609 Sema::AA_Initializing,
11610 /*AllowExplicit=*/true);
11611 if (Allocator.isInvalid())
11612 return nullptr;
11613 return new (Context)
11614 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11615}
11616
Alexander Musman64d33f12014-06-04 07:53:32 +000011617OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11618 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011619 SourceLocation LParenLoc,
11620 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011621 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011622 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011623 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011624 // The parameter of the collapse clause must be a constant
11625 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011626 ExprResult NumForLoopsResult =
11627 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11628 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011629 return nullptr;
11630 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011631 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011632}
11633
Alexey Bataev10e775f2015-07-30 11:36:16 +000011634OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11635 SourceLocation EndLoc,
11636 SourceLocation LParenLoc,
11637 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011638 // OpenMP [2.7.1, loop construct, Description]
11639 // OpenMP [2.8.1, simd construct, Description]
11640 // OpenMP [2.9.6, distribute construct, Description]
11641 // The parameter of the ordered clause must be a constant
11642 // positive integer expression if any.
11643 if (NumForLoops && LParenLoc.isValid()) {
11644 ExprResult NumForLoopsResult =
11645 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11646 if (NumForLoopsResult.isInvalid())
11647 return nullptr;
11648 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011649 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011650 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011651 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011652 auto *Clause = OMPOrderedClause::Create(
11653 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11654 StartLoc, LParenLoc, EndLoc);
11655 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11656 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011657}
11658
Alexey Bataeved09d242014-05-28 05:53:51 +000011659OMPClause *Sema::ActOnOpenMPSimpleClause(
11660 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11661 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011662 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011663 switch (Kind) {
11664 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011665 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011666 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11667 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011668 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011669 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011670 Res = ActOnOpenMPProcBindClause(
11671 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11672 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011673 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011674 case OMPC_atomic_default_mem_order:
11675 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11676 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11677 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11678 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011679 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011680 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011681 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011682 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011683 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011684 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011685 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011686 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011687 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011688 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011689 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011690 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011691 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011692 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011693 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011694 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011695 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011696 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011697 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011698 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011699 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011700 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011701 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011702 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011703 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011704 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011705 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011706 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011707 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011708 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011709 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011710 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011711 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011712 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011713 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011714 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011715 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011716 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011717 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011718 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011719 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011720 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011721 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011722 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011723 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011724 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011725 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011726 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011727 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011728 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011729 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011730 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011731 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011732 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011733 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011734 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011735 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011736 llvm_unreachable("Clause is not allowed.");
11737 }
11738 return Res;
11739}
11740
Alexey Bataev6402bca2015-12-28 07:25:51 +000011741static std::string
11742getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11743 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011744 SmallString<256> Buffer;
11745 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011746 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11747 unsigned Skipped = Exclude.size();
11748 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011749 for (unsigned I = First; I < Last; ++I) {
11750 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011751 --Skipped;
11752 continue;
11753 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011754 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11755 if (I == Bound - Skipped)
11756 Out << " or ";
11757 else if (I != Bound + 1 - Skipped)
11758 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011759 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011760 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011761}
11762
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011763OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11764 SourceLocation KindKwLoc,
11765 SourceLocation StartLoc,
11766 SourceLocation LParenLoc,
11767 SourceLocation EndLoc) {
11768 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011769 static_assert(OMPC_DEFAULT_unknown > 0,
11770 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011771 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011772 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11773 /*Last=*/OMPC_DEFAULT_unknown)
11774 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011775 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011776 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011777 switch (Kind) {
11778 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011779 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011780 break;
11781 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011782 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011783 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011784 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011785 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011786 break;
11787 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011788 return new (Context)
11789 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011790}
11791
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011792OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11793 SourceLocation KindKwLoc,
11794 SourceLocation StartLoc,
11795 SourceLocation LParenLoc,
11796 SourceLocation EndLoc) {
11797 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011798 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011799 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11800 /*Last=*/OMPC_PROC_BIND_unknown)
11801 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011802 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011803 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011804 return new (Context)
11805 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011806}
11807
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011808OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11809 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11810 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11811 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11812 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11813 << getListOfPossibleValues(
11814 OMPC_atomic_default_mem_order, /*First=*/0,
11815 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11816 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11817 return nullptr;
11818 }
11819 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11820 LParenLoc, EndLoc);
11821}
11822
Alexey Bataev56dafe82014-06-20 07:16:17 +000011823OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011824 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011825 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011826 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011827 SourceLocation EndLoc) {
11828 OMPClause *Res = nullptr;
11829 switch (Kind) {
11830 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011831 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11832 assert(Argument.size() == NumberOfElements &&
11833 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011834 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011835 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11836 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11837 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11838 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11839 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011840 break;
11841 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011842 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11843 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11844 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11845 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011846 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011847 case OMPC_dist_schedule:
11848 Res = ActOnOpenMPDistScheduleClause(
11849 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11850 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11851 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011852 case OMPC_defaultmap:
11853 enum { Modifier, DefaultmapKind };
11854 Res = ActOnOpenMPDefaultmapClause(
11855 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11856 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011857 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11858 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011859 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011860 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011861 case OMPC_num_threads:
11862 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011863 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011864 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011865 case OMPC_collapse:
11866 case OMPC_default:
11867 case OMPC_proc_bind:
11868 case OMPC_private:
11869 case OMPC_firstprivate:
11870 case OMPC_lastprivate:
11871 case OMPC_shared:
11872 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011873 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011874 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011875 case OMPC_linear:
11876 case OMPC_aligned:
11877 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011878 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011879 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011880 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011881 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011882 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011883 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011884 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011885 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011886 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011887 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011888 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011889 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011890 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011891 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011892 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011893 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011894 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011895 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011896 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011897 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011898 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011899 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011900 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011901 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011902 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011903 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011904 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011905 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011906 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011907 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011908 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011909 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011910 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011911 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011912 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011913 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011914 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011915 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011916 llvm_unreachable("Clause is not allowed.");
11917 }
11918 return Res;
11919}
11920
Alexey Bataev6402bca2015-12-28 07:25:51 +000011921static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11922 OpenMPScheduleClauseModifier M2,
11923 SourceLocation M1Loc, SourceLocation M2Loc) {
11924 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11925 SmallVector<unsigned, 2> Excluded;
11926 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11927 Excluded.push_back(M2);
11928 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11929 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11930 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11931 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11932 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11933 << getListOfPossibleValues(OMPC_schedule,
11934 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11935 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11936 Excluded)
11937 << getOpenMPClauseName(OMPC_schedule);
11938 return true;
11939 }
11940 return false;
11941}
11942
Alexey Bataev56dafe82014-06-20 07:16:17 +000011943OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011944 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011945 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011946 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11947 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11948 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11949 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11950 return nullptr;
11951 // OpenMP, 2.7.1, Loop Construct, Restrictions
11952 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11953 // but not both.
11954 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11955 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11956 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11957 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11958 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11959 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11960 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11961 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11962 return nullptr;
11963 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011964 if (Kind == OMPC_SCHEDULE_unknown) {
11965 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011966 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11967 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11968 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11969 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11970 Exclude);
11971 } else {
11972 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11973 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011974 }
11975 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11976 << Values << getOpenMPClauseName(OMPC_schedule);
11977 return nullptr;
11978 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011979 // OpenMP, 2.7.1, Loop Construct, Restrictions
11980 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11981 // schedule(guided).
11982 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11983 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11984 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11985 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11986 diag::err_omp_schedule_nonmonotonic_static);
11987 return nullptr;
11988 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011989 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011990 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011991 if (ChunkSize) {
11992 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11993 !ChunkSize->isInstantiationDependent() &&
11994 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011995 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011996 ExprResult Val =
11997 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11998 if (Val.isInvalid())
11999 return nullptr;
12000
12001 ValExpr = Val.get();
12002
12003 // OpenMP [2.7.1, Restrictions]
12004 // chunk_size must be a loop invariant integer expression with a positive
12005 // value.
12006 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012007 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12008 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12009 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012010 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012011 return nullptr;
12012 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012013 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012014 DSAStack->getCurrentDirective(), OMPC_schedule,
12015 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012016 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012017 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012018 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012019 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12020 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012021 }
12022 }
12023 }
12024
Alexey Bataev6402bca2015-12-28 07:25:51 +000012025 return new (Context)
12026 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012027 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012028}
12029
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012030OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12031 SourceLocation StartLoc,
12032 SourceLocation EndLoc) {
12033 OMPClause *Res = nullptr;
12034 switch (Kind) {
12035 case OMPC_ordered:
12036 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12037 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012038 case OMPC_nowait:
12039 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12040 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012041 case OMPC_untied:
12042 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12043 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012044 case OMPC_mergeable:
12045 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12046 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012047 case OMPC_read:
12048 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12049 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012050 case OMPC_write:
12051 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12052 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012053 case OMPC_update:
12054 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12055 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012056 case OMPC_capture:
12057 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12058 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012059 case OMPC_seq_cst:
12060 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12061 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012062 case OMPC_threads:
12063 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12064 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012065 case OMPC_simd:
12066 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12067 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012068 case OMPC_nogroup:
12069 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12070 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012071 case OMPC_unified_address:
12072 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12073 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012074 case OMPC_unified_shared_memory:
12075 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12076 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012077 case OMPC_reverse_offload:
12078 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12079 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012080 case OMPC_dynamic_allocators:
12081 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12082 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012083 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012084 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012085 case OMPC_num_threads:
12086 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012087 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012088 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012089 case OMPC_collapse:
12090 case OMPC_schedule:
12091 case OMPC_private:
12092 case OMPC_firstprivate:
12093 case OMPC_lastprivate:
12094 case OMPC_shared:
12095 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012096 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012097 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012098 case OMPC_linear:
12099 case OMPC_aligned:
12100 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012101 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012102 case OMPC_default:
12103 case OMPC_proc_bind:
12104 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012105 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012106 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012107 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012108 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012109 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012110 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012111 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012112 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012113 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012114 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012115 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012116 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012117 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012118 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012119 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012120 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012121 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012122 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012123 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012124 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012125 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012126 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012127 llvm_unreachable("Clause is not allowed.");
12128 }
12129 return Res;
12130}
12131
Alexey Bataev236070f2014-06-20 11:19:47 +000012132OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12133 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012134 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012135 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12136}
12137
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012138OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12139 SourceLocation EndLoc) {
12140 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12141}
12142
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012143OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12144 SourceLocation EndLoc) {
12145 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12146}
12147
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012148OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12149 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012150 return new (Context) OMPReadClause(StartLoc, EndLoc);
12151}
12152
Alexey Bataevdea47612014-07-23 07:46:59 +000012153OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12154 SourceLocation EndLoc) {
12155 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12156}
12157
Alexey Bataev67a4f222014-07-23 10:25:33 +000012158OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12159 SourceLocation EndLoc) {
12160 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12161}
12162
Alexey Bataev459dec02014-07-24 06:46:57 +000012163OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12164 SourceLocation EndLoc) {
12165 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12166}
12167
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012168OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12169 SourceLocation EndLoc) {
12170 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12171}
12172
Alexey Bataev346265e2015-09-25 10:37:12 +000012173OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12174 SourceLocation EndLoc) {
12175 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12176}
12177
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012178OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12179 SourceLocation EndLoc) {
12180 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12181}
12182
Alexey Bataevb825de12015-12-07 10:51:44 +000012183OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12184 SourceLocation EndLoc) {
12185 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12186}
12187
Kelvin Li1408f912018-09-26 04:28:39 +000012188OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12189 SourceLocation EndLoc) {
12190 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12191}
12192
Patrick Lyster4a370b92018-10-01 13:47:43 +000012193OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12194 SourceLocation EndLoc) {
12195 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12196}
12197
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012198OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12199 SourceLocation EndLoc) {
12200 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12201}
12202
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012203OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12204 SourceLocation EndLoc) {
12205 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12206}
12207
Alexey Bataevc5e02582014-06-16 07:08:35 +000012208OMPClause *Sema::ActOnOpenMPVarListClause(
12209 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012210 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12211 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
12212 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000012213 OpenMPLinearClauseKind LinKind,
12214 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012215 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
12216 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
12217 SourceLocation StartLoc = Locs.StartLoc;
12218 SourceLocation LParenLoc = Locs.LParenLoc;
12219 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012220 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012221 switch (Kind) {
12222 case OMPC_private:
12223 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12224 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012225 case OMPC_firstprivate:
12226 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12227 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012228 case OMPC_lastprivate:
12229 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12230 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012231 case OMPC_shared:
12232 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12233 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012234 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012235 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012236 EndLoc, ReductionOrMapperIdScopeSpec,
12237 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012238 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012239 case OMPC_task_reduction:
12240 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012241 EndLoc, ReductionOrMapperIdScopeSpec,
12242 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012243 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012244 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012245 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12246 EndLoc, ReductionOrMapperIdScopeSpec,
12247 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012248 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012249 case OMPC_linear:
12250 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012251 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012252 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012253 case OMPC_aligned:
12254 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12255 ColonLoc, EndLoc);
12256 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012257 case OMPC_copyin:
12258 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12259 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012260 case OMPC_copyprivate:
12261 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12262 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012263 case OMPC_flush:
12264 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12265 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012266 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000012267 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012268 StartLoc, LParenLoc, EndLoc);
12269 break;
12270 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012271 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
12272 ReductionOrMapperIdScopeSpec,
12273 ReductionOrMapperId, MapType, IsMapTypeImplicit,
12274 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012275 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012276 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012277 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12278 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012279 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012280 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012281 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12282 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012283 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012284 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012285 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012286 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012287 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012288 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012289 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012290 case OMPC_allocate:
12291 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12292 ColonLoc, EndLoc);
12293 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012294 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012295 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012296 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012297 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012298 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012299 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012300 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012301 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012302 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012303 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012304 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012305 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012306 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012307 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012308 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012309 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012310 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012311 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012312 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012313 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012314 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012315 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012316 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012317 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012318 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012319 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012320 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012321 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012322 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012323 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012324 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012325 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012326 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012327 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012328 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012329 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012330 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012331 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012332 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012333 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012334 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012335 llvm_unreachable("Clause is not allowed.");
12336 }
12337 return Res;
12338}
12339
Alexey Bataev90c228f2016-02-08 09:29:13 +000012340ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012341 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012342 ExprResult Res = BuildDeclRefExpr(
12343 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12344 if (!Res.isUsable())
12345 return ExprError();
12346 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12347 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12348 if (!Res.isUsable())
12349 return ExprError();
12350 }
12351 if (VK != VK_LValue && Res.get()->isGLValue()) {
12352 Res = DefaultLvalueConversion(Res.get());
12353 if (!Res.isUsable())
12354 return ExprError();
12355 }
12356 return Res;
12357}
12358
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012359OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12360 SourceLocation StartLoc,
12361 SourceLocation LParenLoc,
12362 SourceLocation EndLoc) {
12363 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012364 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012365 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012366 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012367 SourceLocation ELoc;
12368 SourceRange ERange;
12369 Expr *SimpleRefExpr = RefExpr;
12370 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012371 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012372 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012373 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012374 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012375 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012376 ValueDecl *D = Res.first;
12377 if (!D)
12378 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012379
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012380 QualType Type = D->getType();
12381 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012382
12383 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12384 // A variable that appears in a private clause must not have an incomplete
12385 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012386 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012387 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012388 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012389
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012390 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12391 // A variable that is privatized must not have a const-qualified type
12392 // unless it is of class type with a mutable member. This restriction does
12393 // not apply to the firstprivate clause.
12394 //
12395 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12396 // A variable that appears in a private clause must not have a
12397 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012398 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012399 continue;
12400
Alexey Bataev758e55e2013-09-06 18:03:48 +000012401 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12402 // in a Construct]
12403 // Variables with the predetermined data-sharing attributes may not be
12404 // listed in data-sharing attributes clauses, except for the cases
12405 // listed below. For these exceptions only, listing a predetermined
12406 // variable in a data-sharing attribute clause is allowed and overrides
12407 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012408 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012409 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012410 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12411 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012412 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012413 continue;
12414 }
12415
Alexey Bataeve3727102018-04-18 15:57:46 +000012416 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012417 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012418 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012419 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012420 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12421 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012422 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012423 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012424 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012425 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012426 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012427 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012428 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012429 continue;
12430 }
12431
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012432 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12433 // A list item cannot appear in both a map clause and a data-sharing
12434 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012435 //
12436 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12437 // A list item cannot appear in both a map clause and a data-sharing
12438 // attribute clause on the same construct unless the construct is a
12439 // combined construct.
12440 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12441 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012442 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012443 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012444 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012445 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12446 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12447 ConflictKind = WhereFoundClauseKind;
12448 return true;
12449 })) {
12450 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012451 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012452 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012453 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012454 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012455 continue;
12456 }
12457 }
12458
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012459 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12460 // A variable of class type (or array thereof) that appears in a private
12461 // clause requires an accessible, unambiguous default constructor for the
12462 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012463 // Generate helper private variable and initialize it with the default
12464 // value. The address of the original variable is replaced by the address of
12465 // the new private variable in CodeGen. This new variable is not added to
12466 // IdResolver, so the code in the OpenMP region uses original variable for
12467 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012468 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012469 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012470 buildVarDecl(*this, ELoc, Type, D->getName(),
12471 D->hasAttrs() ? &D->getAttrs() : nullptr,
12472 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012473 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012474 if (VDPrivate->isInvalidDecl())
12475 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012476 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012477 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012478
Alexey Bataev90c228f2016-02-08 09:29:13 +000012479 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012480 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012481 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012482 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012483 Vars.push_back((VD || CurContext->isDependentContext())
12484 ? RefExpr->IgnoreParens()
12485 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012486 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012487 }
12488
Alexey Bataeved09d242014-05-28 05:53:51 +000012489 if (Vars.empty())
12490 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012491
Alexey Bataev03b340a2014-10-21 03:16:40 +000012492 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12493 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012494}
12495
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012496namespace {
12497class DiagsUninitializedSeveretyRAII {
12498private:
12499 DiagnosticsEngine &Diags;
12500 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012501 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012502
12503public:
12504 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12505 bool IsIgnored)
12506 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12507 if (!IsIgnored) {
12508 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12509 /*Map*/ diag::Severity::Ignored, Loc);
12510 }
12511 }
12512 ~DiagsUninitializedSeveretyRAII() {
12513 if (!IsIgnored)
12514 Diags.popMappings(SavedLoc);
12515 }
12516};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012517}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012518
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012519OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12520 SourceLocation StartLoc,
12521 SourceLocation LParenLoc,
12522 SourceLocation EndLoc) {
12523 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012524 SmallVector<Expr *, 8> PrivateCopies;
12525 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012526 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012527 bool IsImplicitClause =
12528 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012529 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012530
Alexey Bataeve3727102018-04-18 15:57:46 +000012531 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012532 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012533 SourceLocation ELoc;
12534 SourceRange ERange;
12535 Expr *SimpleRefExpr = RefExpr;
12536 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012537 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012538 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012539 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012540 PrivateCopies.push_back(nullptr);
12541 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012542 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012543 ValueDecl *D = Res.first;
12544 if (!D)
12545 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012546
Alexey Bataev60da77e2016-02-29 05:54:20 +000012547 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012548 QualType Type = D->getType();
12549 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012550
12551 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12552 // A variable that appears in a private clause must not have an incomplete
12553 // type or a reference type.
12554 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012555 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012556 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012557 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012558
12559 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12560 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012561 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012562 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012563 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012564
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012565 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012566 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012567 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012568 DSAStackTy::DSAVarData DVar =
12569 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012570 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012571 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012572 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012573 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12574 // A list item that specifies a given variable may not appear in more
12575 // than one clause on the same directive, except that a variable may be
12576 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012577 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12578 // A list item may appear in a firstprivate or lastprivate clause but not
12579 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012580 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012581 (isOpenMPDistributeDirective(CurrDir) ||
12582 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012583 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012584 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012585 << getOpenMPClauseName(DVar.CKind)
12586 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012587 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012588 continue;
12589 }
12590
12591 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12592 // in a Construct]
12593 // Variables with the predetermined data-sharing attributes may not be
12594 // listed in data-sharing attributes clauses, except for the cases
12595 // listed below. For these exceptions only, listing a predetermined
12596 // variable in a data-sharing attribute clause is allowed and overrides
12597 // the variable's predetermined data-sharing attributes.
12598 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12599 // in a Construct, C/C++, p.2]
12600 // Variables with const-qualified type having no mutable member may be
12601 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012602 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012603 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12604 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012605 << getOpenMPClauseName(DVar.CKind)
12606 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012607 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012608 continue;
12609 }
12610
12611 // OpenMP [2.9.3.4, Restrictions, p.2]
12612 // A list item that is private within a parallel region must not appear
12613 // in a firstprivate clause on a worksharing construct if any of the
12614 // worksharing regions arising from the worksharing construct ever bind
12615 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012616 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12617 // A list item that is private within a teams region must not appear in a
12618 // firstprivate clause on a distribute construct if any of the distribute
12619 // regions arising from the distribute construct ever bind to any of the
12620 // teams regions arising from the teams construct.
12621 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12622 // A list item that appears in a reduction clause of a teams construct
12623 // must not appear in a firstprivate clause on a distribute construct if
12624 // any of the distribute regions arising from the distribute construct
12625 // ever bind to any of the teams regions arising from the teams construct.
12626 if ((isOpenMPWorksharingDirective(CurrDir) ||
12627 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012628 !isOpenMPParallelDirective(CurrDir) &&
12629 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012630 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012631 if (DVar.CKind != OMPC_shared &&
12632 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012633 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012634 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012635 Diag(ELoc, diag::err_omp_required_access)
12636 << getOpenMPClauseName(OMPC_firstprivate)
12637 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012638 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012639 continue;
12640 }
12641 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012642 // OpenMP [2.9.3.4, Restrictions, p.3]
12643 // A list item that appears in a reduction clause of a parallel construct
12644 // must not appear in a firstprivate clause on a worksharing or task
12645 // construct if any of the worksharing or task regions arising from the
12646 // worksharing or task construct ever bind to any of the parallel regions
12647 // arising from the parallel construct.
12648 // OpenMP [2.9.3.4, Restrictions, p.4]
12649 // A list item that appears in a reduction clause in worksharing
12650 // construct must not appear in a firstprivate clause in a task construct
12651 // encountered during execution of any of the worksharing regions arising
12652 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012653 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012654 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012655 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12656 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012657 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012658 isOpenMPWorksharingDirective(K) ||
12659 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012660 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012661 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012662 if (DVar.CKind == OMPC_reduction &&
12663 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012664 isOpenMPWorksharingDirective(DVar.DKind) ||
12665 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012666 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12667 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012668 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012669 continue;
12670 }
12671 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012672
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012673 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12674 // A list item cannot appear in both a map clause and a data-sharing
12675 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012676 //
12677 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12678 // A list item cannot appear in both a map clause and a data-sharing
12679 // attribute clause on the same construct unless the construct is a
12680 // combined construct.
12681 if ((LangOpts.OpenMP <= 45 &&
12682 isOpenMPTargetExecutionDirective(CurrDir)) ||
12683 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012684 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012685 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012686 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012687 [&ConflictKind](
12688 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12689 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012690 ConflictKind = WhereFoundClauseKind;
12691 return true;
12692 })) {
12693 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012694 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012695 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012696 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012697 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012698 continue;
12699 }
12700 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012701 }
12702
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012703 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012704 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012705 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012706 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12707 << getOpenMPClauseName(OMPC_firstprivate) << Type
12708 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12709 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012710 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012711 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012712 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012713 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012714 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012715 continue;
12716 }
12717
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012718 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012719 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012720 buildVarDecl(*this, ELoc, Type, D->getName(),
12721 D->hasAttrs() ? &D->getAttrs() : nullptr,
12722 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012723 // Generate helper private variable and initialize it with the value of the
12724 // original variable. The address of the original variable is replaced by
12725 // the address of the new private variable in the CodeGen. This new variable
12726 // is not added to IdResolver, so the code in the OpenMP region uses
12727 // original variable for proper diagnostics and variable capturing.
12728 Expr *VDInitRefExpr = nullptr;
12729 // For arrays generate initializer for single element and replace it by the
12730 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012731 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012732 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012733 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012734 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012735 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012736 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012737 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12738 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012739 InitializedEntity Entity =
12740 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012741 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12742
12743 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12744 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12745 if (Result.isInvalid())
12746 VDPrivate->setInvalidDecl();
12747 else
12748 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012749 // Remove temp variable declaration.
12750 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012751 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012752 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12753 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012754 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12755 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012756 AddInitializerToDecl(VDPrivate,
12757 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012758 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012759 }
12760 if (VDPrivate->isInvalidDecl()) {
12761 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012762 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012763 diag::note_omp_task_predetermined_firstprivate_here);
12764 }
12765 continue;
12766 }
12767 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012768 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012769 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12770 RefExpr->getExprLoc());
12771 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012772 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012773 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012774 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012775 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012776 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012777 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012778 ExprCaptures.push_back(Ref->getDecl());
12779 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012780 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012781 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012782 Vars.push_back((VD || CurContext->isDependentContext())
12783 ? RefExpr->IgnoreParens()
12784 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012785 PrivateCopies.push_back(VDPrivateRefExpr);
12786 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012787 }
12788
Alexey Bataeved09d242014-05-28 05:53:51 +000012789 if (Vars.empty())
12790 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012791
12792 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012793 Vars, PrivateCopies, Inits,
12794 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012795}
12796
Alexander Musman1bb328c2014-06-04 13:06:39 +000012797OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12798 SourceLocation StartLoc,
12799 SourceLocation LParenLoc,
12800 SourceLocation EndLoc) {
12801 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012802 SmallVector<Expr *, 8> SrcExprs;
12803 SmallVector<Expr *, 8> DstExprs;
12804 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012805 SmallVector<Decl *, 4> ExprCaptures;
12806 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012807 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012808 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012809 SourceLocation ELoc;
12810 SourceRange ERange;
12811 Expr *SimpleRefExpr = RefExpr;
12812 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012813 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012814 // It will be analyzed later.
12815 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012816 SrcExprs.push_back(nullptr);
12817 DstExprs.push_back(nullptr);
12818 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012819 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012820 ValueDecl *D = Res.first;
12821 if (!D)
12822 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012823
Alexey Bataev74caaf22016-02-20 04:09:36 +000012824 QualType Type = D->getType();
12825 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012826
12827 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12828 // A variable that appears in a lastprivate clause must not have an
12829 // incomplete type or a reference type.
12830 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012831 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012832 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012833 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012834
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012835 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12836 // A variable that is privatized must not have a const-qualified type
12837 // unless it is of class type with a mutable member. This restriction does
12838 // not apply to the firstprivate clause.
12839 //
12840 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12841 // A variable that appears in a lastprivate clause must not have a
12842 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012843 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012844 continue;
12845
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012846 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012847 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12848 // in a Construct]
12849 // Variables with the predetermined data-sharing attributes may not be
12850 // listed in data-sharing attributes clauses, except for the cases
12851 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012852 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12853 // A list item may appear in a firstprivate or lastprivate clause but not
12854 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012855 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012856 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012857 (isOpenMPDistributeDirective(CurrDir) ||
12858 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012859 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12860 Diag(ELoc, diag::err_omp_wrong_dsa)
12861 << getOpenMPClauseName(DVar.CKind)
12862 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012863 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012864 continue;
12865 }
12866
Alexey Bataevf29276e2014-06-18 04:14:57 +000012867 // OpenMP [2.14.3.5, Restrictions, p.2]
12868 // A list item that is private within a parallel region, or that appears in
12869 // the reduction clause of a parallel construct, must not appear in a
12870 // lastprivate clause on a worksharing construct if any of the corresponding
12871 // worksharing regions ever binds to any of the corresponding parallel
12872 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012873 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012874 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012875 !isOpenMPParallelDirective(CurrDir) &&
12876 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012877 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012878 if (DVar.CKind != OMPC_shared) {
12879 Diag(ELoc, diag::err_omp_required_access)
12880 << getOpenMPClauseName(OMPC_lastprivate)
12881 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012882 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012883 continue;
12884 }
12885 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012886
Alexander Musman1bb328c2014-06-04 13:06:39 +000012887 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012888 // A variable of class type (or array thereof) that appears in a
12889 // lastprivate clause requires an accessible, unambiguous default
12890 // constructor for the class type, unless the list item is also specified
12891 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012892 // A variable of class type (or array thereof) that appears in a
12893 // lastprivate clause requires an accessible, unambiguous copy assignment
12894 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012895 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012896 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12897 Type.getUnqualifiedType(), ".lastprivate.src",
12898 D->hasAttrs() ? &D->getAttrs() : nullptr);
12899 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012900 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012901 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012902 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012903 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012904 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012905 // For arrays generate assignment operation for single element and replace
12906 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012907 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12908 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012909 if (AssignmentOp.isInvalid())
12910 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012911 AssignmentOp =
12912 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012913 if (AssignmentOp.isInvalid())
12914 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012915
Alexey Bataev74caaf22016-02-20 04:09:36 +000012916 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012917 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012918 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012919 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012920 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012921 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012922 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012923 ExprCaptures.push_back(Ref->getDecl());
12924 }
12925 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012926 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012927 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012928 ExprResult RefRes = DefaultLvalueConversion(Ref);
12929 if (!RefRes.isUsable())
12930 continue;
12931 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012932 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12933 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012934 if (!PostUpdateRes.isUsable())
12935 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012936 ExprPostUpdates.push_back(
12937 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012938 }
12939 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012940 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012941 Vars.push_back((VD || CurContext->isDependentContext())
12942 ? RefExpr->IgnoreParens()
12943 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012944 SrcExprs.push_back(PseudoSrcExpr);
12945 DstExprs.push_back(PseudoDstExpr);
12946 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012947 }
12948
12949 if (Vars.empty())
12950 return nullptr;
12951
12952 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012953 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012954 buildPreInits(Context, ExprCaptures),
12955 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012956}
12957
Alexey Bataev758e55e2013-09-06 18:03:48 +000012958OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12959 SourceLocation StartLoc,
12960 SourceLocation LParenLoc,
12961 SourceLocation EndLoc) {
12962 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012963 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012964 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012965 SourceLocation ELoc;
12966 SourceRange ERange;
12967 Expr *SimpleRefExpr = RefExpr;
12968 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012969 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012970 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012971 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012972 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012973 ValueDecl *D = Res.first;
12974 if (!D)
12975 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012976
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012977 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012978 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12979 // in a Construct]
12980 // Variables with the predetermined data-sharing attributes may not be
12981 // listed in data-sharing attributes clauses, except for the cases
12982 // listed below. For these exceptions only, listing a predetermined
12983 // variable in a data-sharing attribute clause is allowed and overrides
12984 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012985 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012986 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12987 DVar.RefExpr) {
12988 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12989 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012990 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012991 continue;
12992 }
12993
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012994 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012995 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012996 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012997 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012998 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12999 ? RefExpr->IgnoreParens()
13000 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013001 }
13002
Alexey Bataeved09d242014-05-28 05:53:51 +000013003 if (Vars.empty())
13004 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013005
13006 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13007}
13008
Alexey Bataevc5e02582014-06-16 07:08:35 +000013009namespace {
13010class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13011 DSAStackTy *Stack;
13012
13013public:
13014 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013015 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13016 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013017 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13018 return false;
13019 if (DVar.CKind != OMPC_unknown)
13020 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013021 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013022 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013023 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013025 }
13026 return false;
13027 }
13028 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013029 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013030 if (Child && Visit(Child))
13031 return true;
13032 }
13033 return false;
13034 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013035 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013036};
Alexey Bataev23b69422014-06-18 07:08:49 +000013037} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013038
Alexey Bataev60da77e2016-02-29 05:54:20 +000013039namespace {
13040// Transform MemberExpression for specified FieldDecl of current class to
13041// DeclRefExpr to specified OMPCapturedExprDecl.
13042class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13043 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013044 ValueDecl *Field = nullptr;
13045 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013046
13047public:
13048 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13049 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13050
13051 ExprResult TransformMemberExpr(MemberExpr *E) {
13052 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13053 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013054 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013055 return CapturedExpr;
13056 }
13057 return BaseTransform::TransformMemberExpr(E);
13058 }
13059 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13060};
13061} // namespace
13062
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013063template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013064static T filterLookupForUDReductionAndMapper(
13065 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013066 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013067 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013068 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013069 return Res;
13070 }
13071 }
13072 return T();
13073}
13074
Alexey Bataev43b90b72018-09-12 16:31:59 +000013075static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13076 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13077
13078 for (auto RD : D->redecls()) {
13079 // Don't bother with extra checks if we already know this one isn't visible.
13080 if (RD == D)
13081 continue;
13082
13083 auto ND = cast<NamedDecl>(RD);
13084 if (LookupResult::isVisible(SemaRef, ND))
13085 return ND;
13086 }
13087
13088 return nullptr;
13089}
13090
13091static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013092argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013093 SourceLocation Loc, QualType Ty,
13094 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13095 // Find all of the associated namespaces and classes based on the
13096 // arguments we have.
13097 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13098 Sema::AssociatedClassSet AssociatedClasses;
13099 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13100 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13101 AssociatedClasses);
13102
13103 // C++ [basic.lookup.argdep]p3:
13104 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13105 // and let Y be the lookup set produced by argument dependent
13106 // lookup (defined as follows). If X contains [...] then Y is
13107 // empty. Otherwise Y is the set of declarations found in the
13108 // namespaces associated with the argument types as described
13109 // below. The set of declarations found by the lookup of the name
13110 // is the union of X and Y.
13111 //
13112 // Here, we compute Y and add its members to the overloaded
13113 // candidate set.
13114 for (auto *NS : AssociatedNamespaces) {
13115 // When considering an associated namespace, the lookup is the
13116 // same as the lookup performed when the associated namespace is
13117 // used as a qualifier (3.4.3.2) except that:
13118 //
13119 // -- Any using-directives in the associated namespace are
13120 // ignored.
13121 //
13122 // -- Any namespace-scope friend functions declared in
13123 // associated classes are visible within their respective
13124 // namespaces even if they are not visible during an ordinary
13125 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013126 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013127 for (auto *D : R) {
13128 auto *Underlying = D;
13129 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13130 Underlying = USD->getTargetDecl();
13131
Michael Kruse4304e9d2019-02-19 16:38:20 +000013132 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13133 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013134 continue;
13135
13136 if (!SemaRef.isVisible(D)) {
13137 D = findAcceptableDecl(SemaRef, D);
13138 if (!D)
13139 continue;
13140 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13141 Underlying = USD->getTargetDecl();
13142 }
13143 Lookups.emplace_back();
13144 Lookups.back().addDecl(Underlying);
13145 }
13146 }
13147}
13148
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013149static ExprResult
13150buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13151 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13152 const DeclarationNameInfo &ReductionId, QualType Ty,
13153 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13154 if (ReductionIdScopeSpec.isInvalid())
13155 return ExprError();
13156 SmallVector<UnresolvedSet<8>, 4> Lookups;
13157 if (S) {
13158 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13159 Lookup.suppressDiagnostics();
13160 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013161 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013162 do {
13163 S = S->getParent();
13164 } while (S && !S->isDeclScope(D));
13165 if (S)
13166 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013167 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013168 Lookups.back().append(Lookup.begin(), Lookup.end());
13169 Lookup.clear();
13170 }
13171 } else if (auto *ULE =
13172 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13173 Lookups.push_back(UnresolvedSet<8>());
13174 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013175 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013176 if (D == PrevD)
13177 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013178 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013179 Lookups.back().addDecl(DRD);
13180 PrevD = D;
13181 }
13182 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013183 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13184 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013185 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013186 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013187 return !D->isInvalidDecl() &&
13188 (D->getType()->isDependentType() ||
13189 D->getType()->isInstantiationDependentType() ||
13190 D->getType()->containsUnexpandedParameterPack());
13191 })) {
13192 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013193 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013194 if (Set.empty())
13195 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013196 ResSet.append(Set.begin(), Set.end());
13197 // The last item marks the end of all declarations at the specified scope.
13198 ResSet.addDecl(Set[Set.size() - 1]);
13199 }
13200 return UnresolvedLookupExpr::Create(
13201 SemaRef.Context, /*NamingClass=*/nullptr,
13202 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13203 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13204 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013205 // Lookup inside the classes.
13206 // C++ [over.match.oper]p3:
13207 // For a unary operator @ with an operand of a type whose
13208 // cv-unqualified version is T1, and for a binary operator @ with
13209 // a left operand of a type whose cv-unqualified version is T1 and
13210 // a right operand of a type whose cv-unqualified version is T2,
13211 // three sets of candidate functions, designated member
13212 // candidates, non-member candidates and built-in candidates, are
13213 // constructed as follows:
13214 // -- If T1 is a complete class type or a class currently being
13215 // defined, the set of member candidates is the result of the
13216 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13217 // the set of member candidates is empty.
13218 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13219 Lookup.suppressDiagnostics();
13220 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13221 // Complete the type if it can be completed.
13222 // If the type is neither complete nor being defined, bail out now.
13223 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13224 TyRec->getDecl()->getDefinition()) {
13225 Lookup.clear();
13226 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13227 if (Lookup.empty()) {
13228 Lookups.emplace_back();
13229 Lookups.back().append(Lookup.begin(), Lookup.end());
13230 }
13231 }
13232 }
13233 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013234 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013235 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013236 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13237 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13238 if (!D->isInvalidDecl() &&
13239 SemaRef.Context.hasSameType(D->getType(), Ty))
13240 return D;
13241 return nullptr;
13242 }))
13243 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13244 VK_LValue, Loc);
13245 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013246 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13247 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13248 if (!D->isInvalidDecl() &&
13249 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13250 !Ty.isMoreQualifiedThan(D->getType()))
13251 return D;
13252 return nullptr;
13253 })) {
13254 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13255 /*DetectVirtual=*/false);
13256 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13257 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13258 VD->getType().getUnqualifiedType()))) {
13259 if (SemaRef.CheckBaseClassAccess(
13260 Loc, VD->getType(), Ty, Paths.front(),
13261 /*DiagID=*/0) != Sema::AR_inaccessible) {
13262 SemaRef.BuildBasePathArray(Paths, BasePath);
13263 return SemaRef.BuildDeclRefExpr(
13264 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13265 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013266 }
13267 }
13268 }
13269 }
13270 if (ReductionIdScopeSpec.isSet()) {
13271 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13272 return ExprError();
13273 }
13274 return ExprEmpty();
13275}
13276
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013277namespace {
13278/// Data for the reduction-based clauses.
13279struct ReductionData {
13280 /// List of original reduction items.
13281 SmallVector<Expr *, 8> Vars;
13282 /// List of private copies of the reduction items.
13283 SmallVector<Expr *, 8> Privates;
13284 /// LHS expressions for the reduction_op expressions.
13285 SmallVector<Expr *, 8> LHSs;
13286 /// RHS expressions for the reduction_op expressions.
13287 SmallVector<Expr *, 8> RHSs;
13288 /// Reduction operation expression.
13289 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013290 /// Taskgroup descriptors for the corresponding reduction items in
13291 /// in_reduction clauses.
13292 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013293 /// List of captures for clause.
13294 SmallVector<Decl *, 4> ExprCaptures;
13295 /// List of postupdate expressions.
13296 SmallVector<Expr *, 4> ExprPostUpdates;
13297 ReductionData() = delete;
13298 /// Reserves required memory for the reduction data.
13299 ReductionData(unsigned Size) {
13300 Vars.reserve(Size);
13301 Privates.reserve(Size);
13302 LHSs.reserve(Size);
13303 RHSs.reserve(Size);
13304 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013305 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013306 ExprCaptures.reserve(Size);
13307 ExprPostUpdates.reserve(Size);
13308 }
13309 /// Stores reduction item and reduction operation only (required for dependent
13310 /// reduction item).
13311 void push(Expr *Item, Expr *ReductionOp) {
13312 Vars.emplace_back(Item);
13313 Privates.emplace_back(nullptr);
13314 LHSs.emplace_back(nullptr);
13315 RHSs.emplace_back(nullptr);
13316 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013317 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013318 }
13319 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013320 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13321 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013322 Vars.emplace_back(Item);
13323 Privates.emplace_back(Private);
13324 LHSs.emplace_back(LHS);
13325 RHSs.emplace_back(RHS);
13326 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013327 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013328 }
13329};
13330} // namespace
13331
Alexey Bataeve3727102018-04-18 15:57:46 +000013332static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013333 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13334 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13335 const Expr *Length = OASE->getLength();
13336 if (Length == nullptr) {
13337 // For array sections of the form [1:] or [:], we would need to analyze
13338 // the lower bound...
13339 if (OASE->getColonLoc().isValid())
13340 return false;
13341
13342 // This is an array subscript which has implicit length 1!
13343 SingleElement = true;
13344 ArraySizes.push_back(llvm::APSInt::get(1));
13345 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013346 Expr::EvalResult Result;
13347 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013348 return false;
13349
Fangrui Song407659a2018-11-30 23:41:18 +000013350 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013351 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13352 ArraySizes.push_back(ConstantLengthValue);
13353 }
13354
13355 // Get the base of this array section and walk up from there.
13356 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13357
13358 // We require length = 1 for all array sections except the right-most to
13359 // guarantee that the memory region is contiguous and has no holes in it.
13360 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13361 Length = TempOASE->getLength();
13362 if (Length == nullptr) {
13363 // For array sections of the form [1:] or [:], we would need to analyze
13364 // the lower bound...
13365 if (OASE->getColonLoc().isValid())
13366 return false;
13367
13368 // This is an array subscript which has implicit length 1!
13369 ArraySizes.push_back(llvm::APSInt::get(1));
13370 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013371 Expr::EvalResult Result;
13372 if (!Length->EvaluateAsInt(Result, Context))
13373 return false;
13374
13375 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13376 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013377 return false;
13378
13379 ArraySizes.push_back(ConstantLengthValue);
13380 }
13381 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13382 }
13383
13384 // If we have a single element, we don't need to add the implicit lengths.
13385 if (!SingleElement) {
13386 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13387 // Has implicit length 1!
13388 ArraySizes.push_back(llvm::APSInt::get(1));
13389 Base = TempASE->getBase()->IgnoreParenImpCasts();
13390 }
13391 }
13392
13393 // This array section can be privatized as a single value or as a constant
13394 // sized array.
13395 return true;
13396}
13397
Alexey Bataeve3727102018-04-18 15:57:46 +000013398static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013399 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13400 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13401 SourceLocation ColonLoc, SourceLocation EndLoc,
13402 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013403 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013404 DeclarationName DN = ReductionId.getName();
13405 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013406 BinaryOperatorKind BOK = BO_Comma;
13407
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013408 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013409 // OpenMP [2.14.3.6, reduction clause]
13410 // C
13411 // reduction-identifier is either an identifier or one of the following
13412 // operators: +, -, *, &, |, ^, && and ||
13413 // C++
13414 // reduction-identifier is either an id-expression or one of the following
13415 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013416 switch (OOK) {
13417 case OO_Plus:
13418 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013419 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013420 break;
13421 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013422 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013423 break;
13424 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013425 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013426 break;
13427 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013428 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013429 break;
13430 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013431 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013432 break;
13433 case OO_AmpAmp:
13434 BOK = BO_LAnd;
13435 break;
13436 case OO_PipePipe:
13437 BOK = BO_LOr;
13438 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013439 case OO_New:
13440 case OO_Delete:
13441 case OO_Array_New:
13442 case OO_Array_Delete:
13443 case OO_Slash:
13444 case OO_Percent:
13445 case OO_Tilde:
13446 case OO_Exclaim:
13447 case OO_Equal:
13448 case OO_Less:
13449 case OO_Greater:
13450 case OO_LessEqual:
13451 case OO_GreaterEqual:
13452 case OO_PlusEqual:
13453 case OO_MinusEqual:
13454 case OO_StarEqual:
13455 case OO_SlashEqual:
13456 case OO_PercentEqual:
13457 case OO_CaretEqual:
13458 case OO_AmpEqual:
13459 case OO_PipeEqual:
13460 case OO_LessLess:
13461 case OO_GreaterGreater:
13462 case OO_LessLessEqual:
13463 case OO_GreaterGreaterEqual:
13464 case OO_EqualEqual:
13465 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013466 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013467 case OO_PlusPlus:
13468 case OO_MinusMinus:
13469 case OO_Comma:
13470 case OO_ArrowStar:
13471 case OO_Arrow:
13472 case OO_Call:
13473 case OO_Subscript:
13474 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013475 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013476 case NUM_OVERLOADED_OPERATORS:
13477 llvm_unreachable("Unexpected reduction identifier");
13478 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013479 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013480 if (II->isStr("max"))
13481 BOK = BO_GT;
13482 else if (II->isStr("min"))
13483 BOK = BO_LT;
13484 }
13485 break;
13486 }
13487 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013488 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013489 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013490 else
13491 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013492 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013493
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013494 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13495 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013496 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013497 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013498 // OpenMP [2.1, C/C++]
13499 // A list item is a variable or array section, subject to the restrictions
13500 // specified in Section 2.4 on page 42 and in each of the sections
13501 // describing clauses and directives for which a list appears.
13502 // OpenMP [2.14.3.3, Restrictions, p.1]
13503 // A variable that is part of another variable (as an array or
13504 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013505 if (!FirstIter && IR != ER)
13506 ++IR;
13507 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013508 SourceLocation ELoc;
13509 SourceRange ERange;
13510 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013511 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013512 /*AllowArraySection=*/true);
13513 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013514 // Try to find 'declare reduction' corresponding construct before using
13515 // builtin/overloaded operators.
13516 QualType Type = Context.DependentTy;
13517 CXXCastPath BasePath;
13518 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013519 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013520 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013521 Expr *ReductionOp = nullptr;
13522 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013523 (DeclareReductionRef.isUnset() ||
13524 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013525 ReductionOp = DeclareReductionRef.get();
13526 // It will be analyzed later.
13527 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013528 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013529 ValueDecl *D = Res.first;
13530 if (!D)
13531 continue;
13532
Alexey Bataev88202be2017-07-27 13:20:36 +000013533 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013534 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013535 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13536 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013537 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013538 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013539 } else if (OASE) {
13540 QualType BaseType =
13541 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13542 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013543 Type = ATy->getElementType();
13544 else
13545 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013546 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013547 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013548 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013549 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013550 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013551
Alexey Bataevc5e02582014-06-16 07:08:35 +000013552 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13553 // A variable that appears in a private clause must not have an incomplete
13554 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013555 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013556 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013557 continue;
13558 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013559 // A list item that appears in a reduction clause must not be
13560 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013561 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13562 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013563 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013564
13565 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013566 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13567 // If a list-item is a reference type then it must bind to the same object
13568 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013569 if (!ASE && !OASE) {
13570 if (VD) {
13571 VarDecl *VDDef = VD->getDefinition();
13572 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13573 DSARefChecker Check(Stack);
13574 if (Check.Visit(VDDef->getInit())) {
13575 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13576 << getOpenMPClauseName(ClauseKind) << ERange;
13577 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13578 continue;
13579 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013580 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013581 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013582
Alexey Bataevbc529672018-09-28 19:33:14 +000013583 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13584 // in a Construct]
13585 // Variables with the predetermined data-sharing attributes may not be
13586 // listed in data-sharing attributes clauses, except for the cases
13587 // listed below. For these exceptions only, listing a predetermined
13588 // variable in a data-sharing attribute clause is allowed and overrides
13589 // the variable's predetermined data-sharing attributes.
13590 // OpenMP [2.14.3.6, Restrictions, p.3]
13591 // Any number of reduction clauses can be specified on the directive,
13592 // but a list item can appear only once in the reduction clauses for that
13593 // directive.
13594 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13595 if (DVar.CKind == OMPC_reduction) {
13596 S.Diag(ELoc, diag::err_omp_once_referenced)
13597 << getOpenMPClauseName(ClauseKind);
13598 if (DVar.RefExpr)
13599 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13600 continue;
13601 }
13602 if (DVar.CKind != OMPC_unknown) {
13603 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13604 << getOpenMPClauseName(DVar.CKind)
13605 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013606 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013607 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013608 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013609
13610 // OpenMP [2.14.3.6, Restrictions, p.1]
13611 // A list item that appears in a reduction clause of a worksharing
13612 // construct must be shared in the parallel regions to which any of the
13613 // worksharing regions arising from the worksharing construct bind.
13614 if (isOpenMPWorksharingDirective(CurrDir) &&
13615 !isOpenMPParallelDirective(CurrDir) &&
13616 !isOpenMPTeamsDirective(CurrDir)) {
13617 DVar = Stack->getImplicitDSA(D, true);
13618 if (DVar.CKind != OMPC_shared) {
13619 S.Diag(ELoc, diag::err_omp_required_access)
13620 << getOpenMPClauseName(OMPC_reduction)
13621 << getOpenMPClauseName(OMPC_shared);
13622 reportOriginalDsa(S, Stack, D, DVar);
13623 continue;
13624 }
13625 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013626 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013627
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013628 // Try to find 'declare reduction' corresponding construct before using
13629 // builtin/overloaded operators.
13630 CXXCastPath BasePath;
13631 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013632 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013633 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13634 if (DeclareReductionRef.isInvalid())
13635 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013636 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013637 (DeclareReductionRef.isUnset() ||
13638 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013639 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013640 continue;
13641 }
13642 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13643 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013644 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013645 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013646 << Type << ReductionIdRange;
13647 continue;
13648 }
13649
13650 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13651 // The type of a list item that appears in a reduction clause must be valid
13652 // for the reduction-identifier. For a max or min reduction in C, the type
13653 // of the list item must be an allowed arithmetic data type: char, int,
13654 // float, double, or _Bool, possibly modified with long, short, signed, or
13655 // unsigned. For a max or min reduction in C++, the type of the list item
13656 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13657 // double, or bool, possibly modified with long, short, signed, or unsigned.
13658 if (DeclareReductionRef.isUnset()) {
13659 if ((BOK == BO_GT || BOK == BO_LT) &&
13660 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013661 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13662 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013663 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013664 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013665 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13666 VarDecl::DeclarationOnly;
13667 S.Diag(D->getLocation(),
13668 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013669 << D;
13670 }
13671 continue;
13672 }
13673 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013674 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013675 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13676 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013677 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013678 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13679 VarDecl::DeclarationOnly;
13680 S.Diag(D->getLocation(),
13681 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013682 << D;
13683 }
13684 continue;
13685 }
13686 }
13687
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013688 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013689 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13690 D->hasAttrs() ? &D->getAttrs() : nullptr);
13691 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13692 D->hasAttrs() ? &D->getAttrs() : nullptr);
13693 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013694
13695 // Try if we can determine constant lengths for all array sections and avoid
13696 // the VLA.
13697 bool ConstantLengthOASE = false;
13698 if (OASE) {
13699 bool SingleElement;
13700 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013701 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013702 Context, OASE, SingleElement, ArraySizes);
13703
13704 // If we don't have a single element, we must emit a constant array type.
13705 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013706 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013707 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13708 ArrayType::Normal,
13709 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013710 }
13711 }
13712
13713 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013714 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013715 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013716 if (!Context.getTargetInfo().isVLASupported()) {
13717 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13718 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13719 S.Diag(ELoc, diag::note_vla_unsupported);
13720 } else {
13721 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13722 S.targetDiag(ELoc, diag::note_vla_unsupported);
13723 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013724 continue;
13725 }
David Majnemer9d168222016-08-05 17:44:54 +000013726 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013727 // Create pseudo array type for private copy. The size for this array will
13728 // be generated during codegen.
13729 // For array subscripts or single variables Private Ty is the same as Type
13730 // (type of the variable or single array element).
13731 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013732 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013733 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013734 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013735 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013736 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013737 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013738 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013739 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013740 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013741 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13742 D->hasAttrs() ? &D->getAttrs() : nullptr,
13743 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013744 // Add initializer for private variable.
13745 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013746 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13747 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013748 if (DeclareReductionRef.isUsable()) {
13749 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13750 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13751 if (DRD->getInitializer()) {
13752 Init = DRDRef;
13753 RHSVD->setInit(DRDRef);
13754 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013755 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013756 } else {
13757 switch (BOK) {
13758 case BO_Add:
13759 case BO_Xor:
13760 case BO_Or:
13761 case BO_LOr:
13762 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13763 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013764 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013765 break;
13766 case BO_Mul:
13767 case BO_LAnd:
13768 if (Type->isScalarType() || Type->isAnyComplexType()) {
13769 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013770 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013771 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013772 break;
13773 case BO_And: {
13774 // '&' reduction op - initializer is '~0'.
13775 QualType OrigType = Type;
13776 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13777 Type = ComplexTy->getElementType();
13778 if (Type->isRealFloatingType()) {
13779 llvm::APFloat InitValue =
13780 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13781 /*isIEEE=*/true);
13782 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13783 Type, ELoc);
13784 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013785 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013786 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13787 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13788 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13789 }
13790 if (Init && OrigType->isAnyComplexType()) {
13791 // Init = 0xFFFF + 0xFFFFi;
13792 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013793 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013794 }
13795 Type = OrigType;
13796 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013797 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013798 case BO_LT:
13799 case BO_GT: {
13800 // 'min' reduction op - initializer is 'Largest representable number in
13801 // the reduction list item type'.
13802 // 'max' reduction op - initializer is 'Least representable number in
13803 // the reduction list item type'.
13804 if (Type->isIntegerType() || Type->isPointerType()) {
13805 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013806 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013807 QualType IntTy =
13808 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13809 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013810 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13811 : llvm::APInt::getMinValue(Size)
13812 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13813 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013814 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13815 if (Type->isPointerType()) {
13816 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013817 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013818 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013819 if (CastExpr.isInvalid())
13820 continue;
13821 Init = CastExpr.get();
13822 }
13823 } else if (Type->isRealFloatingType()) {
13824 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13825 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13826 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13827 Type, ELoc);
13828 }
13829 break;
13830 }
13831 case BO_PtrMemD:
13832 case BO_PtrMemI:
13833 case BO_MulAssign:
13834 case BO_Div:
13835 case BO_Rem:
13836 case BO_Sub:
13837 case BO_Shl:
13838 case BO_Shr:
13839 case BO_LE:
13840 case BO_GE:
13841 case BO_EQ:
13842 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013843 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013844 case BO_AndAssign:
13845 case BO_XorAssign:
13846 case BO_OrAssign:
13847 case BO_Assign:
13848 case BO_AddAssign:
13849 case BO_SubAssign:
13850 case BO_DivAssign:
13851 case BO_RemAssign:
13852 case BO_ShlAssign:
13853 case BO_ShrAssign:
13854 case BO_Comma:
13855 llvm_unreachable("Unexpected reduction operation");
13856 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013857 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013858 if (Init && DeclareReductionRef.isUnset())
13859 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13860 else if (!Init)
13861 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013862 if (RHSVD->isInvalidDecl())
13863 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013864 if (!RHSVD->hasInit() &&
13865 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013866 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13867 << Type << ReductionIdRange;
13868 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13869 VarDecl::DeclarationOnly;
13870 S.Diag(D->getLocation(),
13871 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013872 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013873 continue;
13874 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013875 // Store initializer for single element in private copy. Will be used during
13876 // codegen.
13877 PrivateVD->setInit(RHSVD->getInit());
13878 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013879 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013880 ExprResult ReductionOp;
13881 if (DeclareReductionRef.isUsable()) {
13882 QualType RedTy = DeclareReductionRef.get()->getType();
13883 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013884 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13885 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013886 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013887 LHS = S.DefaultLvalueConversion(LHS.get());
13888 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013889 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13890 CK_UncheckedDerivedToBase, LHS.get(),
13891 &BasePath, LHS.get()->getValueKind());
13892 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13893 CK_UncheckedDerivedToBase, RHS.get(),
13894 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013895 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013896 FunctionProtoType::ExtProtoInfo EPI;
13897 QualType Params[] = {PtrRedTy, PtrRedTy};
13898 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13899 auto *OVE = new (Context) OpaqueValueExpr(
13900 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013901 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013902 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013903 ReductionOp =
13904 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013905 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013906 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013907 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013908 if (ReductionOp.isUsable()) {
13909 if (BOK != BO_LT && BOK != BO_GT) {
13910 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013911 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013912 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013913 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013914 auto *ConditionalOp = new (Context)
13915 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13916 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013917 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, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013920 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013921 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013922 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13923 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013924 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013925 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013926 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013927 }
13928
Alexey Bataevfa312f32017-07-21 18:48:21 +000013929 // OpenMP [2.15.4.6, Restrictions, p.2]
13930 // A list item that appears in an in_reduction clause of a task construct
13931 // must appear in a task_reduction clause of a construct associated with a
13932 // taskgroup region that includes the participating task in its taskgroup
13933 // set. The construct associated with the innermost region that meets this
13934 // condition must specify the same reduction-identifier as the in_reduction
13935 // clause.
13936 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013937 SourceRange ParentSR;
13938 BinaryOperatorKind ParentBOK;
13939 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013940 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013941 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013942 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13943 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013944 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013945 Stack->getTopMostTaskgroupReductionData(
13946 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013947 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13948 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13949 if (!IsParentBOK && !IsParentReductionOp) {
13950 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13951 continue;
13952 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013953 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13954 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13955 IsParentReductionOp) {
13956 bool EmitError = true;
13957 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13958 llvm::FoldingSetNodeID RedId, ParentRedId;
13959 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13960 DeclareReductionRef.get()->Profile(RedId, Context,
13961 /*Canonical=*/true);
13962 EmitError = RedId != ParentRedId;
13963 }
13964 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013965 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013966 diag::err_omp_reduction_identifier_mismatch)
13967 << ReductionIdRange << RefExpr->getSourceRange();
13968 S.Diag(ParentSR.getBegin(),
13969 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013970 << ParentSR
13971 << (IsParentBOK ? ParentBOKDSA.RefExpr
13972 : ParentReductionOpDSA.RefExpr)
13973 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013974 continue;
13975 }
13976 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013977 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13978 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013979 }
13980
Alexey Bataev60da77e2016-02-29 05:54:20 +000013981 DeclRefExpr *Ref = nullptr;
13982 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013983 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013984 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013985 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013986 VarsExpr =
13987 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13988 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013989 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013990 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013991 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013992 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013993 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013994 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013995 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013996 if (!RefRes.isUsable())
13997 continue;
13998 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013999 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14000 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014001 if (!PostUpdateRes.isUsable())
14002 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014003 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14004 Stack->getCurrentDirective() == OMPD_taskgroup) {
14005 S.Diag(RefExpr->getExprLoc(),
14006 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014007 << RefExpr->getSourceRange();
14008 continue;
14009 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014010 RD.ExprPostUpdates.emplace_back(
14011 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014012 }
14013 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014014 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014015 // All reduction items are still marked as reduction (to do not increase
14016 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014017 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014018 if (CurrDir == OMPD_taskgroup) {
14019 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014020 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14021 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014022 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014023 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014024 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014025 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14026 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014027 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014028 return RD.Vars.empty();
14029}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014030
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014031OMPClause *Sema::ActOnOpenMPReductionClause(
14032 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14033 SourceLocation ColonLoc, SourceLocation EndLoc,
14034 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14035 ArrayRef<Expr *> UnresolvedReductions) {
14036 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014037 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014038 StartLoc, LParenLoc, ColonLoc, EndLoc,
14039 ReductionIdScopeSpec, ReductionId,
14040 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014041 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014042
Alexey Bataevc5e02582014-06-16 07:08:35 +000014043 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014044 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14045 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14046 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14047 buildPreInits(Context, RD.ExprCaptures),
14048 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014049}
14050
Alexey Bataev169d96a2017-07-18 20:17:46 +000014051OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14052 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14053 SourceLocation ColonLoc, SourceLocation EndLoc,
14054 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14055 ArrayRef<Expr *> UnresolvedReductions) {
14056 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014057 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14058 StartLoc, LParenLoc, ColonLoc, EndLoc,
14059 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014060 UnresolvedReductions, RD))
14061 return nullptr;
14062
14063 return OMPTaskReductionClause::Create(
14064 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14065 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14066 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14067 buildPreInits(Context, RD.ExprCaptures),
14068 buildPostUpdate(*this, RD.ExprPostUpdates));
14069}
14070
Alexey Bataevfa312f32017-07-21 18:48:21 +000014071OMPClause *Sema::ActOnOpenMPInReductionClause(
14072 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14073 SourceLocation ColonLoc, SourceLocation EndLoc,
14074 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14075 ArrayRef<Expr *> UnresolvedReductions) {
14076 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014077 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014078 StartLoc, LParenLoc, ColonLoc, EndLoc,
14079 ReductionIdScopeSpec, ReductionId,
14080 UnresolvedReductions, RD))
14081 return nullptr;
14082
14083 return OMPInReductionClause::Create(
14084 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14085 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014086 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014087 buildPreInits(Context, RD.ExprCaptures),
14088 buildPostUpdate(*this, RD.ExprPostUpdates));
14089}
14090
Alexey Bataevecba70f2016-04-12 11:02:11 +000014091bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14092 SourceLocation LinLoc) {
14093 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14094 LinKind == OMPC_LINEAR_unknown) {
14095 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14096 return true;
14097 }
14098 return false;
14099}
14100
Alexey Bataeve3727102018-04-18 15:57:46 +000014101bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014102 OpenMPLinearClauseKind LinKind,
14103 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014104 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014105 // A variable must not have an incomplete type or a reference type.
14106 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14107 return true;
14108 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14109 !Type->isReferenceType()) {
14110 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14111 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14112 return true;
14113 }
14114 Type = Type.getNonReferenceType();
14115
Joel E. Dennybae586f2019-01-04 22:12:13 +000014116 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14117 // A variable that is privatized must not have a const-qualified type
14118 // unless it is of class type with a mutable member. This restriction does
14119 // not apply to the firstprivate clause.
14120 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014121 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014122
14123 // A list item must be of integral or pointer type.
14124 Type = Type.getUnqualifiedType().getCanonicalType();
14125 const auto *Ty = Type.getTypePtrOrNull();
14126 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
14127 !Ty->isPointerType())) {
14128 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14129 if (D) {
14130 bool IsDecl =
14131 !VD ||
14132 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14133 Diag(D->getLocation(),
14134 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14135 << D;
14136 }
14137 return true;
14138 }
14139 return false;
14140}
14141
Alexey Bataev182227b2015-08-20 10:54:39 +000014142OMPClause *Sema::ActOnOpenMPLinearClause(
14143 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14144 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14145 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014146 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014147 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014148 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014149 SmallVector<Decl *, 4> ExprCaptures;
14150 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014151 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014152 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014153 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014154 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014155 SourceLocation ELoc;
14156 SourceRange ERange;
14157 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014158 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014159 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014160 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014161 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014162 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014163 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014164 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014165 ValueDecl *D = Res.first;
14166 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014167 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014168
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014169 QualType Type = D->getType();
14170 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014171
14172 // OpenMP [2.14.3.7, linear clause]
14173 // A list-item cannot appear in more than one linear clause.
14174 // A list-item that appears in a linear clause cannot appear in any
14175 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014176 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014177 if (DVar.RefExpr) {
14178 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14179 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014180 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014181 continue;
14182 }
14183
Alexey Bataevecba70f2016-04-12 11:02:11 +000014184 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014185 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014186 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014187
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014188 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014189 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014190 buildVarDecl(*this, ELoc, Type, D->getName(),
14191 D->hasAttrs() ? &D->getAttrs() : nullptr,
14192 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014193 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014194 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014195 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014196 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014197 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014198 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014199 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014200 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014201 ExprCaptures.push_back(Ref->getDecl());
14202 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14203 ExprResult RefRes = DefaultLvalueConversion(Ref);
14204 if (!RefRes.isUsable())
14205 continue;
14206 ExprResult PostUpdateRes =
14207 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14208 SimpleRefExpr, RefRes.get());
14209 if (!PostUpdateRes.isUsable())
14210 continue;
14211 ExprPostUpdates.push_back(
14212 IgnoredValueConversions(PostUpdateRes.get()).get());
14213 }
14214 }
14215 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014216 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014217 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014218 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014219 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014220 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014221 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014222 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014223
14224 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014225 Vars.push_back((VD || CurContext->isDependentContext())
14226 ? RefExpr->IgnoreParens()
14227 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014228 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014229 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014230 }
14231
14232 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014233 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014234
14235 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014236 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014237 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14238 !Step->isInstantiationDependent() &&
14239 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014240 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014241 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014242 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014243 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014244 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014245
Alexander Musman3276a272015-03-21 10:12:56 +000014246 // Build var to save the step value.
14247 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014248 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014249 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014250 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014251 ExprResult CalcStep =
14252 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014253 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014254
Alexander Musman8dba6642014-04-22 13:09:42 +000014255 // Warn about zero linear step (it would be probably better specified as
14256 // making corresponding variables 'const').
14257 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014258 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14259 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014260 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14261 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014262 if (!IsConstant && CalcStep.isUsable()) {
14263 // Calculate the step beforehand instead of doing this on each iteration.
14264 // (This is not used if the number of iterations may be kfold-ed).
14265 CalcStepExpr = CalcStep.get();
14266 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014267 }
14268
Alexey Bataev182227b2015-08-20 10:54:39 +000014269 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14270 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014271 StepExpr, CalcStepExpr,
14272 buildPreInits(Context, ExprCaptures),
14273 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014274}
14275
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014276static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14277 Expr *NumIterations, Sema &SemaRef,
14278 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014279 // Walk the vars and build update/final expressions for the CodeGen.
14280 SmallVector<Expr *, 8> Updates;
14281 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014282 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014283 Expr *Step = Clause.getStep();
14284 Expr *CalcStep = Clause.getCalcStep();
14285 // OpenMP [2.14.3.7, linear clause]
14286 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014287 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014288 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014289 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014290 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14291 bool HasErrors = false;
14292 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014293 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014294 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14295 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014296 SourceLocation ELoc;
14297 SourceRange ERange;
14298 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014299 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014300 ValueDecl *D = Res.first;
14301 if (Res.second || !D) {
14302 Updates.push_back(nullptr);
14303 Finals.push_back(nullptr);
14304 HasErrors = true;
14305 continue;
14306 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014307 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014308 // OpenMP [2.15.11, distribute simd Construct]
14309 // A list item may not appear in a linear clause, unless it is the loop
14310 // iteration variable.
14311 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14312 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14313 SemaRef.Diag(ELoc,
14314 diag::err_omp_linear_distribute_var_non_loop_iteration);
14315 Updates.push_back(nullptr);
14316 Finals.push_back(nullptr);
14317 HasErrors = true;
14318 continue;
14319 }
Alexander Musman3276a272015-03-21 10:12:56 +000014320 Expr *InitExpr = *CurInit;
14321
14322 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014323 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014324 Expr *CapturedRef;
14325 if (LinKind == OMPC_LINEAR_uval)
14326 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14327 else
14328 CapturedRef =
14329 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14330 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14331 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014332
14333 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014334 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014335 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014336 Update = buildCounterUpdate(
14337 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14338 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014339 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014340 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014341 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014342 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014343
14344 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014345 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014346 if (!Info.first)
14347 Final =
14348 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014349 InitExpr, NumIterations, Step, /*Subtract=*/false,
14350 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014351 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014352 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014353 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014354 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014355
Alexander Musman3276a272015-03-21 10:12:56 +000014356 if (!Update.isUsable() || !Final.isUsable()) {
14357 Updates.push_back(nullptr);
14358 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014359 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014360 HasErrors = true;
14361 } else {
14362 Updates.push_back(Update.get());
14363 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014364 if (!Info.first)
14365 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014366 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014367 ++CurInit;
14368 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014369 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014370 if (Expr *S = Clause.getStep())
14371 UsedExprs.push_back(S);
14372 // Fill the remaining part with the nullptr.
14373 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014374 Clause.setUpdates(Updates);
14375 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014376 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014377 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014378}
14379
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014380OMPClause *Sema::ActOnOpenMPAlignedClause(
14381 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14382 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014383 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014384 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014385 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14386 SourceLocation ELoc;
14387 SourceRange ERange;
14388 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014389 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014390 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014391 // It will be analyzed later.
14392 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014393 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014394 ValueDecl *D = Res.first;
14395 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014396 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014397
Alexey Bataev1efd1662016-03-29 10:59:56 +000014398 QualType QType = D->getType();
14399 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014400
14401 // OpenMP [2.8.1, simd construct, Restrictions]
14402 // The type of list items appearing in the aligned clause must be
14403 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014404 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014405 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014406 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014407 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014408 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014409 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014410 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014411 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014412 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014413 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014414 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014415 continue;
14416 }
14417
14418 // OpenMP [2.8.1, simd construct, Restrictions]
14419 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014420 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000014421 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014422 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14423 << getOpenMPClauseName(OMPC_aligned);
14424 continue;
14425 }
14426
Alexey Bataev1efd1662016-03-29 10:59:56 +000014427 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014428 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014429 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14430 Vars.push_back(DefaultFunctionArrayConversion(
14431 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14432 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014433 }
14434
14435 // OpenMP [2.8.1, simd construct, Description]
14436 // The parameter of the aligned clause, alignment, must be a constant
14437 // positive integer expression.
14438 // If no optional parameter is specified, implementation-defined default
14439 // alignments for SIMD instructions on the target platforms are assumed.
14440 if (Alignment != nullptr) {
14441 ExprResult AlignResult =
14442 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14443 if (AlignResult.isInvalid())
14444 return nullptr;
14445 Alignment = AlignResult.get();
14446 }
14447 if (Vars.empty())
14448 return nullptr;
14449
14450 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14451 EndLoc, Vars, Alignment);
14452}
14453
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014454OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14455 SourceLocation StartLoc,
14456 SourceLocation LParenLoc,
14457 SourceLocation EndLoc) {
14458 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014459 SmallVector<Expr *, 8> SrcExprs;
14460 SmallVector<Expr *, 8> DstExprs;
14461 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014462 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014463 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14464 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014465 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014466 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014467 SrcExprs.push_back(nullptr);
14468 DstExprs.push_back(nullptr);
14469 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014470 continue;
14471 }
14472
Alexey Bataeved09d242014-05-28 05:53:51 +000014473 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014474 // OpenMP [2.1, C/C++]
14475 // A list item is a variable name.
14476 // OpenMP [2.14.4.1, Restrictions, p.1]
14477 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014478 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014479 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014480 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14481 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014482 continue;
14483 }
14484
14485 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014486 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014487
14488 QualType Type = VD->getType();
14489 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14490 // It will be analyzed later.
14491 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014492 SrcExprs.push_back(nullptr);
14493 DstExprs.push_back(nullptr);
14494 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014495 continue;
14496 }
14497
14498 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14499 // A list item that appears in a copyin clause must be threadprivate.
14500 if (!DSAStack->isThreadPrivate(VD)) {
14501 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014502 << getOpenMPClauseName(OMPC_copyin)
14503 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014504 continue;
14505 }
14506
14507 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14508 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014509 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014510 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014511 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14512 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014513 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014514 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014515 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014516 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014517 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014518 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014519 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014520 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014521 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014522 // For arrays generate assignment operation for single element and replace
14523 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014524 ExprResult AssignmentOp =
14525 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14526 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014527 if (AssignmentOp.isInvalid())
14528 continue;
14529 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014530 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014531 if (AssignmentOp.isInvalid())
14532 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014533
14534 DSAStack->addDSA(VD, DE, OMPC_copyin);
14535 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014536 SrcExprs.push_back(PseudoSrcExpr);
14537 DstExprs.push_back(PseudoDstExpr);
14538 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014539 }
14540
Alexey Bataeved09d242014-05-28 05:53:51 +000014541 if (Vars.empty())
14542 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014543
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014544 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14545 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014546}
14547
Alexey Bataevbae9a792014-06-27 10:37:06 +000014548OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14549 SourceLocation StartLoc,
14550 SourceLocation LParenLoc,
14551 SourceLocation EndLoc) {
14552 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014553 SmallVector<Expr *, 8> SrcExprs;
14554 SmallVector<Expr *, 8> DstExprs;
14555 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014556 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014557 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14558 SourceLocation ELoc;
14559 SourceRange ERange;
14560 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014561 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014562 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014563 // It will be analyzed later.
14564 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014565 SrcExprs.push_back(nullptr);
14566 DstExprs.push_back(nullptr);
14567 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014568 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014569 ValueDecl *D = Res.first;
14570 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014571 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014572
Alexey Bataeve122da12016-03-17 10:50:17 +000014573 QualType Type = D->getType();
14574 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014575
14576 // OpenMP [2.14.4.2, Restrictions, p.2]
14577 // A list item that appears in a copyprivate clause may not appear in a
14578 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014579 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014580 DSAStackTy::DSAVarData DVar =
14581 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014582 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14583 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014584 Diag(ELoc, diag::err_omp_wrong_dsa)
14585 << getOpenMPClauseName(DVar.CKind)
14586 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014587 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014588 continue;
14589 }
14590
14591 // OpenMP [2.11.4.2, Restrictions, p.1]
14592 // All list items that appear in a copyprivate clause must be either
14593 // threadprivate or private in the enclosing context.
14594 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014595 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014596 if (DVar.CKind == OMPC_shared) {
14597 Diag(ELoc, diag::err_omp_required_access)
14598 << getOpenMPClauseName(OMPC_copyprivate)
14599 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014600 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014601 continue;
14602 }
14603 }
14604 }
14605
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014606 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014607 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014608 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014609 << getOpenMPClauseName(OMPC_copyprivate) << Type
14610 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014611 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014612 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014613 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014614 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014615 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014616 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014617 continue;
14618 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014619
Alexey Bataevbae9a792014-06-27 10:37:06 +000014620 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14621 // A variable of class type (or array thereof) that appears in a
14622 // copyin clause requires an accessible, unambiguous copy assignment
14623 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014624 Type = Context.getBaseElementType(Type.getNonReferenceType())
14625 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014626 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014627 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014628 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014629 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14630 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014631 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014632 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014633 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14634 ExprResult AssignmentOp = BuildBinOp(
14635 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014636 if (AssignmentOp.isInvalid())
14637 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014638 AssignmentOp =
14639 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014640 if (AssignmentOp.isInvalid())
14641 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014642
14643 // No need to mark vars as copyprivate, they are already threadprivate or
14644 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014645 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014646 Vars.push_back(
14647 VD ? RefExpr->IgnoreParens()
14648 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014649 SrcExprs.push_back(PseudoSrcExpr);
14650 DstExprs.push_back(PseudoDstExpr);
14651 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014652 }
14653
14654 if (Vars.empty())
14655 return nullptr;
14656
Alexey Bataeva63048e2015-03-23 06:18:07 +000014657 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14658 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014659}
14660
Alexey Bataev6125da92014-07-21 11:26:11 +000014661OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14662 SourceLocation StartLoc,
14663 SourceLocation LParenLoc,
14664 SourceLocation EndLoc) {
14665 if (VarList.empty())
14666 return nullptr;
14667
14668 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14669}
Alexey Bataevdea47612014-07-23 07:46:59 +000014670
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014671OMPClause *
14672Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14673 SourceLocation DepLoc, SourceLocation ColonLoc,
14674 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14675 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014676 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014677 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014678 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014679 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014680 return nullptr;
14681 }
14682 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014683 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14684 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014685 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014686 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014687 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14688 /*Last=*/OMPC_DEPEND_unknown, Except)
14689 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014690 return nullptr;
14691 }
14692 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014693 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014694 llvm::APSInt DepCounter(/*BitWidth=*/32);
14695 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014696 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14697 if (const Expr *OrderedCountExpr =
14698 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014699 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14700 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014701 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014702 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014703 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014704 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14705 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14706 // It will be analyzed later.
14707 Vars.push_back(RefExpr);
14708 continue;
14709 }
14710
14711 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014712 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014713 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014714 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014715 DepCounter >= TotalDepCount) {
14716 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14717 continue;
14718 }
14719 ++DepCounter;
14720 // OpenMP [2.13.9, Summary]
14721 // depend(dependence-type : vec), where dependence-type is:
14722 // 'sink' and where vec is the iteration vector, which has the form:
14723 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14724 // where n is the value specified by the ordered clause in the loop
14725 // directive, xi denotes the loop iteration variable of the i-th nested
14726 // loop associated with the loop directive, and di is a constant
14727 // non-negative integer.
14728 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014729 // It will be analyzed later.
14730 Vars.push_back(RefExpr);
14731 continue;
14732 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014733 SimpleExpr = SimpleExpr->IgnoreImplicit();
14734 OverloadedOperatorKind OOK = OO_None;
14735 SourceLocation OOLoc;
14736 Expr *LHS = SimpleExpr;
14737 Expr *RHS = nullptr;
14738 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14739 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14740 OOLoc = BO->getOperatorLoc();
14741 LHS = BO->getLHS()->IgnoreParenImpCasts();
14742 RHS = BO->getRHS()->IgnoreParenImpCasts();
14743 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14744 OOK = OCE->getOperator();
14745 OOLoc = OCE->getOperatorLoc();
14746 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14747 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14748 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14749 OOK = MCE->getMethodDecl()
14750 ->getNameInfo()
14751 .getName()
14752 .getCXXOverloadedOperator();
14753 OOLoc = MCE->getCallee()->getExprLoc();
14754 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14755 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014756 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014757 SourceLocation ELoc;
14758 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014759 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014760 if (Res.second) {
14761 // It will be analyzed later.
14762 Vars.push_back(RefExpr);
14763 }
14764 ValueDecl *D = Res.first;
14765 if (!D)
14766 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014767
Alexey Bataev17daedf2018-02-15 22:42:57 +000014768 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14769 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14770 continue;
14771 }
14772 if (RHS) {
14773 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14774 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14775 if (RHSRes.isInvalid())
14776 continue;
14777 }
14778 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014779 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014780 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014781 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014782 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014783 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014784 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14785 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014786 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014787 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014788 continue;
14789 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014790 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014791 } else {
14792 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14793 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14794 (ASE &&
14795 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14796 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14797 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14798 << RefExpr->getSourceRange();
14799 continue;
14800 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014801
14802 ExprResult Res;
14803 {
14804 Sema::TentativeAnalysisScope Trap(*this);
14805 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14806 RefExpr->IgnoreParenImpCasts());
14807 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014808 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14809 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14810 << RefExpr->getSourceRange();
14811 continue;
14812 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014813 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014814 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014815 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014816
14817 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14818 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014819 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014820 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14821 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14822 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14823 }
14824 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14825 Vars.empty())
14826 return nullptr;
14827
Alexey Bataev8b427062016-05-25 12:36:08 +000014828 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014829 DepKind, DepLoc, ColonLoc, Vars,
14830 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014831 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14832 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014833 DSAStack->addDoacrossDependClause(C, OpsOffs);
14834 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014835}
Michael Wonge710d542015-08-07 16:16:36 +000014836
14837OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14838 SourceLocation LParenLoc,
14839 SourceLocation EndLoc) {
14840 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014841 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014842
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014843 // OpenMP [2.9.1, Restrictions]
14844 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014845 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014846 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014847 return nullptr;
14848
Alexey Bataev931e19b2017-10-02 16:32:39 +000014849 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014850 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050014851 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000014852 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014853 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014854 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014855 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14856 HelperValStmt = buildPreInits(Context, Captures);
14857 }
14858
Alexey Bataev8451efa2018-01-15 19:06:12 +000014859 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14860 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014861}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014862
Alexey Bataeve3727102018-04-18 15:57:46 +000014863static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014864 DSAStackTy *Stack, QualType QTy,
14865 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014866 NamedDecl *ND;
14867 if (QTy->isIncompleteType(&ND)) {
14868 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14869 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014870 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014871 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14872 !QTy.isTrivialType(SemaRef.Context))
14873 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014874 return true;
14875}
14876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014877/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014878/// (array section or array subscript) does NOT specify the whole size of the
14879/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014880static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014881 const Expr *E,
14882 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014883 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014884
14885 // If this is an array subscript, it refers to the whole size if the size of
14886 // the dimension is constant and equals 1. Also, an array section assumes the
14887 // format of an array subscript if no colon is used.
14888 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014889 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014890 return ATy->getSize().getSExtValue() != 1;
14891 // Size can't be evaluated statically.
14892 return false;
14893 }
14894
14895 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014896 const Expr *LowerBound = OASE->getLowerBound();
14897 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014898
14899 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014900 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014901 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014902 Expr::EvalResult Result;
14903 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014904 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014905
14906 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014907 if (ConstLowerBound.getSExtValue())
14908 return true;
14909 }
14910
14911 // If we don't have a length we covering the whole dimension.
14912 if (!Length)
14913 return false;
14914
14915 // If the base is a pointer, we don't have a way to get the size of the
14916 // pointee.
14917 if (BaseQTy->isPointerType())
14918 return false;
14919
14920 // We can only check if the length is the same as the size of the dimension
14921 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014922 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014923 if (!CATy)
14924 return false;
14925
Fangrui Song407659a2018-11-30 23:41:18 +000014926 Expr::EvalResult Result;
14927 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014928 return false; // Can't get the integer value as a constant.
14929
Fangrui Song407659a2018-11-30 23:41:18 +000014930 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014931 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14932}
14933
14934// Return true if it can be proven that the provided array expression (array
14935// section or array subscript) does NOT specify a single element of the array
14936// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014937static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014938 const Expr *E,
14939 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014940 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014941
14942 // An array subscript always refer to a single element. Also, an array section
14943 // assumes the format of an array subscript if no colon is used.
14944 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14945 return false;
14946
14947 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014948 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014949
14950 // If we don't have a length we have to check if the array has unitary size
14951 // for this dimension. Also, we should always expect a length if the base type
14952 // is pointer.
14953 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014954 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014955 return ATy->getSize().getSExtValue() != 1;
14956 // We cannot assume anything.
14957 return false;
14958 }
14959
14960 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014961 Expr::EvalResult Result;
14962 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014963 return false; // Can't get the integer value as a constant.
14964
Fangrui Song407659a2018-11-30 23:41:18 +000014965 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014966 return ConstLength.getSExtValue() != 1;
14967}
14968
Samuel Antao661c0902016-05-26 17:39:58 +000014969// Return the expression of the base of the mappable expression or null if it
14970// cannot be determined and do all the necessary checks to see if the expression
14971// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014972// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014973static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014974 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014975 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014976 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014977 SourceLocation ELoc = E->getExprLoc();
14978 SourceRange ERange = E->getSourceRange();
14979
14980 // The base of elements of list in a map clause have to be either:
14981 // - a reference to variable or field.
14982 // - a member expression.
14983 // - an array expression.
14984 //
14985 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14986 // reference to 'r'.
14987 //
14988 // If we have:
14989 //
14990 // struct SS {
14991 // Bla S;
14992 // foo() {
14993 // #pragma omp target map (S.Arr[:12]);
14994 // }
14995 // }
14996 //
14997 // We want to retrieve the member expression 'this->S';
14998
Alexey Bataeve3727102018-04-18 15:57:46 +000014999 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015000
Samuel Antao5de996e2016-01-22 20:21:36 +000015001 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15002 // If a list item is an array section, it must specify contiguous storage.
15003 //
15004 // For this restriction it is sufficient that we make sure only references
15005 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015006 // exist except in the rightmost expression (unless they cover the whole
15007 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015008 //
15009 // r.ArrS[3:5].Arr[6:7]
15010 //
15011 // r.ArrS[3:5].x
15012 //
15013 // but these would be valid:
15014 // r.ArrS[3].Arr[6:7]
15015 //
15016 // r.ArrS[3].x
15017
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015018 bool AllowUnitySizeArraySection = true;
15019 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015020
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015021 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015022 E = E->IgnoreParenImpCasts();
15023
15024 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15025 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015026 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015027
15028 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015029
15030 // If we got a reference to a declaration, we should not expect any array
15031 // section before that.
15032 AllowUnitySizeArraySection = false;
15033 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015034
15035 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015036 CurComponents.emplace_back(CurE, CurE->getDecl());
15037 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015038 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015039
15040 if (isa<CXXThisExpr>(BaseE))
15041 // We found a base expression: this->Val.
15042 RelevantExpr = CurE;
15043 else
15044 E = BaseE;
15045
15046 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015047 if (!NoDiagnose) {
15048 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15049 << CurE->getSourceRange();
15050 return nullptr;
15051 }
15052 if (RelevantExpr)
15053 return nullptr;
15054 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015055 }
15056
15057 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15058
15059 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15060 // A bit-field cannot appear in a map clause.
15061 //
15062 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015063 if (!NoDiagnose) {
15064 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15065 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15066 return nullptr;
15067 }
15068 if (RelevantExpr)
15069 return nullptr;
15070 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015071 }
15072
15073 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15074 // If the type of a list item is a reference to a type T then the type
15075 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015076 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015077
15078 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15079 // A list item cannot be a variable that is a member of a structure with
15080 // a union type.
15081 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015082 if (CurType->isUnionType()) {
15083 if (!NoDiagnose) {
15084 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15085 << CurE->getSourceRange();
15086 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015087 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015088 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015089 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015090
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015091 // If we got a member expression, we should not expect any array section
15092 // before that:
15093 //
15094 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15095 // If a list item is an element of a structure, only the rightmost symbol
15096 // of the variable reference can be an array section.
15097 //
15098 AllowUnitySizeArraySection = false;
15099 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015100
15101 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015102 CurComponents.emplace_back(CurE, FD);
15103 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015104 E = CurE->getBase()->IgnoreParenImpCasts();
15105
15106 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015107 if (!NoDiagnose) {
15108 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15109 << 0 << CurE->getSourceRange();
15110 return nullptr;
15111 }
15112 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015113 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015114
15115 // If we got an array subscript that express the whole dimension we
15116 // can have any array expressions before. If it only expressing part of
15117 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015118 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015119 E->getType()))
15120 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015121
Patrick Lystere13b1e32019-01-02 19:28:48 +000015122 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15123 Expr::EvalResult Result;
15124 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15125 if (!Result.Val.getInt().isNullValue()) {
15126 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15127 diag::err_omp_invalid_map_this_expr);
15128 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15129 diag::note_omp_invalid_subscript_on_this_ptr_map);
15130 }
15131 }
15132 RelevantExpr = TE;
15133 }
15134
Samuel Antao90927002016-04-26 14:54:23 +000015135 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015136 CurComponents.emplace_back(CurE, nullptr);
15137 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015138 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015139 E = CurE->getBase()->IgnoreParenImpCasts();
15140
Alexey Bataev27041fa2017-12-05 15:22:49 +000015141 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015142 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15143
Samuel Antao5de996e2016-01-22 20:21:36 +000015144 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15145 // If the type of a list item is a reference to a type T then the type
15146 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015147 if (CurType->isReferenceType())
15148 CurType = CurType->getPointeeType();
15149
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015150 bool IsPointer = CurType->isAnyPointerType();
15151
15152 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015153 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15154 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015155 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015156 }
15157
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015158 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015159 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015160 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015161 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015162
Samuel Antaodab51bb2016-07-18 23:22:11 +000015163 if (AllowWholeSizeArraySection) {
15164 // Any array section is currently allowed. Allowing a whole size array
15165 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015166 //
15167 // If this array section refers to the whole dimension we can still
15168 // accept other array sections before this one, except if the base is a
15169 // pointer. Otherwise, only unitary sections are accepted.
15170 if (NotWhole || IsPointer)
15171 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015172 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015173 // A unity or whole array section is not allowed and that is not
15174 // compatible with the properties of the current array section.
15175 SemaRef.Diag(
15176 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15177 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015178 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015179 }
Samuel Antao90927002016-04-26 14:54:23 +000015180
Patrick Lystere13b1e32019-01-02 19:28:48 +000015181 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15182 Expr::EvalResult ResultR;
15183 Expr::EvalResult ResultL;
15184 if (CurE->getLength()->EvaluateAsInt(ResultR,
15185 SemaRef.getASTContext())) {
15186 if (!ResultR.Val.getInt().isOneValue()) {
15187 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15188 diag::err_omp_invalid_map_this_expr);
15189 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15190 diag::note_omp_invalid_length_on_this_ptr_mapping);
15191 }
15192 }
15193 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15194 ResultL, SemaRef.getASTContext())) {
15195 if (!ResultL.Val.getInt().isNullValue()) {
15196 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15197 diag::err_omp_invalid_map_this_expr);
15198 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15199 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15200 }
15201 }
15202 RelevantExpr = TE;
15203 }
15204
Samuel Antao90927002016-04-26 14:54:23 +000015205 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015206 CurComponents.emplace_back(CurE, nullptr);
15207 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015208 if (!NoDiagnose) {
15209 // If nothing else worked, this is not a valid map clause expression.
15210 SemaRef.Diag(
15211 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15212 << ERange;
15213 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015214 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015215 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015216 }
15217
15218 return RelevantExpr;
15219}
15220
15221// Return true if expression E associated with value VD has conflicts with other
15222// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015223static bool checkMapConflicts(
15224 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015225 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015226 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15227 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015228 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015229 SourceLocation ELoc = E->getExprLoc();
15230 SourceRange ERange = E->getSourceRange();
15231
15232 // In order to easily check the conflicts we need to match each component of
15233 // the expression under test with the components of the expressions that are
15234 // already in the stack.
15235
Samuel Antao5de996e2016-01-22 20:21:36 +000015236 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015237 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015238 "Map clause expression with unexpected base!");
15239
15240 // Variables to help detecting enclosing problems in data environment nests.
15241 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015242 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015243
Samuel Antao90927002016-04-26 14:54:23 +000015244 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15245 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015246 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15247 ERange, CKind, &EnclosingExpr,
15248 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15249 StackComponents,
15250 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015251 assert(!StackComponents.empty() &&
15252 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015253 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015254 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015255 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015256
Samuel Antao90927002016-04-26 14:54:23 +000015257 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015258 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015259
Samuel Antao5de996e2016-01-22 20:21:36 +000015260 // Expressions must start from the same base. Here we detect at which
15261 // point both expressions diverge from each other and see if we can
15262 // detect if the memory referred to both expressions is contiguous and
15263 // do not overlap.
15264 auto CI = CurComponents.rbegin();
15265 auto CE = CurComponents.rend();
15266 auto SI = StackComponents.rbegin();
15267 auto SE = StackComponents.rend();
15268 for (; CI != CE && SI != SE; ++CI, ++SI) {
15269
15270 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15271 // At most one list item can be an array item derived from a given
15272 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015273 if (CurrentRegionOnly &&
15274 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15275 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15276 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15277 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15278 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015279 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015280 << CI->getAssociatedExpression()->getSourceRange();
15281 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15282 diag::note_used_here)
15283 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015284 return true;
15285 }
15286
15287 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015288 if (CI->getAssociatedExpression()->getStmtClass() !=
15289 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015290 break;
15291
15292 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015293 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015294 break;
15295 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015296 // Check if the extra components of the expressions in the enclosing
15297 // data environment are redundant for the current base declaration.
15298 // If they are, the maps completely overlap, which is legal.
15299 for (; SI != SE; ++SI) {
15300 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015301 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015302 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015303 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015304 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015305 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015306 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015307 Type =
15308 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15309 }
15310 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015311 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015312 SemaRef, SI->getAssociatedExpression(), Type))
15313 break;
15314 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015315
15316 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15317 // List items of map clauses in the same construct must not share
15318 // original storage.
15319 //
15320 // If the expressions are exactly the same or one is a subset of the
15321 // other, it means they are sharing storage.
15322 if (CI == CE && SI == SE) {
15323 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015324 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015325 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015326 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015327 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015328 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15329 << ERange;
15330 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015331 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15332 << RE->getSourceRange();
15333 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015334 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015335 // If we find the same expression in the enclosing data environment,
15336 // that is legal.
15337 IsEnclosedByDataEnvironmentExpr = true;
15338 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015339 }
15340
Samuel Antao90927002016-04-26 14:54:23 +000015341 QualType DerivedType =
15342 std::prev(CI)->getAssociatedDeclaration()->getType();
15343 SourceLocation DerivedLoc =
15344 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015345
15346 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15347 // If the type of a list item is a reference to a type T then the type
15348 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015349 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015350
15351 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15352 // A variable for which the type is pointer and an array section
15353 // derived from that variable must not appear as list items of map
15354 // clauses of the same construct.
15355 //
15356 // Also, cover one of the cases in:
15357 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15358 // If any part of the original storage of a list item has corresponding
15359 // storage in the device data environment, all of the original storage
15360 // must have corresponding storage in the device data environment.
15361 //
15362 if (DerivedType->isAnyPointerType()) {
15363 if (CI == CE || SI == SE) {
15364 SemaRef.Diag(
15365 DerivedLoc,
15366 diag::err_omp_pointer_mapped_along_with_derived_section)
15367 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015368 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15369 << RE->getSourceRange();
15370 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015371 }
15372 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015373 SI->getAssociatedExpression()->getStmtClass() ||
15374 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15375 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015376 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015377 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015378 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015379 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15380 << RE->getSourceRange();
15381 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015382 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015383 }
15384
15385 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15386 // List items of map clauses in the same construct must not share
15387 // original storage.
15388 //
15389 // An expression is a subset of the other.
15390 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015391 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015392 if (CI != CE || SI != SE) {
15393 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15394 // a pointer.
15395 auto Begin =
15396 CI != CE ? CurComponents.begin() : StackComponents.begin();
15397 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15398 auto It = Begin;
15399 while (It != End && !It->getAssociatedDeclaration())
15400 std::advance(It, 1);
15401 assert(It != End &&
15402 "Expected at least one component with the declaration.");
15403 if (It != Begin && It->getAssociatedDeclaration()
15404 ->getType()
15405 .getCanonicalType()
15406 ->isAnyPointerType()) {
15407 IsEnclosedByDataEnvironmentExpr = false;
15408 EnclosingExpr = nullptr;
15409 return false;
15410 }
15411 }
Samuel Antao661c0902016-05-26 17:39:58 +000015412 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015413 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015414 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015415 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15416 << ERange;
15417 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015418 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15419 << RE->getSourceRange();
15420 return true;
15421 }
15422
15423 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015424 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015425 if (!CurrentRegionOnly && SI != SE)
15426 EnclosingExpr = RE;
15427
15428 // The current expression is a subset of the expression in the data
15429 // environment.
15430 IsEnclosedByDataEnvironmentExpr |=
15431 (!CurrentRegionOnly && CI != CE && SI == SE);
15432
15433 return false;
15434 });
15435
15436 if (CurrentRegionOnly)
15437 return FoundError;
15438
15439 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15440 // If any part of the original storage of a list item has corresponding
15441 // storage in the device data environment, all of the original storage must
15442 // have corresponding storage in the device data environment.
15443 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15444 // If a list item is an element of a structure, and a different element of
15445 // the structure has a corresponding list item in the device data environment
15446 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015447 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015448 // data environment prior to the task encountering the construct.
15449 //
15450 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15451 SemaRef.Diag(ELoc,
15452 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15453 << ERange;
15454 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15455 << EnclosingExpr->getSourceRange();
15456 return true;
15457 }
15458
15459 return FoundError;
15460}
15461
Michael Kruse4304e9d2019-02-19 16:38:20 +000015462// Look up the user-defined mapper given the mapper name and mapped type, and
15463// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015464static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15465 CXXScopeSpec &MapperIdScopeSpec,
15466 const DeclarationNameInfo &MapperId,
15467 QualType Type,
15468 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015469 if (MapperIdScopeSpec.isInvalid())
15470 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015471 // Get the actual type for the array type.
15472 if (Type->isArrayType()) {
15473 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15474 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15475 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015476 // Find all user-defined mappers with the given MapperId.
15477 SmallVector<UnresolvedSet<8>, 4> Lookups;
15478 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15479 Lookup.suppressDiagnostics();
15480 if (S) {
15481 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15482 NamedDecl *D = Lookup.getRepresentativeDecl();
15483 while (S && !S->isDeclScope(D))
15484 S = S->getParent();
15485 if (S)
15486 S = S->getParent();
15487 Lookups.emplace_back();
15488 Lookups.back().append(Lookup.begin(), Lookup.end());
15489 Lookup.clear();
15490 }
15491 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15492 // Extract the user-defined mappers with the given MapperId.
15493 Lookups.push_back(UnresolvedSet<8>());
15494 for (NamedDecl *D : ULE->decls()) {
15495 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15496 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15497 Lookups.back().addDecl(DMD);
15498 }
15499 }
15500 // Defer the lookup for dependent types. The results will be passed through
15501 // UnresolvedMapper on instantiation.
15502 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15503 Type->isInstantiationDependentType() ||
15504 Type->containsUnexpandedParameterPack() ||
15505 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15506 return !D->isInvalidDecl() &&
15507 (D->getType()->isDependentType() ||
15508 D->getType()->isInstantiationDependentType() ||
15509 D->getType()->containsUnexpandedParameterPack());
15510 })) {
15511 UnresolvedSet<8> URS;
15512 for (const UnresolvedSet<8> &Set : Lookups) {
15513 if (Set.empty())
15514 continue;
15515 URS.append(Set.begin(), Set.end());
15516 }
15517 return UnresolvedLookupExpr::Create(
15518 SemaRef.Context, /*NamingClass=*/nullptr,
15519 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15520 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15521 }
Michael Kruse945249b2019-09-26 22:53:01 +000015522 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015523 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15524 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015525 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15526 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15527 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15528 return ExprError();
15529 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015530 // Perform argument dependent lookup.
15531 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15532 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15533 // Return the first user-defined mapper with the desired type.
15534 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15535 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15536 if (!D->isInvalidDecl() &&
15537 SemaRef.Context.hasSameType(D->getType(), Type))
15538 return D;
15539 return nullptr;
15540 }))
15541 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15542 // Find the first user-defined mapper with a type derived from the desired
15543 // type.
15544 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15545 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15546 if (!D->isInvalidDecl() &&
15547 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15548 !Type.isMoreQualifiedThan(D->getType()))
15549 return D;
15550 return nullptr;
15551 })) {
15552 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15553 /*DetectVirtual=*/false);
15554 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15555 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15556 VD->getType().getUnqualifiedType()))) {
15557 if (SemaRef.CheckBaseClassAccess(
15558 Loc, VD->getType(), Type, Paths.front(),
15559 /*DiagID=*/0) != Sema::AR_inaccessible) {
15560 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15561 }
15562 }
15563 }
15564 }
15565 // Report error if a mapper is specified, but cannot be found.
15566 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15567 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15568 << Type << MapperId.getName();
15569 return ExprError();
15570 }
15571 return ExprEmpty();
15572}
15573
Samuel Antao661c0902016-05-26 17:39:58 +000015574namespace {
15575// Utility struct that gathers all the related lists associated with a mappable
15576// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015577struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015578 // The list of expressions.
15579 ArrayRef<Expr *> VarList;
15580 // The list of processed expressions.
15581 SmallVector<Expr *, 16> ProcessedVarList;
15582 // The mappble components for each expression.
15583 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15584 // The base declaration of the variable.
15585 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015586 // The reference to the user-defined mapper associated with every expression.
15587 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015588
15589 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15590 // We have a list of components and base declarations for each entry in the
15591 // variable list.
15592 VarComponents.reserve(VarList.size());
15593 VarBaseDeclarations.reserve(VarList.size());
15594 }
15595};
15596}
15597
15598// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015599// \a CKind. In the check process the valid expressions, mappable expression
15600// components, variables, and user-defined mappers are extracted and used to
15601// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15602// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15603// and \a MapperId are expected to be valid if the clause kind is 'map'.
15604static void checkMappableExpressionList(
15605 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15606 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015607 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15608 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015609 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015610 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015611 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15612 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015613 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015614
15615 // If the identifier of user-defined mapper is not specified, it is "default".
15616 // We do not change the actual name in this clause to distinguish whether a
15617 // mapper is specified explicitly, i.e., it is not explicitly specified when
15618 // MapperId.getName() is empty.
15619 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15620 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15621 MapperId.setName(DeclNames.getIdentifier(
15622 &SemaRef.getASTContext().Idents.get("default")));
15623 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015624
15625 // Iterators to find the current unresolved mapper expression.
15626 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15627 bool UpdateUMIt = false;
15628 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015629
Samuel Antao90927002016-04-26 14:54:23 +000015630 // Keep track of the mappable components and base declarations in this clause.
15631 // Each entry in the list is going to have a list of components associated. We
15632 // record each set of the components so that we can build the clause later on.
15633 // In the end we should have the same amount of declarations and component
15634 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015635
Alexey Bataeve3727102018-04-18 15:57:46 +000015636 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015637 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015638 SourceLocation ELoc = RE->getExprLoc();
15639
Michael Kruse4304e9d2019-02-19 16:38:20 +000015640 // Find the current unresolved mapper expression.
15641 if (UpdateUMIt && UMIt != UMEnd) {
15642 UMIt++;
15643 assert(
15644 UMIt != UMEnd &&
15645 "Expect the size of UnresolvedMappers to match with that of VarList");
15646 }
15647 UpdateUMIt = true;
15648 if (UMIt != UMEnd)
15649 UnresolvedMapper = *UMIt;
15650
Alexey Bataeve3727102018-04-18 15:57:46 +000015651 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015652
15653 if (VE->isValueDependent() || VE->isTypeDependent() ||
15654 VE->isInstantiationDependent() ||
15655 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015656 // Try to find the associated user-defined mapper.
15657 ExprResult ER = buildUserDefinedMapperRef(
15658 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15659 VE->getType().getCanonicalType(), UnresolvedMapper);
15660 if (ER.isInvalid())
15661 continue;
15662 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015663 // We can only analyze this information once the missing information is
15664 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015665 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015666 continue;
15667 }
15668
Alexey Bataeve3727102018-04-18 15:57:46 +000015669 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015670
Samuel Antao5de996e2016-01-22 20:21:36 +000015671 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015672 SemaRef.Diag(ELoc,
15673 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015674 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015675 continue;
15676 }
15677
Samuel Antao90927002016-04-26 14:54:23 +000015678 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15679 ValueDecl *CurDeclaration = nullptr;
15680
15681 // Obtain the array or member expression bases if required. Also, fill the
15682 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015683 const Expr *BE = checkMapClauseExpressionBase(
15684 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015685 if (!BE)
15686 continue;
15687
Samuel Antao90927002016-04-26 14:54:23 +000015688 assert(!CurComponents.empty() &&
15689 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015690
Patrick Lystere13b1e32019-01-02 19:28:48 +000015691 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15692 // Add store "this" pointer to class in DSAStackTy for future checking
15693 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015694 // Try to find the associated user-defined mapper.
15695 ExprResult ER = buildUserDefinedMapperRef(
15696 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15697 VE->getType().getCanonicalType(), UnresolvedMapper);
15698 if (ER.isInvalid())
15699 continue;
15700 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015701 // Skip restriction checking for variable or field declarations
15702 MVLI.ProcessedVarList.push_back(RE);
15703 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15704 MVLI.VarComponents.back().append(CurComponents.begin(),
15705 CurComponents.end());
15706 MVLI.VarBaseDeclarations.push_back(nullptr);
15707 continue;
15708 }
15709
Samuel Antao90927002016-04-26 14:54:23 +000015710 // For the following checks, we rely on the base declaration which is
15711 // expected to be associated with the last component. The declaration is
15712 // expected to be a variable or a field (if 'this' is being mapped).
15713 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15714 assert(CurDeclaration && "Null decl on map clause.");
15715 assert(
15716 CurDeclaration->isCanonicalDecl() &&
15717 "Expecting components to have associated only canonical declarations.");
15718
15719 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015720 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015721
15722 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015723 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015724
15725 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015726 // threadprivate variables cannot appear in a map clause.
15727 // OpenMP 4.5 [2.10.5, target update Construct]
15728 // threadprivate variables cannot appear in a from clause.
15729 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015730 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015731 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15732 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015733 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015734 continue;
15735 }
15736
Samuel Antao5de996e2016-01-22 20:21:36 +000015737 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15738 // A list item cannot appear in both a map clause and a data-sharing
15739 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015740
Samuel Antao5de996e2016-01-22 20:21:36 +000015741 // Check conflicts with other map clause expressions. We check the conflicts
15742 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015743 // environment, because the restrictions are different. We only have to
15744 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015745 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015746 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015747 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015748 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015749 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015750 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015751 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015752
Samuel Antao661c0902016-05-26 17:39:58 +000015753 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015754 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15755 // If the type of a list item is a reference to a type T then the type will
15756 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015757 auto I = llvm::find_if(
15758 CurComponents,
15759 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15760 return MC.getAssociatedDeclaration();
15761 });
15762 assert(I != CurComponents.end() && "Null decl on map clause.");
15763 QualType Type =
15764 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015765
Samuel Antao661c0902016-05-26 17:39:58 +000015766 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15767 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015768 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015769 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015770 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015771 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015772 continue;
15773
Samuel Antao661c0902016-05-26 17:39:58 +000015774 if (CKind == OMPC_map) {
15775 // target enter data
15776 // OpenMP [2.10.2, Restrictions, p. 99]
15777 // A map-type must be specified in all map clauses and must be either
15778 // to or alloc.
15779 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15780 if (DKind == OMPD_target_enter_data &&
15781 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15782 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15783 << (IsMapTypeImplicit ? 1 : 0)
15784 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15785 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015786 continue;
15787 }
Samuel Antao661c0902016-05-26 17:39:58 +000015788
15789 // target exit_data
15790 // OpenMP [2.10.3, Restrictions, p. 102]
15791 // A map-type must be specified in all map clauses and must be either
15792 // from, release, or delete.
15793 if (DKind == OMPD_target_exit_data &&
15794 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15795 MapType == OMPC_MAP_delete)) {
15796 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15797 << (IsMapTypeImplicit ? 1 : 0)
15798 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15799 << getOpenMPDirectiveName(DKind);
15800 continue;
15801 }
15802
15803 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15804 // A list item cannot appear in both a map clause and a data-sharing
15805 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015806 //
15807 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15808 // A list item cannot appear in both a map clause and a data-sharing
15809 // attribute clause on the same construct unless the construct is a
15810 // combined construct.
15811 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15812 isOpenMPTargetExecutionDirective(DKind)) ||
15813 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015814 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015815 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015816 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015817 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015818 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015819 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015820 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015821 continue;
15822 }
15823 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015824 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015825
Michael Kruse01f670d2019-02-22 22:29:42 +000015826 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015827 ExprResult ER = buildUserDefinedMapperRef(
15828 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15829 Type.getCanonicalType(), UnresolvedMapper);
15830 if (ER.isInvalid())
15831 continue;
15832 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015833
Samuel Antao90927002016-04-26 14:54:23 +000015834 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015835 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015836
15837 // Store the components in the stack so that they can be used to check
15838 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015839 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15840 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015841
15842 // Save the components and declaration to create the clause. For purposes of
15843 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015844 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015845 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15846 MVLI.VarComponents.back().append(CurComponents.begin(),
15847 CurComponents.end());
15848 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15849 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015850 }
Samuel Antao661c0902016-05-26 17:39:58 +000015851}
15852
Michael Kruse4304e9d2019-02-19 16:38:20 +000015853OMPClause *Sema::ActOnOpenMPMapClause(
15854 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15855 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15856 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15857 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15858 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15859 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15860 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15861 OMPC_MAP_MODIFIER_unknown,
15862 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015863 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15864
15865 // Process map-type-modifiers, flag errors for duplicate modifiers.
15866 unsigned Count = 0;
15867 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15868 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15869 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15870 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15871 continue;
15872 }
15873 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015874 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015875 Modifiers[Count] = MapTypeModifiers[I];
15876 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15877 ++Count;
15878 }
15879
Michael Kruse4304e9d2019-02-19 16:38:20 +000015880 MappableVarListInfo MVLI(VarList);
15881 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015882 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15883 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015884
Samuel Antao5de996e2016-01-22 20:21:36 +000015885 // We need to produce a map clause even if we don't have variables so that
15886 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015887 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15888 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15889 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15890 MapperIdScopeSpec.getWithLocInContext(Context),
15891 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015892}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015893
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015894QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15895 TypeResult ParsedType) {
15896 assert(ParsedType.isUsable());
15897
15898 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15899 if (ReductionType.isNull())
15900 return QualType();
15901
15902 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15903 // A type name in a declare reduction directive cannot be a function type, an
15904 // array type, a reference type, or a type qualified with const, volatile or
15905 // restrict.
15906 if (ReductionType.hasQualifiers()) {
15907 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15908 return QualType();
15909 }
15910
15911 if (ReductionType->isFunctionType()) {
15912 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15913 return QualType();
15914 }
15915 if (ReductionType->isReferenceType()) {
15916 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15917 return QualType();
15918 }
15919 if (ReductionType->isArrayType()) {
15920 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15921 return QualType();
15922 }
15923 return ReductionType;
15924}
15925
15926Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15927 Scope *S, DeclContext *DC, DeclarationName Name,
15928 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15929 AccessSpecifier AS, Decl *PrevDeclInScope) {
15930 SmallVector<Decl *, 8> Decls;
15931 Decls.reserve(ReductionTypes.size());
15932
15933 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015934 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015935 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15936 // A reduction-identifier may not be re-declared in the current scope for the
15937 // same type or for a type that is compatible according to the base language
15938 // rules.
15939 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15940 OMPDeclareReductionDecl *PrevDRD = nullptr;
15941 bool InCompoundScope = true;
15942 if (S != nullptr) {
15943 // Find previous declaration with the same name not referenced in other
15944 // declarations.
15945 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15946 InCompoundScope =
15947 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15948 LookupName(Lookup, S);
15949 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15950 /*AllowInlineNamespace=*/false);
15951 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015952 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015953 while (Filter.hasNext()) {
15954 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15955 if (InCompoundScope) {
15956 auto I = UsedAsPrevious.find(PrevDecl);
15957 if (I == UsedAsPrevious.end())
15958 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015959 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015960 UsedAsPrevious[D] = true;
15961 }
15962 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15963 PrevDecl->getLocation();
15964 }
15965 Filter.done();
15966 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015967 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015968 if (!PrevData.second) {
15969 PrevDRD = PrevData.first;
15970 break;
15971 }
15972 }
15973 }
15974 } else if (PrevDeclInScope != nullptr) {
15975 auto *PrevDRDInScope = PrevDRD =
15976 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15977 do {
15978 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15979 PrevDRDInScope->getLocation();
15980 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15981 } while (PrevDRDInScope != nullptr);
15982 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015983 for (const auto &TyData : ReductionTypes) {
15984 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015985 bool Invalid = false;
15986 if (I != PreviousRedeclTypes.end()) {
15987 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15988 << TyData.first;
15989 Diag(I->second, diag::note_previous_definition);
15990 Invalid = true;
15991 }
15992 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15993 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15994 Name, TyData.first, PrevDRD);
15995 DC->addDecl(DRD);
15996 DRD->setAccess(AS);
15997 Decls.push_back(DRD);
15998 if (Invalid)
15999 DRD->setInvalidDecl();
16000 else
16001 PrevDRD = DRD;
16002 }
16003
16004 return DeclGroupPtrTy::make(
16005 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16006}
16007
16008void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16009 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16010
16011 // Enter new function scope.
16012 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016013 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016014 getCurFunction()->setHasOMPDeclareReductionCombiner();
16015
16016 if (S != nullptr)
16017 PushDeclContext(S, DRD);
16018 else
16019 CurContext = DRD;
16020
Faisal Valid143a0c2017-04-01 21:30:49 +000016021 PushExpressionEvaluationContext(
16022 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016023
16024 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016025 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16026 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16027 // uses semantics of argument handles by value, but it should be passed by
16028 // reference. C lang does not support references, so pass all parameters as
16029 // pointers.
16030 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016031 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016032 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016033 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16034 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16035 // uses semantics of argument handles by value, but it should be passed by
16036 // reference. C lang does not support references, so pass all parameters as
16037 // pointers.
16038 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016039 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016040 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16041 if (S != nullptr) {
16042 PushOnScopeChains(OmpInParm, S);
16043 PushOnScopeChains(OmpOutParm, S);
16044 } else {
16045 DRD->addDecl(OmpInParm);
16046 DRD->addDecl(OmpOutParm);
16047 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016048 Expr *InE =
16049 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16050 Expr *OutE =
16051 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16052 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016053}
16054
16055void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16056 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16057 DiscardCleanupsInEvaluationContext();
16058 PopExpressionEvaluationContext();
16059
16060 PopDeclContext();
16061 PopFunctionScopeInfo();
16062
16063 if (Combiner != nullptr)
16064 DRD->setCombiner(Combiner);
16065 else
16066 DRD->setInvalidDecl();
16067}
16068
Alexey Bataev070f43a2017-09-06 14:49:58 +000016069VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016070 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16071
16072 // Enter new function scope.
16073 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016074 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016075
16076 if (S != nullptr)
16077 PushDeclContext(S, DRD);
16078 else
16079 CurContext = DRD;
16080
Faisal Valid143a0c2017-04-01 21:30:49 +000016081 PushExpressionEvaluationContext(
16082 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016083
16084 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016085 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16086 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16087 // uses semantics of argument handles by value, but it should be passed by
16088 // reference. C lang does not support references, so pass all parameters as
16089 // pointers.
16090 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016091 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016092 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016093 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16094 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16095 // uses semantics of argument handles by value, but it should be passed by
16096 // reference. C lang does not support references, so pass all parameters as
16097 // pointers.
16098 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016099 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016100 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016101 if (S != nullptr) {
16102 PushOnScopeChains(OmpPrivParm, S);
16103 PushOnScopeChains(OmpOrigParm, S);
16104 } else {
16105 DRD->addDecl(OmpPrivParm);
16106 DRD->addDecl(OmpOrigParm);
16107 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016108 Expr *OrigE =
16109 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16110 Expr *PrivE =
16111 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16112 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016113 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016114}
16115
Alexey Bataev070f43a2017-09-06 14:49:58 +000016116void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16117 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016118 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16119 DiscardCleanupsInEvaluationContext();
16120 PopExpressionEvaluationContext();
16121
16122 PopDeclContext();
16123 PopFunctionScopeInfo();
16124
Alexey Bataev070f43a2017-09-06 14:49:58 +000016125 if (Initializer != nullptr) {
16126 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16127 } else if (OmpPrivParm->hasInit()) {
16128 DRD->setInitializer(OmpPrivParm->getInit(),
16129 OmpPrivParm->isDirectInit()
16130 ? OMPDeclareReductionDecl::DirectInit
16131 : OMPDeclareReductionDecl::CopyInit);
16132 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016133 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016134 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016135}
16136
16137Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16138 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016139 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016140 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016141 if (S)
16142 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16143 /*AddToContext=*/false);
16144 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016145 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016146 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016147 }
16148 return DeclReductions;
16149}
16150
Michael Kruse251e1482019-02-01 20:25:04 +000016151TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16152 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16153 QualType T = TInfo->getType();
16154 if (D.isInvalidType())
16155 return true;
16156
16157 if (getLangOpts().CPlusPlus) {
16158 // Check that there are no default arguments (C++ only).
16159 CheckExtraCXXDefaultArguments(D);
16160 }
16161
16162 return CreateParsedType(T, TInfo);
16163}
16164
16165QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16166 TypeResult ParsedType) {
16167 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16168
16169 QualType MapperType = GetTypeFromParser(ParsedType.get());
16170 assert(!MapperType.isNull() && "Expect valid mapper type");
16171
16172 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16173 // The type must be of struct, union or class type in C and C++
16174 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16175 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16176 return QualType();
16177 }
16178 return MapperType;
16179}
16180
16181OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16182 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16183 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16184 Decl *PrevDeclInScope) {
16185 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16186 forRedeclarationInCurContext());
16187 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16188 // A mapper-identifier may not be redeclared in the current scope for the
16189 // same type or for a type that is compatible according to the base language
16190 // rules.
16191 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16192 OMPDeclareMapperDecl *PrevDMD = nullptr;
16193 bool InCompoundScope = true;
16194 if (S != nullptr) {
16195 // Find previous declaration with the same name not referenced in other
16196 // declarations.
16197 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16198 InCompoundScope =
16199 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16200 LookupName(Lookup, S);
16201 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16202 /*AllowInlineNamespace=*/false);
16203 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16204 LookupResult::Filter Filter = Lookup.makeFilter();
16205 while (Filter.hasNext()) {
16206 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16207 if (InCompoundScope) {
16208 auto I = UsedAsPrevious.find(PrevDecl);
16209 if (I == UsedAsPrevious.end())
16210 UsedAsPrevious[PrevDecl] = false;
16211 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16212 UsedAsPrevious[D] = true;
16213 }
16214 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16215 PrevDecl->getLocation();
16216 }
16217 Filter.done();
16218 if (InCompoundScope) {
16219 for (const auto &PrevData : UsedAsPrevious) {
16220 if (!PrevData.second) {
16221 PrevDMD = PrevData.first;
16222 break;
16223 }
16224 }
16225 }
16226 } else if (PrevDeclInScope) {
16227 auto *PrevDMDInScope = PrevDMD =
16228 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16229 do {
16230 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16231 PrevDMDInScope->getLocation();
16232 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16233 } while (PrevDMDInScope != nullptr);
16234 }
16235 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16236 bool Invalid = false;
16237 if (I != PreviousRedeclTypes.end()) {
16238 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16239 << MapperType << Name;
16240 Diag(I->second, diag::note_previous_definition);
16241 Invalid = true;
16242 }
16243 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16244 MapperType, VN, PrevDMD);
16245 DC->addDecl(DMD);
16246 DMD->setAccess(AS);
16247 if (Invalid)
16248 DMD->setInvalidDecl();
16249
16250 // Enter new function scope.
16251 PushFunctionScope();
16252 setFunctionHasBranchProtectedScope();
16253
16254 CurContext = DMD;
16255
16256 return DMD;
16257}
16258
16259void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16260 Scope *S,
16261 QualType MapperType,
16262 SourceLocation StartLoc,
16263 DeclarationName VN) {
16264 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16265 if (S)
16266 PushOnScopeChains(VD, S);
16267 else
16268 DMD->addDecl(VD);
16269 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16270 DMD->setMapperVarRef(MapperVarRefExpr);
16271}
16272
16273Sema::DeclGroupPtrTy
16274Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16275 ArrayRef<OMPClause *> ClauseList) {
16276 PopDeclContext();
16277 PopFunctionScopeInfo();
16278
16279 if (D) {
16280 if (S)
16281 PushOnScopeChains(D, S, /*AddToContext=*/false);
16282 D->CreateClauses(Context, ClauseList);
16283 }
16284
16285 return DeclGroupPtrTy::make(DeclGroupRef(D));
16286}
16287
David Majnemer9d168222016-08-05 17:44:54 +000016288OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016289 SourceLocation StartLoc,
16290 SourceLocation LParenLoc,
16291 SourceLocation EndLoc) {
16292 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016293 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016294
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016295 // OpenMP [teams Constrcut, Restrictions]
16296 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016297 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016298 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016299 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016300
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016301 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016302 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016303 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016304 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016305 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016306 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016307 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16308 HelperValStmt = buildPreInits(Context, Captures);
16309 }
16310
16311 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16312 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016313}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016314
16315OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16316 SourceLocation StartLoc,
16317 SourceLocation LParenLoc,
16318 SourceLocation EndLoc) {
16319 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016320 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016321
16322 // OpenMP [teams Constrcut, Restrictions]
16323 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016324 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016325 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016326 return nullptr;
16327
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016328 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016329 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16330 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016331 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016332 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016333 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016334 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16335 HelperValStmt = buildPreInits(Context, Captures);
16336 }
16337
16338 return new (Context) OMPThreadLimitClause(
16339 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016340}
Alexey Bataeva0569352015-12-01 10:17:31 +000016341
16342OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16343 SourceLocation StartLoc,
16344 SourceLocation LParenLoc,
16345 SourceLocation EndLoc) {
16346 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016347 Stmt *HelperValStmt = nullptr;
16348 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016349
16350 // OpenMP [2.9.1, task Constrcut]
16351 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016352 if (!isNonNegativeIntegerValue(
16353 ValExpr, *this, OMPC_priority,
16354 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16355 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016356 return nullptr;
16357
Alexey Bataev31ba4762019-10-16 18:09:37 +000016358 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16359 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016360}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016361
16362OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16363 SourceLocation StartLoc,
16364 SourceLocation LParenLoc,
16365 SourceLocation EndLoc) {
16366 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016367 Stmt *HelperValStmt = nullptr;
16368 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016369
16370 // OpenMP [2.9.2, taskloop Constrcut]
16371 // The parameter of the grainsize clause must be a positive integer
16372 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016373 if (!isNonNegativeIntegerValue(
16374 ValExpr, *this, OMPC_grainsize,
16375 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16376 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016377 return nullptr;
16378
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016379 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16380 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016381}
Alexey Bataev382967a2015-12-08 12:06:20 +000016382
16383OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16384 SourceLocation StartLoc,
16385 SourceLocation LParenLoc,
16386 SourceLocation EndLoc) {
16387 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016388 Stmt *HelperValStmt = nullptr;
16389 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016390
16391 // OpenMP [2.9.2, taskloop Constrcut]
16392 // The parameter of the num_tasks clause must be a positive integer
16393 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016394 if (!isNonNegativeIntegerValue(
16395 ValExpr, *this, OMPC_num_tasks,
16396 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16397 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016398 return nullptr;
16399
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016400 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16401 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016402}
16403
Alexey Bataev28c75412015-12-15 08:19:24 +000016404OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16405 SourceLocation LParenLoc,
16406 SourceLocation EndLoc) {
16407 // OpenMP [2.13.2, critical construct, Description]
16408 // ... where hint-expression is an integer constant expression that evaluates
16409 // to a valid lock hint.
16410 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16411 if (HintExpr.isInvalid())
16412 return nullptr;
16413 return new (Context)
16414 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16415}
16416
Carlo Bertollib4adf552016-01-15 18:50:31 +000016417OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16418 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16419 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16420 SourceLocation EndLoc) {
16421 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16422 std::string Values;
16423 Values += "'";
16424 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16425 Values += "'";
16426 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16427 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16428 return nullptr;
16429 }
16430 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016431 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016432 if (ChunkSize) {
16433 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16434 !ChunkSize->isInstantiationDependent() &&
16435 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016436 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016437 ExprResult Val =
16438 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16439 if (Val.isInvalid())
16440 return nullptr;
16441
16442 ValExpr = Val.get();
16443
16444 // OpenMP [2.7.1, Restrictions]
16445 // chunk_size must be a loop invariant integer expression with a positive
16446 // value.
16447 llvm::APSInt Result;
16448 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16449 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16450 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16451 << "dist_schedule" << ChunkSize->getSourceRange();
16452 return nullptr;
16453 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016454 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016455 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16456 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016457 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016458 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016459 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016460 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16461 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016462 }
16463 }
16464 }
16465
16466 return new (Context)
16467 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016468 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016469}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016470
16471OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16472 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16473 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16474 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016475 if (getLangOpts().OpenMP < 50) {
16476 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16477 Kind != OMPC_DEFAULTMAP_scalar) {
16478 std::string Value;
16479 SourceLocation Loc;
16480 Value += "'";
16481 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16482 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16483 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16484 Loc = MLoc;
16485 } else {
16486 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16487 OMPC_DEFAULTMAP_scalar);
16488 Loc = KindLoc;
16489 }
16490 Value += "'";
16491 Diag(Loc, diag::err_omp_unexpected_clause_value)
16492 << Value << getOpenMPClauseName(OMPC_defaultmap);
16493 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016494 }
cchene06f3e02019-11-15 13:02:06 -050016495 } else {
16496 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16497 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16498 if (!isDefaultmapKind || !isDefaultmapModifier) {
16499 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16500 "'firstprivate', 'none', 'default'";
16501 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16502 if (!isDefaultmapKind && isDefaultmapModifier) {
16503 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16504 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16505 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16506 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16507 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16508 } else {
16509 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16510 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16511 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16512 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16513 }
16514 return nullptr;
16515 }
16516
16517 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16518 // At most one defaultmap clause for each category can appear on the
16519 // directive.
16520 if (DSAStack->checkDefaultmapCategory(Kind)) {
16521 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16522 return nullptr;
16523 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016524 }
cchene06f3e02019-11-15 13:02:06 -050016525 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016526
16527 return new (Context)
16528 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16529}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016530
16531bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16532 DeclContext *CurLexicalContext = getCurLexicalContext();
16533 if (!CurLexicalContext->isFileContext() &&
16534 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016535 !CurLexicalContext->isExternCXXContext() &&
16536 !isa<CXXRecordDecl>(CurLexicalContext) &&
16537 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16538 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16539 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016540 Diag(Loc, diag::err_omp_region_not_file_context);
16541 return false;
16542 }
Kelvin Libc38e632018-09-10 02:07:09 +000016543 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016544 return true;
16545}
16546
16547void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016548 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016549 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016550 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016551}
16552
Alexey Bataev729e2422019-08-23 16:11:14 +000016553NamedDecl *
16554Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16555 const DeclarationNameInfo &Id,
16556 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016557 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16558 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16559
16560 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016561 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016562 Lookup.suppressDiagnostics();
16563
16564 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016565 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016566 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016567 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016568 CTK_ErrorRecovery)) {
16569 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16570 << Id.getName());
16571 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016572 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016573 }
16574
16575 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016576 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016577 }
16578
16579 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016580 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16581 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016582 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016583 return nullptr;
16584 }
16585 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16586 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16587 return ND;
16588}
16589
16590void Sema::ActOnOpenMPDeclareTargetName(
16591 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16592 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16593 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16594 isa<FunctionTemplateDecl>(ND)) &&
16595 "Expected variable, function or function template.");
16596
16597 // Diagnose marking after use as it may lead to incorrect diagnosis and
16598 // codegen.
16599 if (LangOpts.OpenMP >= 50 &&
16600 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16601 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16602
16603 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16604 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16605 if (DevTy.hasValue() && *DevTy != DT) {
16606 Diag(Loc, diag::err_omp_device_type_mismatch)
16607 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16608 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16609 return;
16610 }
16611 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16612 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16613 if (!Res) {
16614 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16615 SourceRange(Loc, Loc));
16616 ND->addAttr(A);
16617 if (ASTMutationListener *ML = Context.getASTMutationListener())
16618 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16619 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16620 } else if (*Res != MT) {
16621 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016622 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016623}
16624
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016625static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16626 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016627 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016628 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016629 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016630 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16631 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16632 if (SemaRef.LangOpts.OpenMP >= 50 &&
16633 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16634 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16635 VD->hasGlobalStorage()) {
16636 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16637 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16638 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16639 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16640 // If a lambda declaration and definition appears between a
16641 // declare target directive and the matching end declare target
16642 // directive, all variables that are captured by the lambda
16643 // expression must also appear in a to clause.
16644 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016645 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016646 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16647 << VD << 0 << SR;
16648 return;
16649 }
16650 }
16651 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016652 return;
16653 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16654 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016655}
16656
16657static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16658 Sema &SemaRef, DSAStackTy *Stack,
16659 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016660 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016661 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16662 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016663}
16664
Kelvin Li1ce87c72017-12-12 20:08:12 +000016665void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16666 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016667 if (!D || D->isInvalidDecl())
16668 return;
16669 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016670 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016671 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016672 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016673 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16674 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016675 return;
16676 // 2.10.6: threadprivate variable cannot appear in a declare target
16677 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016678 if (DSAStack->isThreadPrivate(VD)) {
16679 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016680 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016681 return;
16682 }
16683 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016684 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16685 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016686 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016687 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16688 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016689 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016690 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16691 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16692 return;
16693 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016694 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016695 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16696 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16697 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16698 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016699 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016700 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16701 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16702 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016703 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016704 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16705 // Problem if any with var declared with incomplete type will be reported
16706 // as normal, so no need to check it here.
16707 if ((E || !VD->getType()->isIncompleteType()) &&
16708 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16709 return;
16710 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16711 // Checking declaration inside declare target region.
16712 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16713 isa<FunctionTemplateDecl>(D)) {
16714 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016715 Context, OMPDeclareTargetDeclAttr::MT_To,
16716 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016717 D->addAttr(A);
16718 if (ASTMutationListener *ML = Context.getASTMutationListener())
16719 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16720 }
16721 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016722 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016723 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016724 if (!E)
16725 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016726 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16727}
Samuel Antao661c0902016-05-26 17:39:58 +000016728
16729OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016730 CXXScopeSpec &MapperIdScopeSpec,
16731 DeclarationNameInfo &MapperId,
16732 const OMPVarListLocTy &Locs,
16733 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016734 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016735 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16736 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016737 if (MVLI.ProcessedVarList.empty())
16738 return nullptr;
16739
Michael Kruse01f670d2019-02-22 22:29:42 +000016740 return OMPToClause::Create(
16741 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16742 MVLI.VarComponents, MVLI.UDMapperList,
16743 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016744}
Samuel Antaoec172c62016-05-26 17:49:04 +000016745
16746OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016747 CXXScopeSpec &MapperIdScopeSpec,
16748 DeclarationNameInfo &MapperId,
16749 const OMPVarListLocTy &Locs,
16750 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016751 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016752 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16753 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016754 if (MVLI.ProcessedVarList.empty())
16755 return nullptr;
16756
Michael Kruse0336c752019-02-25 20:34:15 +000016757 return OMPFromClause::Create(
16758 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16759 MVLI.VarComponents, MVLI.UDMapperList,
16760 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016761}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016762
16763OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016764 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016765 MappableVarListInfo MVLI(VarList);
16766 SmallVector<Expr *, 8> PrivateCopies;
16767 SmallVector<Expr *, 8> Inits;
16768
Alexey Bataeve3727102018-04-18 15:57:46 +000016769 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016770 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16771 SourceLocation ELoc;
16772 SourceRange ERange;
16773 Expr *SimpleRefExpr = RefExpr;
16774 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16775 if (Res.second) {
16776 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016777 MVLI.ProcessedVarList.push_back(RefExpr);
16778 PrivateCopies.push_back(nullptr);
16779 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016780 }
16781 ValueDecl *D = Res.first;
16782 if (!D)
16783 continue;
16784
16785 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016786 Type = Type.getNonReferenceType().getUnqualifiedType();
16787
16788 auto *VD = dyn_cast<VarDecl>(D);
16789
16790 // Item should be a pointer or reference to pointer.
16791 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016792 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16793 << 0 << RefExpr->getSourceRange();
16794 continue;
16795 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016796
16797 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016798 auto VDPrivate =
16799 buildVarDecl(*this, ELoc, Type, D->getName(),
16800 D->hasAttrs() ? &D->getAttrs() : nullptr,
16801 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016802 if (VDPrivate->isInvalidDecl())
16803 continue;
16804
16805 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016806 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016807 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16808
16809 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016810 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016811 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016812 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16813 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016814 AddInitializerToDecl(VDPrivate,
16815 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016816 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016817
16818 // If required, build a capture to implement the privatization initialized
16819 // with the current list item value.
16820 DeclRefExpr *Ref = nullptr;
16821 if (!VD)
16822 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16823 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16824 PrivateCopies.push_back(VDPrivateRefExpr);
16825 Inits.push_back(VDInitRefExpr);
16826
16827 // We need to add a data sharing attribute for this variable to make sure it
16828 // is correctly captured. A variable that shows up in a use_device_ptr has
16829 // similar properties of a first private variable.
16830 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16831
16832 // Create a mappable component for the list item. List items in this clause
16833 // only need a component.
16834 MVLI.VarBaseDeclarations.push_back(D);
16835 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16836 MVLI.VarComponents.back().push_back(
16837 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016838 }
16839
Samuel Antaocc10b852016-07-28 14:23:26 +000016840 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016841 return nullptr;
16842
Samuel Antaocc10b852016-07-28 14:23:26 +000016843 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016844 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16845 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016846}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016847
16848OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016849 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016850 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016851 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016852 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016853 SourceLocation ELoc;
16854 SourceRange ERange;
16855 Expr *SimpleRefExpr = RefExpr;
16856 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16857 if (Res.second) {
16858 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016859 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016860 }
16861 ValueDecl *D = Res.first;
16862 if (!D)
16863 continue;
16864
16865 QualType Type = D->getType();
16866 // item should be a pointer or array or reference to pointer or array
16867 if (!Type.getNonReferenceType()->isPointerType() &&
16868 !Type.getNonReferenceType()->isArrayType()) {
16869 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16870 << 0 << RefExpr->getSourceRange();
16871 continue;
16872 }
Samuel Antao6890b092016-07-28 14:25:09 +000016873
16874 // Check if the declaration in the clause does not show up in any data
16875 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016876 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016877 if (isOpenMPPrivate(DVar.CKind)) {
16878 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16879 << getOpenMPClauseName(DVar.CKind)
16880 << getOpenMPClauseName(OMPC_is_device_ptr)
16881 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016882 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016883 continue;
16884 }
16885
Alexey Bataeve3727102018-04-18 15:57:46 +000016886 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016887 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016888 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016889 [&ConflictExpr](
16890 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16891 OpenMPClauseKind) -> bool {
16892 ConflictExpr = R.front().getAssociatedExpression();
16893 return true;
16894 })) {
16895 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16896 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16897 << ConflictExpr->getSourceRange();
16898 continue;
16899 }
16900
16901 // Store the components in the stack so that they can be used to check
16902 // against other clauses later on.
16903 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16904 DSAStack->addMappableExpressionComponents(
16905 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16906
16907 // Record the expression we've just processed.
16908 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16909
16910 // Create a mappable component for the list item. List items in this clause
16911 // only need a component. We use a null declaration to signal fields in
16912 // 'this'.
16913 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16914 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16915 "Unexpected device pointer expression!");
16916 MVLI.VarBaseDeclarations.push_back(
16917 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16918 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16919 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016920 }
16921
Samuel Antao6890b092016-07-28 14:25:09 +000016922 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016923 return nullptr;
16924
Michael Kruse4304e9d2019-02-19 16:38:20 +000016925 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16926 MVLI.VarBaseDeclarations,
16927 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016928}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016929
16930OMPClause *Sema::ActOnOpenMPAllocateClause(
16931 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16932 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16933 if (Allocator) {
16934 // OpenMP [2.11.4 allocate Clause, Description]
16935 // allocator is an expression of omp_allocator_handle_t type.
16936 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16937 return nullptr;
16938
16939 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16940 if (AllocatorRes.isInvalid())
16941 return nullptr;
16942 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16943 DSAStack->getOMPAllocatorHandleT(),
16944 Sema::AA_Initializing,
16945 /*AllowExplicit=*/true);
16946 if (AllocatorRes.isInvalid())
16947 return nullptr;
16948 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016949 } else {
16950 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16951 // allocate clauses that appear on a target construct or on constructs in a
16952 // target region must specify an allocator expression unless a requires
16953 // directive with the dynamic_allocators clause is present in the same
16954 // compilation unit.
16955 if (LangOpts.OpenMPIsDevice &&
16956 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16957 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016958 }
16959 // Analyze and build list of variables.
16960 SmallVector<Expr *, 8> Vars;
16961 for (Expr *RefExpr : VarList) {
16962 assert(RefExpr && "NULL expr in OpenMP private clause.");
16963 SourceLocation ELoc;
16964 SourceRange ERange;
16965 Expr *SimpleRefExpr = RefExpr;
16966 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16967 if (Res.second) {
16968 // It will be analyzed later.
16969 Vars.push_back(RefExpr);
16970 }
16971 ValueDecl *D = Res.first;
16972 if (!D)
16973 continue;
16974
16975 auto *VD = dyn_cast<VarDecl>(D);
16976 DeclRefExpr *Ref = nullptr;
16977 if (!VD && !CurContext->isDependentContext())
16978 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16979 Vars.push_back((VD || CurContext->isDependentContext())
16980 ? RefExpr->IgnoreParens()
16981 : Ref);
16982 }
16983
16984 if (Vars.empty())
16985 return nullptr;
16986
16987 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16988 ColonLoc, EndLoc, Vars);
16989}