Bug Summary

File:clang/lib/Sema/SemaOpenMP.cpp
Warning:line 1970, column 38
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOpenMP.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp
1//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements semantic analysis for OpenMP directives and
10/// clauses.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeOrdering.h"
25#include "clang/Basic/OpenMPKinds.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
30#include "clang/Sema/SemaInternal.h"
31#include "llvm/ADT/PointerEmbeddedInt.h"
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
38static const Expr *checkMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind, bool NoDiagnose);
42
43namespace {
44/// Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
46 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'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55};
56
57/// Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
59class DSAStackTy {
60public:
61 struct DSAVarData {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 const Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
66 SourceLocation ImplicitDSALoc;
67 DSAVarData() = default;
68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73 };
74 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78
79private:
80 struct DSAInfo {
81 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85 DeclRefExpr *PrivateCopy = nullptr;
86 };
87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
98 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102 struct ReductionData {
103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104 SourceRange ReductionRange;
105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118
119 struct SharingMapTy {
120 DeclSAMapTy SharingMap;
121 DeclReductionMapTy ReductionMap;
122 AlignedMapTy AlignedMap;
123 MappedExprComponentsTy MappedExprComponents;
124 LoopControlVariablesMapTy LCVMap;
125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126 SourceLocation DefaultAttrLoc;
127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
129 OpenMPDirectiveKind Directive = OMPD_unknown;
130 DeclarationNameInfo DirectiveName;
131 Scope *CurScope = nullptr;
132 SourceLocation ConstructLoc;
133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
137 /// First argument (Expr *) contains optional argument of the
138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141 unsigned AssociatedLoops = 1;
142 bool HasMutipleLoops = false;
143 const Decl *PossiblyLoopCounter = nullptr;
144 bool NowaitRegion = false;
145 bool CancelRegion = false;
146 bool LoopStart = false;
147 bool BodyComplete = false;
148 SourceLocation InnerTeamsRegionLoc;
149 /// Reference to the taskgroup task_reduction reference expression.
150 Expr *TaskgroupReductionRef = nullptr;
151 llvm::DenseSet<QualType> MappedClassesQualTypes;
152 /// List of globals marked as declare target link in this target region
153 /// (isOpenMPTargetExecutionDirective(Directive) == true).
154 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
155 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
156 Scope *CurScope, SourceLocation Loc)
157 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
158 ConstructLoc(Loc) {}
159 SharingMapTy() = default;
160 };
161
162 using StackTy = SmallVector<SharingMapTy, 4>;
163
164 /// Stack of used declaration and their data-sharing attributes.
165 DeclSAMapTy Threadprivates;
166 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
167 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
168 /// true, if check for DSA must be from parent directive, false, if
169 /// from current directive.
170 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
171 Sema &SemaRef;
172 bool ForceCapturing = false;
173 /// true if all the variables in the target executable directives must be
174 /// captured by reference.
175 bool ForceCaptureByReferenceInTargetExecutable = false;
176 CriticalsWithHintsTy Criticals;
177 unsigned IgnoredStackElements = 0;
178
179 /// Iterators over the stack iterate in order from innermost to outermost
180 /// directive.
181 using const_iterator = StackTy::const_reverse_iterator;
182 const_iterator begin() const {
183 return Stack.empty() ? const_iterator()
184 : Stack.back().first.rbegin() + IgnoredStackElements;
185 }
186 const_iterator end() const {
187 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
188 }
189 using iterator = StackTy::reverse_iterator;
190 iterator begin() {
191 return Stack.empty() ? iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
193 }
194 iterator end() {
195 return Stack.empty() ? iterator() : Stack.back().first.rend();
196 }
197
198 // Convenience operations to get at the elements of the stack.
199
200 bool isStackEmpty() const {
201 return Stack.empty() ||
202 Stack.back().second != CurrentNonCapturingFunctionScope ||
203 Stack.back().first.size() <= IgnoredStackElements;
204 }
205 size_t getStackSize() const {
206 return isStackEmpty() ? 0
207 : Stack.back().first.size() - IgnoredStackElements;
208 }
209
210 SharingMapTy *getTopOfStackOrNull() {
211 size_t Size = getStackSize();
212 if (Size == 0)
213 return nullptr;
214 return &Stack.back().first[Size - 1];
215 }
216 const SharingMapTy *getTopOfStackOrNull() const {
217 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
218 }
219 SharingMapTy &getTopOfStack() {
220 assert(!isStackEmpty() && "no current directive")((!isStackEmpty() && "no current directive") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && \"no current directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 220, __PRETTY_FUNCTION__))
;
221 return *getTopOfStackOrNull();
222 }
223 const SharingMapTy &getTopOfStack() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStack();
225 }
226
227 SharingMapTy *getSecondOnStackOrNull() {
228 size_t Size = getStackSize();
229 if (Size <= 1)
230 return nullptr;
231 return &Stack.back().first[Size - 2];
232 }
233 const SharingMapTy *getSecondOnStackOrNull() const {
234 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
235 }
236
237 /// Get the stack element at a certain level (previously returned by
238 /// \c getNestingLevel).
239 ///
240 /// Note that nesting levels count from outermost to innermost, and this is
241 /// the reverse of our iteration order where new inner levels are pushed at
242 /// the front of the stack.
243 SharingMapTy &getStackElemAtLevel(unsigned Level) {
244 assert(Level < getStackSize() && "no such stack element")((Level < getStackSize() && "no such stack element"
) ? static_cast<void> (0) : __assert_fail ("Level < getStackSize() && \"no such stack element\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 244, __PRETTY_FUNCTION__))
;
245 return Stack.back().first[Level];
246 }
247 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
248 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
249 }
250
251 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
252
253 /// Checks if the variable is a local for OpenMP region.
254 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
255
256 /// Vector of previously declared requires directives
257 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
258 /// omp_allocator_handle_t type.
259 QualType OMPAllocatorHandleT;
260 /// Expression for the predefined allocators.
261 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
262 nullptr};
263 /// Vector of previously encountered target directives
264 SmallVector<SourceLocation, 2> TargetLocations;
265
266public:
267 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
268
269 /// Sets omp_allocator_handle_t type.
270 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
271 /// Gets omp_allocator_handle_t type.
272 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
273 /// Sets the given default allocator.
274 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
275 Expr *Allocator) {
276 OMPPredefinedAllocators[AllocatorKind] = Allocator;
277 }
278 /// Returns the specified default allocator.
279 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
280 return OMPPredefinedAllocators[AllocatorKind];
281 }
282
283 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
12
Assuming field 'ClauseKindMode' is equal to OMPC_unknown
13
Returning zero, which participates in a condition later
284 OpenMPClauseKind getClauseParsingMode() const {
285 assert(isClauseParsingMode() && "Must be in clause parsing mode.")((isClauseParsingMode() && "Must be in clause parsing mode."
) ? static_cast<void> (0) : __assert_fail ("isClauseParsingMode() && \"Must be in clause parsing mode.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 285, __PRETTY_FUNCTION__))
;
286 return ClauseKindMode;
287 }
288 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
289
290 bool isBodyComplete() const {
291 const SharingMapTy *Top = getTopOfStackOrNull();
292 return Top && Top->BodyComplete;
293 }
294 void setBodyComplete() {
295 getTopOfStack().BodyComplete = true;
296 }
297
298 bool isForceVarCapturing() const { return ForceCapturing; }
299 void setForceVarCapturing(bool V) { ForceCapturing = V; }
300
301 void setForceCaptureByReferenceInTargetExecutable(bool V) {
302 ForceCaptureByReferenceInTargetExecutable = V;
303 }
304 bool isForceCaptureByReferenceInTargetExecutable() const {
305 return ForceCaptureByReferenceInTargetExecutable;
306 }
307
308 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
309 Scope *CurScope, SourceLocation Loc) {
310 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 311, __PRETTY_FUNCTION__))
311 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 311, __PRETTY_FUNCTION__))
;
312 if (Stack.empty() ||
313 Stack.back().second != CurrentNonCapturingFunctionScope)
314 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
315 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
316 Stack.back().first.back().DefaultAttrLoc = Loc;
317 }
318
319 void pop() {
320 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 321, __PRETTY_FUNCTION__))
321 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 321, __PRETTY_FUNCTION__))
;
322 assert(!Stack.back().first.empty() &&((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 323, __PRETTY_FUNCTION__))
323 "Data-sharing attributes stack is empty!")((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 323, __PRETTY_FUNCTION__))
;
324 Stack.back().first.pop_back();
325 }
326
327 /// RAII object to temporarily leave the scope of a directive when we want to
328 /// logically operate in its parent.
329 class ParentDirectiveScope {
330 DSAStackTy &Self;
331 bool Active;
332 public:
333 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
334 : Self(Self), Active(false) {
335 if (Activate)
336 enable();
337 }
338 ~ParentDirectiveScope() { disable(); }
339 void disable() {
340 if (Active) {
341 --Self.IgnoredStackElements;
342 Active = false;
343 }
344 }
345 void enable() {
346 if (!Active) {
347 ++Self.IgnoredStackElements;
348 Active = true;
349 }
350 }
351 };
352
353 /// Marks that we're started loop parsing.
354 void loopInit() {
355 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 356, __PRETTY_FUNCTION__))
356 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 356, __PRETTY_FUNCTION__))
;
357 getTopOfStack().LoopStart = true;
358 }
359 /// Start capturing of the variables in the loop context.
360 void loopStart() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 362, __PRETTY_FUNCTION__))
362 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 362, __PRETTY_FUNCTION__))
;
363 getTopOfStack().LoopStart = false;
364 }
365 /// true, if variables are captured, false otherwise.
366 bool isLoopStarted() const {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 368, __PRETTY_FUNCTION__))
368 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 368, __PRETTY_FUNCTION__))
;
369 return !getTopOfStack().LoopStart;
370 }
371 /// Marks (or clears) declaration as possibly loop counter.
372 void resetPossibleLoopCounter(const Decl *D = nullptr) {
373 getTopOfStack().PossiblyLoopCounter =
374 D ? D->getCanonicalDecl() : D;
375 }
376 /// Gets the possible loop counter decl.
377 const Decl *getPossiblyLoopCunter() const {
378 return getTopOfStack().PossiblyLoopCounter;
379 }
380 /// Start new OpenMP region stack in new non-capturing function.
381 void pushFunction() {
382 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 383, __PRETTY_FUNCTION__))
383 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 383, __PRETTY_FUNCTION__))
;
384 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
385 assert(!isa<CapturingScopeInfo>(CurFnScope))((!isa<CapturingScopeInfo>(CurFnScope)) ? static_cast<
void> (0) : __assert_fail ("!isa<CapturingScopeInfo>(CurFnScope)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 385, __PRETTY_FUNCTION__))
;
386 CurrentNonCapturingFunctionScope = CurFnScope;
387 }
388 /// Pop region stack for non-capturing function.
389 void popFunction(const FunctionScopeInfo *OldFSI) {
390 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 391, __PRETTY_FUNCTION__))
391 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 391, __PRETTY_FUNCTION__))
;
392 if (!Stack.empty() && Stack.back().second == OldFSI) {
393 assert(Stack.back().first.empty())((Stack.back().first.empty()) ? static_cast<void> (0) :
__assert_fail ("Stack.back().first.empty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 393, __PRETTY_FUNCTION__))
;
394 Stack.pop_back();
395 }
396 CurrentNonCapturingFunctionScope = nullptr;
397 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
398 if (!isa<CapturingScopeInfo>(FSI)) {
399 CurrentNonCapturingFunctionScope = FSI;
400 break;
401 }
402 }
403 }
404
405 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
406 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
407 }
408 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
409 getCriticalWithHint(const DeclarationNameInfo &Name) const {
410 auto I = Criticals.find(Name.getAsString());
411 if (I != Criticals.end())
412 return I->second;
413 return std::make_pair(nullptr, llvm::APSInt());
414 }
415 /// If 'aligned' declaration for given variable \a D was not seen yet,
416 /// add it and return NULL; otherwise return previous occurrence's expression
417 /// for diagnostics.
418 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
419
420 /// Register specified variable as loop control variable.
421 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
422 /// Check if the specified variable is a loop control variable for
423 /// current region.
424 /// \return The index of the loop control variable in the list of associated
425 /// for-loops (from outer to inner).
426 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
427 /// Check if the specified variable is a loop control variable for
428 /// parent region.
429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
431 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
432 /// Get the loop control variable for the I-th loop (or nullptr) in
433 /// parent directive.
434 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
435
436 /// Adds explicit data sharing attribute to the specified declaration.
437 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
438 DeclRefExpr *PrivateCopy = nullptr);
439
440 /// Adds additional information for the reduction items with the reduction id
441 /// represented as an operator.
442 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
443 BinaryOperatorKind BOK);
444 /// Adds additional information for the reduction items with the reduction id
445 /// represented as reduction identifier.
446 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
447 const Expr *ReductionRef);
448 /// Returns the location and reduction operation from the innermost parent
449 /// region for the given \p D.
450 const DSAVarData
451 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
452 BinaryOperatorKind &BOK,
453 Expr *&TaskgroupDescriptor) const;
454 /// Returns the location and reduction operation from the innermost parent
455 /// region for the given \p D.
456 const DSAVarData
457 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
458 const Expr *&ReductionRef,
459 Expr *&TaskgroupDescriptor) const;
460 /// Return reduction reference expression for the current taskgroup.
461 Expr *getTaskgroupReductionRef() const {
462 assert(getTopOfStack().Directive == OMPD_taskgroup &&((getTopOfStack().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"getTopOfStack().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 464, __PRETTY_FUNCTION__))
463 "taskgroup reference expression requested for non taskgroup "((getTopOfStack().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"getTopOfStack().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 464, __PRETTY_FUNCTION__))
464 "directive.")((getTopOfStack().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"getTopOfStack().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 464, __PRETTY_FUNCTION__))
;
465 return getTopOfStack().TaskgroupReductionRef;
466 }
467 /// Checks if the given \p VD declaration is actually a taskgroup reduction
468 /// descriptor variable at the \p Level of OpenMP regions.
469 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
470 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
471 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
472 ->getDecl() == VD;
473 }
474
475 /// Returns data sharing attributes from top of the stack for the
476 /// specified declaration.
477 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
478 /// Returns data-sharing attributes for the specified declaration.
479 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
480 /// Checks if the specified variables has data-sharing attributes which
481 /// match specified \a CPred predicate in any directive which matches \a DPred
482 /// predicate.
483 const DSAVarData
484 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
485 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
486 bool FromParent) const;
487 /// Checks if the specified variables has data-sharing attributes which
488 /// match specified \a CPred predicate in any innermost directive which
489 /// matches \a DPred predicate.
490 const DSAVarData
491 hasInnermostDSA(ValueDecl *D,
492 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
493 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
494 bool FromParent) const;
495 /// Checks if the specified variables has explicit data-sharing
496 /// attributes which match specified \a CPred predicate at the specified
497 /// OpenMP region.
498 bool hasExplicitDSA(const ValueDecl *D,
499 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
500 unsigned Level, bool NotLastprivate = false) const;
501
502 /// Returns true if the directive at level \Level matches in the
503 /// specified \a DPred predicate.
504 bool hasExplicitDirective(
505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
506 unsigned Level) const;
507
508 /// Finds a directive which matches specified \a DPred predicate.
509 bool hasDirective(
510 const llvm::function_ref<bool(
511 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
512 DPred,
513 bool FromParent) const;
514
515 /// Returns currently analyzed directive.
516 OpenMPDirectiveKind getCurrentDirective() const {
517 const SharingMapTy *Top = getTopOfStackOrNull();
518 return Top ? Top->Directive : OMPD_unknown;
519 }
520 /// Returns directive kind at specified level.
521 OpenMPDirectiveKind getDirective(unsigned Level) const {
522 assert(!isStackEmpty() && "No directive at specified level.")((!isStackEmpty() && "No directive at specified level."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"No directive at specified level.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 522, __PRETTY_FUNCTION__))
;
523 return getStackElemAtLevel(Level).Directive;
524 }
525 /// Returns the capture region at the specified level.
526 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
527 unsigned OpenMPCaptureLevel) const {
528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
529 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
530 return CaptureRegions[OpenMPCaptureLevel];
531 }
532 /// Returns parent directive.
533 OpenMPDirectiveKind getParentDirective() const {
534 const SharingMapTy *Parent = getSecondOnStackOrNull();
535 return Parent ? Parent->Directive : OMPD_unknown;
536 }
537
538 /// Add requires decl to internal vector
539 void addRequiresDecl(OMPRequiresDecl *RD) {
540 RequiresDecls.push_back(RD);
541 }
542
543 /// Checks if the defined 'requires' directive has specified type of clause.
544 template <typename ClauseType>
545 bool hasRequiresDeclWithClause() {
546 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
547 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
548 return isa<ClauseType>(C);
549 });
550 });
551 }
552
553 /// Checks for a duplicate clause amongst previously declared requires
554 /// directives
555 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
556 bool IsDuplicate = false;
557 for (OMPClause *CNew : ClauseList) {
558 for (const OMPRequiresDecl *D : RequiresDecls) {
559 for (const OMPClause *CPrev : D->clauselists()) {
560 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
561 SemaRef.Diag(CNew->getBeginLoc(),
562 diag::err_omp_requires_clause_redeclaration)
563 << getOpenMPClauseName(CNew->getClauseKind());
564 SemaRef.Diag(CPrev->getBeginLoc(),
565 diag::note_omp_requires_previous_clause)
566 << getOpenMPClauseName(CPrev->getClauseKind());
567 IsDuplicate = true;
568 }
569 }
570 }
571 }
572 return IsDuplicate;
573 }
574
575 /// Add location of previously encountered target to internal vector
576 void addTargetDirLocation(SourceLocation LocStart) {
577 TargetLocations.push_back(LocStart);
578 }
579
580 // Return previously encountered target region locations.
581 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
582 return TargetLocations;
583 }
584
585 /// Set default data sharing attribute to none.
586 void setDefaultDSANone(SourceLocation Loc) {
587 getTopOfStack().DefaultAttr = DSA_none;
588 getTopOfStack().DefaultAttrLoc = Loc;
589 }
590 /// Set default data sharing attribute to shared.
591 void setDefaultDSAShared(SourceLocation Loc) {
592 getTopOfStack().DefaultAttr = DSA_shared;
593 getTopOfStack().DefaultAttrLoc = Loc;
594 }
595 /// Set default data mapping attribute to 'tofrom:scalar'.
596 void setDefaultDMAToFromScalar(SourceLocation Loc) {
597 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
598 getTopOfStack().DefaultMapAttrLoc = Loc;
599 }
600
601 DefaultDataSharingAttributes getDefaultDSA() const {
602 return isStackEmpty() ? DSA_unspecified
603 : getTopOfStack().DefaultAttr;
604 }
605 SourceLocation getDefaultDSALocation() const {
606 return isStackEmpty() ? SourceLocation()
607 : getTopOfStack().DefaultAttrLoc;
608 }
609 DefaultMapAttributes getDefaultDMA() const {
610 return isStackEmpty() ? DMA_unspecified
611 : getTopOfStack().DefaultMapAttr;
612 }
613 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
614 return getStackElemAtLevel(Level).DefaultMapAttr;
615 }
616 SourceLocation getDefaultDMALocation() const {
617 return isStackEmpty() ? SourceLocation()
618 : getTopOfStack().DefaultMapAttrLoc;
619 }
620
621 /// Checks if the specified variable is a threadprivate.
622 bool isThreadPrivate(VarDecl *D) {
623 const DSAVarData DVar = getTopDSA(D, false);
624 return isOpenMPThreadPrivate(DVar.CKind);
625 }
626
627 /// Marks current region as ordered (it has an 'ordered' clause).
628 void setOrderedRegion(bool IsOrdered, const Expr *Param,
629 OMPOrderedClause *Clause) {
630 if (IsOrdered)
631 getTopOfStack().OrderedRegion.emplace(Param, Clause);
632 else
633 getTopOfStack().OrderedRegion.reset();
634 }
635 /// Returns true, if region is ordered (has associated 'ordered' clause),
636 /// false - otherwise.
637 bool isOrderedRegion() const {
638 if (const SharingMapTy *Top = getTopOfStackOrNull())
639 return Top->OrderedRegion.hasValue();
640 return false;
641 }
642 /// Returns optional parameter for the ordered region.
643 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
644 if (const SharingMapTy *Top = getTopOfStackOrNull())
645 if (Top->OrderedRegion.hasValue())
646 return Top->OrderedRegion.getValue();
647 return std::make_pair(nullptr, nullptr);
648 }
649 /// Returns true, if parent region is ordered (has associated
650 /// 'ordered' clause), false - otherwise.
651 bool isParentOrderedRegion() const {
652 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
653 return Parent->OrderedRegion.hasValue();
654 return false;
655 }
656 /// Returns optional parameter for the ordered region.
657 std::pair<const Expr *, OMPOrderedClause *>
658 getParentOrderedRegionParam() const {
659 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
660 if (Parent->OrderedRegion.hasValue())
661 return Parent->OrderedRegion.getValue();
662 return std::make_pair(nullptr, nullptr);
663 }
664 /// Marks current region as nowait (it has a 'nowait' clause).
665 void setNowaitRegion(bool IsNowait = true) {
666 getTopOfStack().NowaitRegion = IsNowait;
667 }
668 /// Returns true, if parent region is nowait (has associated
669 /// 'nowait' clause), false - otherwise.
670 bool isParentNowaitRegion() const {
671 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
672 return Parent->NowaitRegion;
673 return false;
674 }
675 /// Marks parent region as cancel region.
676 void setParentCancelRegion(bool Cancel = true) {
677 if (SharingMapTy *Parent = getSecondOnStackOrNull())
678 Parent->CancelRegion |= Cancel;
679 }
680 /// Return true if current region has inner cancel construct.
681 bool isCancelRegion() const {
682 const SharingMapTy *Top = getTopOfStackOrNull();
683 return Top ? Top->CancelRegion : false;
684 }
685
686 /// Set collapse value for the region.
687 void setAssociatedLoops(unsigned Val) {
688 getTopOfStack().AssociatedLoops = Val;
689 if (Val > 1)
690 getTopOfStack().HasMutipleLoops = true;
691 }
692 /// Return collapse value for region.
693 unsigned getAssociatedLoops() const {
694 const SharingMapTy *Top = getTopOfStackOrNull();
695 return Top ? Top->AssociatedLoops : 0;
696 }
697 /// Returns true if the construct is associated with multiple loops.
698 bool hasMutipleLoops() const {
699 const SharingMapTy *Top = getTopOfStackOrNull();
700 return Top ? Top->HasMutipleLoops : false;
701 }
702
703 /// Marks current target region as one with closely nested teams
704 /// region.
705 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
706 if (SharingMapTy *Parent = getSecondOnStackOrNull())
707 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
708 }
709 /// Returns true, if current region has closely nested teams region.
710 bool hasInnerTeamsRegion() const {
711 return getInnerTeamsRegionLoc().isValid();
712 }
713 /// Returns location of the nested teams region (if any).
714 SourceLocation getInnerTeamsRegionLoc() const {
715 const SharingMapTy *Top = getTopOfStackOrNull();
716 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
717 }
718
719 Scope *getCurScope() const {
720 const SharingMapTy *Top = getTopOfStackOrNull();
721 return Top ? Top->CurScope : nullptr;
722 }
723 SourceLocation getConstructLoc() const {
724 const SharingMapTy *Top = getTopOfStackOrNull();
725 return Top ? Top->ConstructLoc : SourceLocation();
726 }
727
728 /// Do the check specified in \a Check to all component lists and return true
729 /// if any issue is found.
730 bool checkMappableExprComponentListsForDecl(
731 const ValueDecl *VD, bool CurrentRegionOnly,
732 const llvm::function_ref<
733 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
734 OpenMPClauseKind)>
735 Check) const {
736 if (isStackEmpty())
737 return false;
738 auto SI = begin();
739 auto SE = end();
740
741 if (SI == SE)
742 return false;
743
744 if (CurrentRegionOnly)
745 SE = std::next(SI);
746 else
747 std::advance(SI, 1);
748
749 for (; SI != SE; ++SI) {
750 auto MI = SI->MappedExprComponents.find(VD);
751 if (MI != SI->MappedExprComponents.end())
752 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
753 MI->second.Components)
754 if (Check(L, MI->second.Kind))
755 return true;
756 }
757 return false;
758 }
759
760 /// Do the check specified in \a Check to all component lists at a given level
761 /// and return true if any issue is found.
762 bool checkMappableExprComponentListsForDeclAtLevel(
763 const ValueDecl *VD, unsigned Level,
764 const llvm::function_ref<
765 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
766 OpenMPClauseKind)>
767 Check) const {
768 if (getStackSize() <= Level)
769 return false;
770
771 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
772 auto MI = StackElem.MappedExprComponents.find(VD);
773 if (MI != StackElem.MappedExprComponents.end())
774 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
775 MI->second.Components)
776 if (Check(L, MI->second.Kind))
777 return true;
778 return false;
779 }
780
781 /// Create a new mappable expression component list associated with a given
782 /// declaration and initialize it with the provided list of components.
783 void addMappableExpressionComponents(
784 const ValueDecl *VD,
785 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
786 OpenMPClauseKind WhereFoundClauseKind) {
787 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
788 // Create new entry and append the new components there.
789 MEC.Components.resize(MEC.Components.size() + 1);
790 MEC.Components.back().append(Components.begin(), Components.end());
791 MEC.Kind = WhereFoundClauseKind;
792 }
793
794 unsigned getNestingLevel() const {
795 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 795, __PRETTY_FUNCTION__))
;
796 return getStackSize() - 1;
797 }
798 void addDoacrossDependClause(OMPDependClause *C,
799 const OperatorOffsetTy &OpsOffs) {
800 SharingMapTy *Parent = getSecondOnStackOrNull();
801 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive))((Parent && isOpenMPWorksharingDirective(Parent->Directive
)) ? static_cast<void> (0) : __assert_fail ("Parent && isOpenMPWorksharingDirective(Parent->Directive)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 801, __PRETTY_FUNCTION__))
;
802 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
803 }
804 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
805 getDoacrossDependClauses() const {
806 const SharingMapTy &StackElem = getTopOfStack();
807 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
808 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
809 return llvm::make_range(Ref.begin(), Ref.end());
810 }
811 return llvm::make_range(StackElem.DoacrossDepends.end(),
812 StackElem.DoacrossDepends.end());
813 }
814
815 // Store types of classes which have been explicitly mapped
816 void addMappedClassesQualTypes(QualType QT) {
817 SharingMapTy &StackElem = getTopOfStack();
818 StackElem.MappedClassesQualTypes.insert(QT);
819 }
820
821 // Return set of mapped classes types
822 bool isClassPreviouslyMapped(QualType QT) const {
823 const SharingMapTy &StackElem = getTopOfStack();
824 return StackElem.MappedClassesQualTypes.count(QT) != 0;
825 }
826
827 /// Adds global declare target to the parent target region.
828 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
829 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 831, __PRETTY_FUNCTION__))
830 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 831, __PRETTY_FUNCTION__))
831 "Expected declare target link global.")((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 831, __PRETTY_FUNCTION__))
;
832 for (auto &Elem : *this) {
833 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
834 Elem.DeclareTargetLinkVarDecls.push_back(E);
835 return;
836 }
837 }
838 }
839
840 /// Returns the list of globals with declare target link if current directive
841 /// is target.
842 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
843 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&((isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(getCurrentDirective()) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 844, __PRETTY_FUNCTION__))
844 "Expected target executable directive.")((isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(getCurrentDirective()) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 844, __PRETTY_FUNCTION__))
;
845 return getTopOfStack().DeclareTargetLinkVarDecls;
846 }
847};
848
849bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
850 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
851}
852
853bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
854 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
855 DKind == OMPD_unknown;
856}
857
858} // namespace
859
860static const Expr *getExprAsWritten(const Expr *E) {
861 if (const auto *FE = dyn_cast<FullExpr>(E))
862 E = FE->getSubExpr();
863
864 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
865 E = MTE->GetTemporaryExpr();
866
867 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
868 E = Binder->getSubExpr();
869
870 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
871 E = ICE->getSubExprAsWritten();
872 return E->IgnoreParens();
873}
874
875static Expr *getExprAsWritten(Expr *E) {
876 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
877}
878
879static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
880 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
881 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
882 D = ME->getMemberDecl();
883 const auto *VD = dyn_cast<VarDecl>(D);
884 const auto *FD = dyn_cast<FieldDecl>(D);
885 if (VD != nullptr) {
886 VD = VD->getCanonicalDecl();
887 D = VD;
888 } else {
889 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 889, __PRETTY_FUNCTION__))
;
890 FD = FD->getCanonicalDecl();
891 D = FD;
892 }
893 return D;
894}
895
896static ValueDecl *getCanonicalDecl(ValueDecl *D) {
897 return const_cast<ValueDecl *>(
898 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
899}
900
901DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
902 ValueDecl *D) const {
903 D = getCanonicalDecl(D);
904 auto *VD = dyn_cast<VarDecl>(D);
905 const auto *FD = dyn_cast<FieldDecl>(D);
906 DSAVarData DVar;
907 if (Iter == end()) {
908 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
909 // in a region but not in construct]
910 // File-scope or namespace-scope variables referenced in called routines
911 // in the region are shared unless they appear in a threadprivate
912 // directive.
913 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
914 DVar.CKind = OMPC_shared;
915
916 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
917 // in a region but not in construct]
918 // Variables with static storage duration that are declared in called
919 // routines in the region are shared.
920 if (VD && VD->hasGlobalStorage())
921 DVar.CKind = OMPC_shared;
922
923 // Non-static data members are shared by default.
924 if (FD)
925 DVar.CKind = OMPC_shared;
926
927 return DVar;
928 }
929
930 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
931 // in a Construct, C/C++, predetermined, p.1]
932 // Variables with automatic storage duration that are declared in a scope
933 // inside the construct are private.
934 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
935 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
936 DVar.CKind = OMPC_private;
937 return DVar;
938 }
939
940 DVar.DKind = Iter->Directive;
941 // Explicitly specified attributes and local variables with predetermined
942 // attributes.
943 if (Iter->SharingMap.count(D)) {
944 const DSAInfo &Data = Iter->SharingMap.lookup(D);
945 DVar.RefExpr = Data.RefExpr.getPointer();
946 DVar.PrivateCopy = Data.PrivateCopy;
947 DVar.CKind = Data.Attributes;
948 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
949 return DVar;
950 }
951
952 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
953 // in a Construct, C/C++, implicitly determined, p.1]
954 // In a parallel or task construct, the data-sharing attributes of these
955 // variables are determined by the default clause, if present.
956 switch (Iter->DefaultAttr) {
957 case DSA_shared:
958 DVar.CKind = OMPC_shared;
959 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
960 return DVar;
961 case DSA_none:
962 return DVar;
963 case DSA_unspecified:
964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
965 // in a Construct, implicitly determined, p.2]
966 // In a parallel construct, if no default clause is present, these
967 // variables are shared.
968 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
969 if ((isOpenMPParallelDirective(DVar.DKind) &&
970 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
971 isOpenMPTeamsDirective(DVar.DKind)) {
972 DVar.CKind = OMPC_shared;
973 return DVar;
974 }
975
976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
977 // in a Construct, implicitly determined, p.4]
978 // In a task construct, if no default clause is present, a variable that in
979 // the enclosing context is determined to be shared by all implicit tasks
980 // bound to the current team is shared.
981 if (isOpenMPTaskingDirective(DVar.DKind)) {
982 DSAVarData DVarTemp;
983 const_iterator I = Iter, E = end();
984 do {
985 ++I;
986 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
987 // Referenced in a Construct, implicitly determined, p.6]
988 // In a task construct, if no default clause is present, a variable
989 // whose data-sharing attribute is not determined by the rules above is
990 // firstprivate.
991 DVarTemp = getDSA(I, D);
992 if (DVarTemp.CKind != OMPC_shared) {
993 DVar.RefExpr = nullptr;
994 DVar.CKind = OMPC_firstprivate;
995 return DVar;
996 }
997 } while (I != E && !isImplicitTaskingRegion(I->Directive));
998 DVar.CKind =
999 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1000 return DVar;
1001 }
1002 }
1003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1004 // in a Construct, implicitly determined, p.3]
1005 // For constructs other than task, if no default clause is present, these
1006 // variables inherit their data-sharing attributes from the enclosing
1007 // context.
1008 return getDSA(++Iter, D);
1009}
1010
1011const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1012 const Expr *NewDE) {
1013 assert(!isStackEmpty() && "Data sharing attributes stack is empty")((!isStackEmpty() && "Data sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1013, __PRETTY_FUNCTION__))
;
1014 D = getCanonicalDecl(D);
1015 SharingMapTy &StackElem = getTopOfStack();
1016 auto It = StackElem.AlignedMap.find(D);
1017 if (It == StackElem.AlignedMap.end()) {
1018 assert(NewDE && "Unexpected nullptr expr to be added into aligned map")((NewDE && "Unexpected nullptr expr to be added into aligned map"
) ? static_cast<void> (0) : __assert_fail ("NewDE && \"Unexpected nullptr expr to be added into aligned map\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1018, __PRETTY_FUNCTION__))
;
1019 StackElem.AlignedMap[D] = NewDE;
1020 return nullptr;
1021 }
1022 assert(It->second && "Unexpected nullptr expr in the aligned map")((It->second && "Unexpected nullptr expr in the aligned map"
) ? static_cast<void> (0) : __assert_fail ("It->second && \"Unexpected nullptr expr in the aligned map\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1022, __PRETTY_FUNCTION__))
;
1023 return It->second;
1024}
1025
1026void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1027 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1027, __PRETTY_FUNCTION__))
;
1028 D = getCanonicalDecl(D);
1029 SharingMapTy &StackElem = getTopOfStack();
1030 StackElem.LCVMap.try_emplace(
1031 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1032}
1033
1034const DSAStackTy::LCDeclInfo
1035DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1036, __PRETTY_FUNCTION__))
;
16
'?' condition is true
1037 D = getCanonicalDecl(D);
1038 const SharingMapTy &StackElem = getTopOfStack();
1039 auto It = StackElem.LCVMap.find(D);
1040 if (It != StackElem.LCVMap.end())
17
Assuming the condition is true
18
Taking true branch
1041 return It->second;
19
Value assigned to field 'first', which participates in a condition later
1042 return {0, nullptr};
1043}
1044
1045const DSAStackTy::LCDeclInfo
1046DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1047 const SharingMapTy *Parent = getSecondOnStackOrNull();
1048 assert(Parent && "Data-sharing attributes stack is empty")((Parent && "Data-sharing attributes stack is empty")
? static_cast<void> (0) : __assert_fail ("Parent && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1048, __PRETTY_FUNCTION__))
;
1049 D = getCanonicalDecl(D);
1050 auto It = Parent->LCVMap.find(D);
1051 if (It != Parent->LCVMap.end())
1052 return It->second;
1053 return {0, nullptr};
1054}
1055
1056const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1057 const SharingMapTy *Parent = getSecondOnStackOrNull();
1058 assert(Parent && "Data-sharing attributes stack is empty")((Parent && "Data-sharing attributes stack is empty")
? static_cast<void> (0) : __assert_fail ("Parent && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1058, __PRETTY_FUNCTION__))
;
1059 if (Parent->LCVMap.size() < I)
1060 return nullptr;
1061 for (const auto &Pair : Parent->LCVMap)
1062 if (Pair.second.first == I)
1063 return Pair.first;
1064 return nullptr;
1065}
1066
1067void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1068 DeclRefExpr *PrivateCopy) {
1069 D = getCanonicalDecl(D);
1070 if (A == OMPC_threadprivate) {
1071 DSAInfo &Data = Threadprivates[D];
1072 Data.Attributes = A;
1073 Data.RefExpr.setPointer(E);
1074 Data.PrivateCopy = nullptr;
1075 } else {
1076 DSAInfo &Data = getTopOfStack().SharingMap[D];
1077 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
1078 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
1079 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
1080 (isLoopControlVariable(D).first && A == OMPC_private))((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
;
1081 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1082 Data.RefExpr.setInt(/*IntVal=*/true);
1083 return;
1084 }
1085 const bool IsLastprivate =
1086 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1087 Data.Attributes = A;
1088 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1089 Data.PrivateCopy = PrivateCopy;
1090 if (PrivateCopy) {
1091 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1092 Data.Attributes = A;
1093 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1094 Data.PrivateCopy = nullptr;
1095 }
1096 }
1097}
1098
1099/// Build a variable declaration for OpenMP loop iteration variable.
1100static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1101 StringRef Name, const AttrVec *Attrs = nullptr,
1102 DeclRefExpr *OrigRef = nullptr) {
1103 DeclContext *DC = SemaRef.CurContext;
1104 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1105 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1106 auto *Decl =
1107 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1108 if (Attrs) {
1109 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1110 I != E; ++I)
1111 Decl->addAttr(*I);
1112 }
1113 Decl->setImplicit();
1114 if (OrigRef) {
1115 Decl->addAttr(
1116 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1117 }
1118 return Decl;
1119}
1120
1121static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1122 SourceLocation Loc,
1123 bool RefersToCapture = false) {
1124 D->setReferenced();
1125 D->markUsed(S.Context);
1126 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1127 SourceLocation(), D, RefersToCapture, Loc, Ty,
1128 VK_LValue);
1129}
1130
1131void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1132 BinaryOperatorKind BOK) {
1133 D = getCanonicalDecl(D);
1134 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1134, __PRETTY_FUNCTION__))
;
1135 assert(((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1137, __PRETTY_FUNCTION__))
1136 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1137, __PRETTY_FUNCTION__))
1137 "Additional reduction info may be specified only for reduction items.")((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1137, __PRETTY_FUNCTION__))
;
1138 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1139 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
1140 getTopOfStack().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
1141 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
1142 "items.")((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
;
1143 ReductionData.set(BOK, SR);
1144 Expr *&TaskgroupReductionRef =
1145 getTopOfStack().TaskgroupReductionRef;
1146 if (!TaskgroupReductionRef) {
1147 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1148 SemaRef.Context.VoidPtrTy, ".task_red.");
1149 TaskgroupReductionRef =
1150 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1151 }
1152}
1153
1154void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1155 const Expr *ReductionRef) {
1156 D = getCanonicalDecl(D);
1157 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1157, __PRETTY_FUNCTION__))
;
1158 assert(((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1160, __PRETTY_FUNCTION__))
1159 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1160, __PRETTY_FUNCTION__))
1160 "Additional reduction info may be specified only for reduction items.")((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1160, __PRETTY_FUNCTION__))
;
1161 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1162 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
1163 getTopOfStack().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
1164 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
1165 "items.")((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
;
1166 ReductionData.set(ReductionRef, SR);
1167 Expr *&TaskgroupReductionRef =
1168 getTopOfStack().TaskgroupReductionRef;
1169 if (!TaskgroupReductionRef) {
1170 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1171 SemaRef.Context.VoidPtrTy, ".task_red.");
1172 TaskgroupReductionRef =
1173 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1174 }
1175}
1176
1177const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1178 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1179 Expr *&TaskgroupDescriptor) const {
1180 D = getCanonicalDecl(D);
1181 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1181, __PRETTY_FUNCTION__))
;
1182 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1183 const DSAInfo &Data = I->SharingMap.lookup(D);
1184 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1185 continue;
1186 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1187 if (!ReductionData.ReductionOp ||
1188 ReductionData.ReductionOp.is<const Expr *>())
1189 return DSAVarData();
1190 SR = ReductionData.ReductionRange;
1191 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1192 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1194, __PRETTY_FUNCTION__))
1193 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1194, __PRETTY_FUNCTION__))
1194 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1194, __PRETTY_FUNCTION__))
;
1195 TaskgroupDescriptor = I->TaskgroupReductionRef;
1196 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1197 Data.PrivateCopy, I->DefaultAttrLoc);
1198 }
1199 return DSAVarData();
1200}
1201
1202const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1203 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1204 Expr *&TaskgroupDescriptor) const {
1205 D = getCanonicalDecl(D);
1206 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1206, __PRETTY_FUNCTION__))
;
1207 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1208 const DSAInfo &Data = I->SharingMap.lookup(D);
1209 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1210 continue;
1211 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1212 if (!ReductionData.ReductionOp ||
1213 !ReductionData.ReductionOp.is<const Expr *>())
1214 return DSAVarData();
1215 SR = ReductionData.ReductionRange;
1216 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1217 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1219, __PRETTY_FUNCTION__))
1218 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1219, __PRETTY_FUNCTION__))
1219 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1219, __PRETTY_FUNCTION__))
;
1220 TaskgroupDescriptor = I->TaskgroupReductionRef;
1221 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1222 Data.PrivateCopy, I->DefaultAttrLoc);
1223 }
1224 return DSAVarData();
1225}
1226
1227bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1228 D = D->getCanonicalDecl();
1229 for (const_iterator E = end(); I != E; ++I) {
1230 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1231 isOpenMPTargetExecutionDirective(I->Directive)) {
1232 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1233 Scope *CurScope = getCurScope();
1234 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1235 CurScope = CurScope->getParent();
1236 return CurScope != TopScope;
1237 }
1238 }
1239 return false;
1240}
1241
1242static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1243 bool AcceptIfMutable = true,
1244 bool *IsClassType = nullptr) {
1245 ASTContext &Context = SemaRef.getASTContext();
1246 Type = Type.getNonReferenceType().getCanonicalType();
1247 bool IsConstant = Type.isConstant(Context);
1248 Type = Context.getBaseElementType(Type);
1249 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1250 ? Type->getAsCXXRecordDecl()
1251 : nullptr;
1252 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1253 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1254 RD = CTD->getTemplatedDecl();
1255 if (IsClassType)
1256 *IsClassType = RD;
1257 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1258 RD->hasDefinition() && RD->hasMutableFields());
1259}
1260
1261static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1262 QualType Type, OpenMPClauseKind CKind,
1263 SourceLocation ELoc,
1264 bool AcceptIfMutable = true,
1265 bool ListItemNotVar = false) {
1266 ASTContext &Context = SemaRef.getASTContext();
1267 bool IsClassType;
1268 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1269 unsigned Diag = ListItemNotVar
1270 ? diag::err_omp_const_list_item
1271 : IsClassType ? diag::err_omp_const_not_mutable_variable
1272 : diag::err_omp_const_variable;
1273 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1274 if (!ListItemNotVar && D) {
1275 const VarDecl *VD = dyn_cast<VarDecl>(D);
1276 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1277 VarDecl::DeclarationOnly;
1278 SemaRef.Diag(D->getLocation(),
1279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1280 << D;
1281 }
1282 return true;
1283 }
1284 return false;
1285}
1286
1287const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1288 bool FromParent) {
1289 D = getCanonicalDecl(D);
1290 DSAVarData DVar;
1291
1292 auto *VD = dyn_cast<VarDecl>(D);
1293 auto TI = Threadprivates.find(D);
1294 if (TI != Threadprivates.end()) {
1295 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1296 DVar.CKind = OMPC_threadprivate;
1297 return DVar;
1298 }
1299 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1300 DVar.RefExpr = buildDeclRefExpr(
1301 SemaRef, VD, D->getType().getNonReferenceType(),
1302 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1303 DVar.CKind = OMPC_threadprivate;
1304 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1305 return DVar;
1306 }
1307 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1308 // in a Construct, C/C++, predetermined, p.1]
1309 // Variables appearing in threadprivate directives are threadprivate.
1310 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1311 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1312 SemaRef.getLangOpts().OpenMPUseTLS &&
1313 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1314 (VD && VD->getStorageClass() == SC_Register &&
1315 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1316 DVar.RefExpr = buildDeclRefExpr(
1317 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1318 DVar.CKind = OMPC_threadprivate;
1319 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1320 return DVar;
1321 }
1322 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1323 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1324 !isLoopControlVariable(D).first) {
1325 const_iterator IterTarget =
1326 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1327 return isOpenMPTargetExecutionDirective(Data.Directive);
1328 });
1329 if (IterTarget != end()) {
1330 const_iterator ParentIterTarget = IterTarget + 1;
1331 for (const_iterator Iter = begin();
1332 Iter != ParentIterTarget; ++Iter) {
1333 if (isOpenMPLocal(VD, Iter)) {
1334 DVar.RefExpr =
1335 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1336 D->getLocation());
1337 DVar.CKind = OMPC_threadprivate;
1338 return DVar;
1339 }
1340 }
1341 if (!isClauseParsingMode() || IterTarget != begin()) {
1342 auto DSAIter = IterTarget->SharingMap.find(D);
1343 if (DSAIter != IterTarget->SharingMap.end() &&
1344 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1345 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1346 DVar.CKind = OMPC_threadprivate;
1347 return DVar;
1348 }
1349 const_iterator End = end();
1350 if (!SemaRef.isOpenMPCapturedByRef(
1351 D, std::distance(ParentIterTarget, End),
1352 /*OpenMPCaptureLevel=*/0)) {
1353 DVar.RefExpr =
1354 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1355 IterTarget->ConstructLoc);
1356 DVar.CKind = OMPC_threadprivate;
1357 return DVar;
1358 }
1359 }
1360 }
1361 }
1362
1363 if (isStackEmpty())
1364 // Not in OpenMP execution region and top scope was already checked.
1365 return DVar;
1366
1367 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1368 // in a Construct, C/C++, predetermined, p.4]
1369 // Static data members are shared.
1370 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1371 // in a Construct, C/C++, predetermined, p.7]
1372 // Variables with static storage duration that are declared in a scope
1373 // inside the construct are shared.
1374 if (VD && VD->isStaticDataMember()) {
1375 // Check for explicitly specified attributes.
1376 const_iterator I = begin();
1377 const_iterator EndI = end();
1378 if (FromParent && I != EndI)
1379 ++I;
1380 auto It = I->SharingMap.find(D);
1381 if (It != I->SharingMap.end()) {
1382 const DSAInfo &Data = It->getSecond();
1383 DVar.RefExpr = Data.RefExpr.getPointer();
1384 DVar.PrivateCopy = Data.PrivateCopy;
1385 DVar.CKind = Data.Attributes;
1386 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1387 DVar.DKind = I->Directive;
1388 return DVar;
1389 }
1390
1391 DVar.CKind = OMPC_shared;
1392 return DVar;
1393 }
1394
1395 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1396 // The predetermined shared attribute for const-qualified types having no
1397 // mutable members was removed after OpenMP 3.1.
1398 if (SemaRef.LangOpts.OpenMP <= 31) {
1399 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1400 // in a Construct, C/C++, predetermined, p.6]
1401 // Variables with const qualified type having no mutable member are
1402 // shared.
1403 if (isConstNotMutableType(SemaRef, D->getType())) {
1404 // Variables with const-qualified type having no mutable member may be
1405 // listed in a firstprivate clause, even if they are static data members.
1406 DSAVarData DVarTemp = hasInnermostDSA(
1407 D,
1408 [](OpenMPClauseKind C) {
1409 return C == OMPC_firstprivate || C == OMPC_shared;
1410 },
1411 MatchesAlways, FromParent);
1412 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1413 return DVarTemp;
1414
1415 DVar.CKind = OMPC_shared;
1416 return DVar;
1417 }
1418 }
1419
1420 // Explicitly specified attributes and local variables with predetermined
1421 // 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;
1434 }
1435
1436 return DVar;
1437}
1438
1439const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1440 bool FromParent) const {
1441 if (isStackEmpty()) {
1442 const_iterator I;
1443 return getDSA(I, D);
1444 }
1445 D = getCanonicalDecl(D);
1446 const_iterator StartI = begin();
1447 const_iterator EndI = end();
1448 if (FromParent && StartI != EndI)
1449 ++StartI;
1450 return getDSA(StartI, D);
1451}
1452
1453const DSAStackTy::DSAVarData
1454DSAStackTy::hasDSA(ValueDecl *D,
1455 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1456 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1457 bool FromParent) const {
1458 if (isStackEmpty())
1459 return {};
1460 D = getCanonicalDecl(D);
1461 const_iterator I = begin();
1462 const_iterator EndI = end();
1463 if (FromParent && I != EndI)
1464 ++I;
1465 for (; I != EndI; ++I) {
1466 if (!DPred(I->Directive) &&
1467 !isImplicitOrExplicitTaskingRegion(I->Directive))
1468 continue;
1469 const_iterator NewI = I;
1470 DSAVarData DVar = getDSA(NewI, D);
1471 if (I == NewI && CPred(DVar.CKind))
1472 return DVar;
1473 }
1474 return {};
1475}
1476
1477const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1478 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1479 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1480 bool FromParent) const {
1481 if (isStackEmpty())
1482 return {};
1483 D = getCanonicalDecl(D);
1484 const_iterator StartI = begin();
1485 const_iterator EndI = end();
1486 if (FromParent && StartI != EndI)
1487 ++StartI;
1488 if (StartI == EndI || !DPred(StartI->Directive))
1489 return {};
1490 const_iterator NewI = StartI;
1491 DSAVarData DVar = getDSA(NewI, D);
1492 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1493}
1494
1495bool DSAStackTy::hasExplicitDSA(
1496 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1497 unsigned Level, bool NotLastprivate) const {
1498 if (getStackSize() <= Level)
1499 return false;
1500 D = getCanonicalDecl(D);
1501 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1502 auto I = StackElem.SharingMap.find(D);
1503 if (I != StackElem.SharingMap.end() &&
1504 I->getSecond().RefExpr.getPointer() &&
1505 CPred(I->getSecond().Attributes) &&
1506 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1507 return true;
1508 // Check predetermined rules for the loop control variables.
1509 auto LI = StackElem.LCVMap.find(D);
1510 if (LI != StackElem.LCVMap.end())
1511 return CPred(OMPC_private);
1512 return false;
1513}
1514
1515bool DSAStackTy::hasExplicitDirective(
1516 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1517 unsigned Level) const {
1518 if (getStackSize() <= Level)
1519 return false;
1520 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1521 return DPred(StackElem.Directive);
1522}
1523
1524bool DSAStackTy::hasDirective(
1525 const llvm::function_ref<bool(OpenMPDirectiveKind,
1526 const DeclarationNameInfo &, SourceLocation)>
1527 DPred,
1528 bool FromParent) const {
1529 // We look only in the enclosing region.
1530 size_t Skip = FromParent ? 2 : 1;
1531 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1532 I != E; ++I) {
1533 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1534 return true;
1535 }
1536 return false;
1537}
1538
1539void Sema::InitDataSharingAttributesStack() {
1540 VarDataSharingAttributesStack = new DSAStackTy(*this);
1541}
1542
1543#define DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1544
1545void Sema::pushOpenMPFunctionRegion() {
1546 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pushFunction();
1547}
1548
1549void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1550 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->popFunction(OldFSI);
1551}
1552
1553static bool isOpenMPDeviceDelayedContext(Sema &S) {
1554 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&((S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1555, __PRETTY_FUNCTION__))
1555 "Expected OpenMP device compilation.")((S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1555, __PRETTY_FUNCTION__))
;
1556 return !S.isInOpenMPTargetExecutionDirective() &&
1557 !S.isInOpenMPDeclareTargetContext();
1558}
1559
1560namespace {
1561/// Status of the function emission on the host/device.
1562enum class FunctionEmissionStatus {
1563 Emitted,
1564 Discarded,
1565 Unknown,
1566};
1567} // anonymous namespace
1568
1569Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1570 unsigned DiagID) {
1571 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1572, __PRETTY_FUNCTION__))
1572 "Expected OpenMP device compilation.")((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1572, __PRETTY_FUNCTION__))
;
1573 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1574 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1575 switch (FES) {
1576 case FunctionEmissionStatus::Emitted:
1577 Kind = DeviceDiagBuilder::K_Immediate;
1578 break;
1579 case FunctionEmissionStatus::Unknown:
1580 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1581 : DeviceDiagBuilder::K_Immediate;
1582 break;
1583 case FunctionEmissionStatus::TemplateDiscarded:
1584 case FunctionEmissionStatus::OMPDiscarded:
1585 Kind = DeviceDiagBuilder::K_Nop;
1586 break;
1587 case FunctionEmissionStatus::CUDADiscarded:
1588 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation")::llvm::llvm_unreachable_internal("CUDADiscarded unexpected in OpenMP device compilation"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1588)
;
1589 break;
1590 }
1591
1592 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1593}
1594
1595Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1596 unsigned DiagID) {
1597 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1598, __PRETTY_FUNCTION__))
1598 "Expected OpenMP host compilation.")((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1598, __PRETTY_FUNCTION__))
;
1599 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1600 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1601 switch (FES) {
1602 case FunctionEmissionStatus::Emitted:
1603 Kind = DeviceDiagBuilder::K_Immediate;
1604 break;
1605 case FunctionEmissionStatus::Unknown:
1606 Kind = DeviceDiagBuilder::K_Deferred;
1607 break;
1608 case FunctionEmissionStatus::TemplateDiscarded:
1609 case FunctionEmissionStatus::OMPDiscarded:
1610 case FunctionEmissionStatus::CUDADiscarded:
1611 Kind = DeviceDiagBuilder::K_Nop;
1612 break;
1613 }
1614
1615 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1616}
1617
1618void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1619 bool CheckForDelayedContext) {
1620 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1621, __PRETTY_FUNCTION__))
1621 "Expected OpenMP device compilation.")((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1621, __PRETTY_FUNCTION__))
;
1622 assert(Callee && "Callee may not be null.")((Callee && "Callee may not be null.") ? static_cast<
void> (0) : __assert_fail ("Callee && \"Callee may not be null.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1622, __PRETTY_FUNCTION__))
;
1623 Callee = Callee->getMostRecentDecl();
1624 FunctionDecl *Caller = getCurFunctionDecl();
1625
1626 // host only function are not available on the device.
1627 if (Caller) {
1628 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1629 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1630 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&((CallerS != FunctionEmissionStatus::CUDADiscarded &&
CalleeS != FunctionEmissionStatus::CUDADiscarded && "CUDADiscarded unexpected in OpenMP device function check"
) ? static_cast<void> (0) : __assert_fail ("CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded && \"CUDADiscarded unexpected in OpenMP device function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1632, __PRETTY_FUNCTION__))
1631 CalleeS != FunctionEmissionStatus::CUDADiscarded &&((CallerS != FunctionEmissionStatus::CUDADiscarded &&
CalleeS != FunctionEmissionStatus::CUDADiscarded && "CUDADiscarded unexpected in OpenMP device function check"
) ? static_cast<void> (0) : __assert_fail ("CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded && \"CUDADiscarded unexpected in OpenMP device function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1632, __PRETTY_FUNCTION__))
1632 "CUDADiscarded unexpected in OpenMP device function check")((CallerS != FunctionEmissionStatus::CUDADiscarded &&
CalleeS != FunctionEmissionStatus::CUDADiscarded && "CUDADiscarded unexpected in OpenMP device function check"
) ? static_cast<void> (0) : __assert_fail ("CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded && \"CUDADiscarded unexpected in OpenMP device function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1632, __PRETTY_FUNCTION__))
;
1633 if ((CallerS == FunctionEmissionStatus::Emitted ||
1634 (!isOpenMPDeviceDelayedContext(*this) &&
1635 CallerS == FunctionEmissionStatus::Unknown)) &&
1636 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1637 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1638 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1639 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1640 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1641 diag::note_omp_marked_device_type_here)
1642 << HostDevTy;
1643 return;
1644 }
1645 }
1646 // If the caller is known-emitted, mark the callee as known-emitted.
1647 // Otherwise, mark the call in our call graph so we can traverse it later.
1648 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1649 (!Caller && !CheckForDelayedContext) ||
1650 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1651 markKnownEmitted(*this, Caller, Callee, Loc,
1652 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
1653 return CheckForDelayedContext &&
1654 S.getEmissionStatus(FD) ==
1655 FunctionEmissionStatus::Emitted;
1656 });
1657 else if (Caller)
1658 DeviceCallGraph[Caller].insert({Callee, Loc});
1659}
1660
1661void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1662 bool CheckCaller) {
1663 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1664, __PRETTY_FUNCTION__))
1664 "Expected OpenMP host compilation.")((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1664, __PRETTY_FUNCTION__))
;
1665 assert(Callee && "Callee may not be null.")((Callee && "Callee may not be null.") ? static_cast<
void> (0) : __assert_fail ("Callee && \"Callee may not be null.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1665, __PRETTY_FUNCTION__))
;
1666 Callee = Callee->getMostRecentDecl();
1667 FunctionDecl *Caller = getCurFunctionDecl();
1668
1669 // device only function are not available on the host.
1670 if (Caller) {
1671 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1672 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1673 assert((((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
1674 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&(((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
1675 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&(((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
1676 "CUDADiscarded unexpected in OpenMP host function check")(((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
;
1677 if (CallerS == FunctionEmissionStatus::Emitted &&
1678 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1679 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1680 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1681 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1682 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1683 diag::note_omp_marked_device_type_here)
1684 << NoHostDevTy;
1685 return;
1686 }
1687 }
1688 // If the caller is known-emitted, mark the callee as known-emitted.
1689 // Otherwise, mark the call in our call graph so we can traverse it later.
1690 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1691 if ((!CheckCaller && !Caller) ||
1692 (Caller &&
1693 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1694 markKnownEmitted(
1695 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1696 return CheckCaller &&
1697 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1698 });
1699 else if (Caller)
1700 DeviceCallGraph[Caller].insert({Callee, Loc});
1701 }
1702}
1703
1704void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1705 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "OpenMP device compilation mode is expected.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"OpenMP device compilation mode is expected.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1706, __PRETTY_FUNCTION__))
1706 "OpenMP device compilation mode is expected.")((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "OpenMP device compilation mode is expected.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"OpenMP device compilation mode is expected.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1706, __PRETTY_FUNCTION__))
;
1707 QualType Ty = E->getType();
1708 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1709 ((Ty->isFloat128Type() ||
1710 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1711 !Context.getTargetInfo().hasFloat128Type()) ||
1712 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1713 !Context.getTargetInfo().hasInt128Type()))
1714 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1715 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1716 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
1717}
1718
1719bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1720 unsigned OpenMPCaptureLevel) const {
1721 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1721, __PRETTY_FUNCTION__))
;
1722
1723 ASTContext &Ctx = getASTContext();
1724 bool IsByRef = true;
1725
1726 // Find the directive that is associated with the provided scope.
1727 D = cast<ValueDecl>(D->getCanonicalDecl());
1728 QualType Ty = D->getType();
1729
1730 bool IsVariableUsedInMapClause = false;
1731 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1732 // This table summarizes how a given variable should be passed to the device
1733 // given its type and the clauses where it appears. This table is based on
1734 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1735 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1736 //
1737 // =========================================================================
1738 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1739 // | |(tofrom:scalar)| | pvt | | | |
1740 // =========================================================================
1741 // | scl | | | | - | | bycopy|
1742 // | scl | | - | x | - | - | bycopy|
1743 // | scl | | x | - | - | - | null |
1744 // | scl | x | | | - | | byref |
1745 // | scl | x | - | x | - | - | bycopy|
1746 // | scl | x | x | - | - | - | null |
1747 // | scl | | - | - | - | x | byref |
1748 // | scl | x | - | - | - | x | byref |
1749 //
1750 // | agg | n.a. | | | - | | byref |
1751 // | agg | n.a. | - | x | - | - | byref |
1752 // | agg | n.a. | x | - | - | - | null |
1753 // | agg | n.a. | - | - | - | x | byref |
1754 // | agg | n.a. | - | - | - | x[] | byref |
1755 //
1756 // | ptr | n.a. | | | - | | bycopy|
1757 // | ptr | n.a. | - | x | - | - | bycopy|
1758 // | ptr | n.a. | x | - | - | - | null |
1759 // | ptr | n.a. | - | - | - | x | byref |
1760 // | ptr | n.a. | - | - | - | x[] | bycopy|
1761 // | ptr | n.a. | - | - | x | | bycopy|
1762 // | ptr | n.a. | - | - | x | x | bycopy|
1763 // | ptr | n.a. | - | - | x | x[] | bycopy|
1764 // =========================================================================
1765 // Legend:
1766 // scl - scalar
1767 // ptr - pointer
1768 // agg - aggregate
1769 // x - applies
1770 // - - invalid in this combination
1771 // [] - mapped with an array section
1772 // byref - should be mapped by reference
1773 // byval - should be mapped by value
1774 // null - initialize a local variable to null on the device
1775 //
1776 // Observations:
1777 // - All scalar declarations that show up in a map clause have to be passed
1778 // by reference, because they may have been mapped in the enclosing data
1779 // environment.
1780 // - If the scalar value does not fit the size of uintptr, it has to be
1781 // passed by reference, regardless the result in the table above.
1782 // - For pointers mapped by value that have either an implicit map or an
1783 // array section, the runtime library may pass the NULL value to the
1784 // device instead of the value passed to it by the compiler.
1785
1786 if (Ty->isReferenceType())
1787 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1788
1789 // Locate map clauses and see if the variable being captured is referred to
1790 // in any of those clauses. Here we only care about variables, not fields,
1791 // because fields are part of aggregates.
1792 bool IsVariableAssociatedWithSection = false;
1793
1794 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
1795 D, Level,
1796 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1797 OMPClauseMappableExprCommon::MappableExprComponentListRef
1798 MapExprComponents,
1799 OpenMPClauseKind WhereFoundClauseKind) {
1800 // Only the map clause information influences how a variable is
1801 // captured. E.g. is_device_ptr does not require changing the default
1802 // behavior.
1803 if (WhereFoundClauseKind != OMPC_map)
1804 return false;
1805
1806 auto EI = MapExprComponents.rbegin();
1807 auto EE = MapExprComponents.rend();
1808
1809 assert(EI != EE && "Invalid map expression!")((EI != EE && "Invalid map expression!") ? static_cast
<void> (0) : __assert_fail ("EI != EE && \"Invalid map expression!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1809, __PRETTY_FUNCTION__))
;
1810
1811 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1812 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1813
1814 ++EI;
1815 if (EI == EE)
1816 return false;
1817
1818 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1819 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1820 isa<MemberExpr>(EI->getAssociatedExpression())) {
1821 IsVariableAssociatedWithSection = true;
1822 // There is nothing more we need to know about this variable.
1823 return true;
1824 }
1825
1826 // Keep looking for more map info.
1827 return false;
1828 });
1829
1830 if (IsVariableUsedInMapClause) {
1831 // If variable is identified in a map clause it is always captured by
1832 // reference except if it is a pointer that is dereferenced somehow.
1833 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1834 } else {
1835 // By default, all the data that has a scalar type is mapped by copy
1836 // (except for reduction variables).
1837 IsByRef =
1838 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable() &&
1839 !Ty->isAnyPointerType()) ||
1840 !Ty->isScalarType() ||
1841 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1842 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1843 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1844 }
1845 }
1846
1847 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1848 IsByRef =
1849 ((IsVariableUsedInMapClause &&
1850 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1851 OMPD_target) ||
1852 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1853 D,
1854 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1855 Level, /*NotLastprivate=*/true)) &&
1856 // If the variable is artificial and must be captured by value - try to
1857 // capture by value.
1858 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1859 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1860 }
1861
1862 // When passing data by copy, we need to make sure it fits the uintptr size
1863 // and alignment, because the runtime library only deals with uintptr types.
1864 // If it does not fit the uintptr size, we need to pass the data by reference
1865 // instead.
1866 if (!IsByRef &&
1867 (Ctx.getTypeSizeInChars(Ty) >
1868 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1869 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1870 IsByRef = true;
1871 }
1872
1873 return IsByRef;
1874}
1875
1876unsigned Sema::getOpenMPNestingLevel() const {
1877 assert(getLangOpts().OpenMP)((getLangOpts().OpenMP) ? static_cast<void> (0) : __assert_fail
("getLangOpts().OpenMP", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1877, __PRETTY_FUNCTION__))
;
1878 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel();
1879}
1880
1881bool Sema::isInOpenMPTargetExecutionDirective() const {
1882 return (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
1883 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()) ||
1884 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDirective(
1885 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1886 SourceLocation) -> bool {
1887 return isOpenMPTargetExecutionDirective(K);
1888 },
1889 false);
1890}
1891
1892VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1893 unsigned StopAt) {
1894 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1894, __PRETTY_FUNCTION__))
;
6
Assuming field 'OpenMP' is not equal to 0
7
'?' condition is true
1895 D = getCanonicalDecl(D);
1896
1897 auto *VD = dyn_cast<VarDecl>(D);
8
Assuming 'D' is not a 'VarDecl'
1898 // Do not capture constexpr variables.
1899 if (VD
8.1
'VD' is null
&& VD->isConstexpr())
1900 return nullptr;
1901
1902 // If we want to determine whether the variable should be captured from the
1903 // perspective of the current capturing scope, and we've already left all the
1904 // capturing scopes of the top directive on the stack, check from the
1905 // perspective of its parent directive (if any) instead.
1906 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1907 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, CheckScopeInfo
8.2
'CheckScopeInfo' is false
&& DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isBodyComplete());
1908
1909 // If we are attempting to capture a global variable in a directive with
1910 // 'target' we return true so that this global is also mapped to the device.
1911 //
1912 if (VD
8.3
'VD' is null
&& !VD->hasLocalStorage() &&
1913 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1914 if (isInOpenMPDeclareTargetContext()) {
1915 // Try to mark variable as declare target if it is used in capturing
1916 // regions.
1917 if (LangOpts.OpenMP <= 45 &&
1918 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1919 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1920 return nullptr;
1921 } else if (isInOpenMPTargetExecutionDirective()) {
1922 // If the declaration is enclosed in a 'declare target' directive,
1923 // then it should not be captured.
1924 //
1925 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1926 return nullptr;
1927 return VD;
1928 }
1929 }
1930
1931 if (CheckScopeInfo
8.4
'CheckScopeInfo' is false
) {
9
Taking false branch
1932 bool OpenMPFound = false;
1933 for (unsigned I = StopAt + 1; I > 0; --I) {
1934 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1935 if(!isa<CapturingScopeInfo>(FSI))
1936 return nullptr;
1937 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1938 if (RSI->CapRegionKind == CR_OpenMP) {
1939 OpenMPFound = true;
1940 break;
1941 }
1942 }
1943 if (!OpenMPFound)
1944 return nullptr;
1945 }
1946
1947 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_unknown
&&
10
Assuming the condition is true
1948 (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()
||
11
Calling 'DSAStackTy::isClauseParsingMode'
14
Returning from 'DSAStackTy::isClauseParsingMode'
1949 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective() != OMPD_unknown)) {
1950 auto &&Info = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D)
;
15
Calling 'DSAStackTy::isLoopControlVariable'
20
Returning from 'DSAStackTy::isLoopControlVariable'
1951 if (Info.first ||
21
Assuming field 'first' is 0
1952 (VD
21.1
'VD' is null
&& VD->hasLocalStorage() &&
1953 isImplicitOrExplicitTaskingRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) ||
1954 (VD
21.2
'VD' is null
&& DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing()))
1955 return VD ? VD : Info.second;
1956 DSAStackTy::DSAVarData DVarPrivate =
1957 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
1958 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
22
Assuming field 'CKind' is equal to OMPC_unknown
1959 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1960 // Threadprivate variables must not be captured.
1961 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
23
Assuming the condition is false
24
Taking false branch
1962 return nullptr;
1963 // The variable is not private or it is the variable in the directive with
1964 // default(none) clause and not used in any clause.
1965 DVarPrivate = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDSA(D, isOpenMPPrivate,
25
Null pointer value stored to 'DVarPrivate.PrivateCopy'
1966 [](OpenMPDirectiveKind) { return true; },
1967 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode())
;
1968 if (DVarPrivate.CKind
25.1
Field 'CKind' is not equal to OMPC_unknown
!= OMPC_unknown ||
1969 (VD && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none))
1970 return VD
25.2
'VD' is null
? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
26
'?' condition is false
27
Called C++ object pointer is null
1971 }
1972 return nullptr;
1973}
1974
1975void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1976 unsigned Level) const {
1977 SmallVector<OpenMPDirectiveKind, 4> Regions;
1978 getOpenMPCaptureRegions(Regions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
1979 FunctionScopesIndex -= Regions.size();
1980}
1981
1982void Sema::startOpenMPLoop() {
1983 assert(LangOpts.OpenMP && "OpenMP must be enabled.")((LangOpts.OpenMP && "OpenMP must be enabled.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP must be enabled.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1983, __PRETTY_FUNCTION__))
;
1984 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
1985 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopInit();
1986}
1987
1988void Sema::startOpenMPCXXRangeFor() {
1989 assert(LangOpts.OpenMP && "OpenMP must be enabled.")((LangOpts.OpenMP && "OpenMP must be enabled.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP must be enabled.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1989, __PRETTY_FUNCTION__))
;
1990 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
1991 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter();
1992 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
1993 }
1994}
1995
1996bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1997 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 1997, __PRETTY_FUNCTION__))
;
1998 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
1999 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() > 0 &&
2000 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopStarted()) {
2001 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter(D);
2002 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
2003 return true;
2004 }
2005 if ((DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2006 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D).first) &&
2007 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2008 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2009 !isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
2010 return true;
2011 }
2012 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2013 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2014 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing() &&
2015 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2016 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2017 return true;
2018 }
2019 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2020 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
2021 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() &&
2022 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getClauseParsingMode() == OMPC_private) ||
2023 // Consider taskgroup reduction descriptor variable a private to avoid
2024 // possible capture in the region.
2025 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(
2026 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2027 Level) &&
2028 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isTaskgroupReductionRef(D, Level));
2029}
2030
2031void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2032 unsigned Level) {
2033 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 2033, __PRETTY_FUNCTION__))
;
2034 D = getCanonicalDecl(D);
2035 OpenMPClauseKind OMPC = OMPC_unknown;
2036 for (unsigned I = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel() + 1; I > Level; --I) {
2037 const unsigned NewLevel = I - 1;
2038 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(D,
2039 [&OMPC](const OpenMPClauseKind K) {
2040 if (isOpenMPPrivate(K)) {
2041 OMPC = K;
2042 return true;
2043 }
2044 return false;
2045 },
2046 NewLevel))
2047 break;
2048 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
2049 D, NewLevel,
2050 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2051 OpenMPClauseKind) { return true; })) {
2052 OMPC = OMPC_map;
2053 break;
2054 }
2055 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2056 NewLevel)) {
2057 OMPC = OMPC_map;
2058 if (D->getType()->isScalarType() &&
2059 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(NewLevel) !=
2060 DefaultMapAttributes::DMA_tofrom_scalar)
2061 OMPC = OMPC_firstprivate;
2062 break;
2063 }
2064 }
2065 if (OMPC != OMPC_unknown)
2066 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2067}
2068
2069bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2070 unsigned Level) const {
2071 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 2071, __PRETTY_FUNCTION__))
;
2072 // Return true if the current level is no longer enclosed in a target region.
2073
2074 const auto *VD = dyn_cast<VarDecl>(D);
2075 return VD && !VD->hasLocalStorage() &&
2076 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2077 Level);
2078}
2079
2080void Sema::DestroyDataSharingAttributesStack() { delete DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
; }
2081
2082void Sema::finalizeOpenMPDelayedAnalysis() {
2083 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.")((LangOpts.OpenMP && "Expected OpenMP compilation mode."
) ? static_cast<void> (0) : __assert_fail ("LangOpts.OpenMP && \"Expected OpenMP compilation mode.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 2083, __PRETTY_FUNCTION__))
;
2084 // Diagnose implicit declare target functions and their callees.
2085 for (const auto &CallerCallees : DeviceCallGraph) {
2086 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2087 OMPDeclareTargetDeclAttr::getDeviceType(
2088 CallerCallees.getFirst()->getMostRecentDecl());
2089 // Ignore host functions during device analyzis.
2090 if (LangOpts.OpenMPIsDevice && DevTy &&
2091 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2092 continue;
2093 // Ignore nohost functions during host analyzis.
2094 if (!LangOpts.OpenMPIsDevice && DevTy &&
2095 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2096 continue;
2097 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2098 &Callee : CallerCallees.getSecond()) {
2099 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2100 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2101 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2102 if (LangOpts.OpenMPIsDevice && DevTy &&
2103 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2104 // Diagnose host function called during device codegen.
2105 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2106 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2107 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2108 << HostDevTy << 0;
2109 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2110 diag::note_omp_marked_device_type_here)
2111 << HostDevTy;
2112 continue;
2113 }
2114 if (!LangOpts.OpenMPIsDevice && DevTy &&
2115 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2116 // Diagnose nohost function called during host codegen.
2117 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2118 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2119 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2120 << NoHostDevTy << 1;
2121 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2122 diag::note_omp_marked_device_type_here)
2123 << NoHostDevTy;
2124 continue;
2125 }
2126 }
2127 }
2128}
2129
2130void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2131 const DeclarationNameInfo &DirName,
2132 Scope *CurScope, SourceLocation Loc) {
2133 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->push(DKind, DirName, CurScope, Loc);
2134 PushExpressionEvaluationContext(
2135 ExpressionEvaluationContext::PotentiallyEvaluated);
2136}
2137
2138void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2139 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(K);
2140}
2141
2142void Sema::EndOpenMPClause() {
2143 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(/*K=*/OMPC_unknown);
2144}
2145
2146static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2147 ArrayRef<OMPClause *> Clauses);
2148
2149void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2150 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2151 // A variable of class type (or array thereof) that appears in a lastprivate
2152 // clause requires an accessible, unambiguous default constructor for the
2153 // class type, unless the list item is also specified in a firstprivate
2154 // clause.
2155 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2156 for (OMPClause *C : D->clauses()) {
2157 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2158 SmallVector<Expr *, 8> PrivateCopies;
2159 for (Expr *DE : Clause->varlists()) {
2160 if (DE->isValueDependent() || DE->isTypeDependent()) {
2161 PrivateCopies.push_back(nullptr);
2162 continue;
2163 }
2164 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2165 auto *VD = cast<VarDecl>(DRE->getDecl());
2166 QualType Type = VD->getType().getNonReferenceType();
2167 const DSAStackTy::DSAVarData DVar =
2168 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, /*FromParent=*/false);
2169 if (DVar.CKind == OMPC_lastprivate) {
2170 // Generate helper private variable and initialize it with the
2171 // default value. The address of the original variable is replaced
2172 // by the address of the new private variable in CodeGen. This new
2173 // variable is not added to IdResolver, so the code in the OpenMP
2174 // region uses original variable for proper diagnostics.
2175 VarDecl *VDPrivate = buildVarDecl(
2176 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2177 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2178 ActOnUninitializedDecl(VDPrivate);
2179 if (VDPrivate->isInvalidDecl()) {
2180 PrivateCopies.push_back(nullptr);
2181 continue;
2182 }
2183 PrivateCopies.push_back(buildDeclRefExpr(
2184 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2185 } else {
2186 // The variable is also a firstprivate, so initialization sequence
2187 // for private copy is generated already.
2188 PrivateCopies.push_back(nullptr);
2189 }
2190 }
2191 Clause->setPrivateCopies(PrivateCopies);
2192 }
2193 }
2194 // Check allocate clauses.
2195 if (!CurContext->isDependentContext())
2196 checkAllocateClauses(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D->clauses());
2197 }
2198
2199 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pop();
2200 DiscardCleanupsInEvaluationContext();
2201 PopExpressionEvaluationContext();
2202}
2203
2204static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2205 Expr *NumIterations, Sema &SemaRef,
2206 Scope *S, DSAStackTy *Stack);
2207
2208namespace {
2209
2210class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2211private:
2212 Sema &SemaRef;
2213
2214public:
2215 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2216 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2217 NamedDecl *ND = Candidate.getCorrectionDecl();
2218 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2219 return VD->hasGlobalStorage() &&
2220 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2221 SemaRef.getCurScope());
2222 }
2223 return false;
2224 }
2225
2226 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2227 return std::make_unique<VarDeclFilterCCC>(*this);
2228 }
2229
2230};
2231
2232class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2233private:
2234 Sema &SemaRef;
2235
2236public:
2237 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2238 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2239 NamedDecl *ND = Candidate.getCorrectionDecl();
2240 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2241 isa<FunctionDecl>(ND))) {
2242 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2243 SemaRef.getCurScope());
2244 }
2245 return false;
2246 }
2247
2248 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2249 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2250 }
2251};
2252
2253} // namespace
2254
2255ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2256 CXXScopeSpec &ScopeSpec,
2257 const DeclarationNameInfo &Id,
2258 OpenMPDirectiveKind Kind) {
2259 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2260 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2261
2262 if (Lookup.isAmbiguous())
2263 return ExprError();
2264
2265 VarDecl *VD;
2266 if (!Lookup.isSingleResult()) {
2267 VarDeclFilterCCC CCC(*this);
2268 if (TypoCorrection Corrected =
2269 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2270 CTK_ErrorRecovery)) {
2271 diagnoseTypo(Corrected,
2272 PDiag(Lookup.empty()
2273 ? diag::err_undeclared_var_use_suggest
2274 : diag::err_omp_expected_var_arg_suggest)
2275 << Id.getName());
2276 VD = Corrected.getCorrectionDeclAs<VarDecl>();
2277 } else {
2278 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2279 : diag::err_omp_expected_var_arg)
2280 << Id.getName();
2281 return ExprError();
2282 }
2283 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2284 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2285 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2286 return ExprError();
2287 }
2288 Lookup.suppressDiagnostics();
2289
2290 // OpenMP [2.9.2, Syntax, C/C++]
2291 // Variables must be file-scope, namespace-scope, or static block-scope.
2292 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2293 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2294 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2295 bool IsDecl =
2296 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2297 Diag(VD->getLocation(),
2298 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2299 << VD;
2300 return ExprError();
2301 }
2302
2303 VarDecl *CanonicalVD = VD->getCanonicalDecl();
2304 NamedDecl *ND = CanonicalVD;
2305 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2306 // A threadprivate directive for file-scope variables must appear outside
2307 // any definition or declaration.
2308 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2309 !getCurLexicalContext()->isTranslationUnit()) {
2310 Diag(Id.getLoc(), diag::err_omp_var_scope)
2311 << getOpenMPDirectiveName(Kind) << VD;
2312 bool IsDecl =
2313 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2314 Diag(VD->getLocation(),
2315 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2316 << VD;
2317 return ExprError();
2318 }
2319 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2320 // A threadprivate directive for static class member variables must appear
2321 // in the class definition, in the same scope in which the member
2322 // variables are declared.
2323 if (CanonicalVD->isStaticDataMember() &&
2324 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2325 Diag(Id.getLoc(), diag::err_omp_var_scope)
2326 << getOpenMPDirectiveName(Kind) << VD;
2327 bool IsDecl =
2328 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2329 Diag(VD->getLocation(),
2330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2331 << VD;
2332 return ExprError();
2333 }
2334 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2335 // A threadprivate directive for namespace-scope variables must appear
2336 // outside any definition or declaration other than the namespace
2337 // definition itself.
2338 if (CanonicalVD->getDeclContext()->isNamespace() &&
2339 (!getCurLexicalContext()->isFileContext() ||
2340 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2341 Diag(Id.getLoc(), diag::err_omp_var_scope)
2342 << getOpenMPDirectiveName(Kind) << VD;
2343 bool IsDecl =
2344 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2345 Diag(VD->getLocation(),
2346 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2347 << VD;
2348 return ExprError();
2349 }
2350 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2351 // A threadprivate directive for static block-scope variables must appear
2352 // in the scope of the variable and not in a nested scope.
2353 if (CanonicalVD->isLocalVarDecl() && CurScope &&
2354 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2355 Diag(Id.getLoc(), diag::err_omp_var_scope)
2356 << getOpenMPDirectiveName(Kind) << VD;
2357 bool IsDecl =
2358 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2359 Diag(VD->getLocation(),
2360 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2361 << VD;
2362 return ExprError();
2363 }
2364
2365 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2366 // A threadprivate directive must lexically precede all references to any
2367 // of the variables in its list.
2368 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2369 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
2370 Diag(Id.getLoc(), diag::err_omp_var_used)
2371 << getOpenMPDirectiveName(Kind) << VD;
2372 return ExprError();
2373 }
2374
2375 QualType ExprType = VD->getType().getNonReferenceType();
2376 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2377 SourceLocation(), VD,
2378 /*RefersToEnclosingVariableOrCapture=*/false,
2379 Id.getLoc(), ExprType, VK_LValue);
2380}
2381
2382Sema::DeclGroupPtrTy
2383Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2384 ArrayRef<Expr *> VarList) {
2385 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2386 CurContext->addDecl(D);
2387 return DeclGroupPtrTy::make(DeclGroupRef(D));
2388 }
2389 return nullptr;
2390}
2391
2392namespace {
2393class LocalVarRefChecker final
2394 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2395 Sema &SemaRef;
2396
2397public:
2398 bool VisitDeclRefExpr(const DeclRefExpr *E) {
2399 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2400 if (VD->hasLocalStorage()) {
2401 SemaRef.Diag(E->getBeginLoc(),
2402 diag::err_omp_local_var_in_threadprivate_init)
2403 << E->getSourceRange();
2404 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2405 << VD << VD->getSourceRange();
2406 return true;
2407 }
2408 }
2409 return false;
2410 }
2411 bool VisitStmt(const Stmt *S) {
2412 for (const Stmt *Child : S->children()) {
2413 if (Child && Visit(Child))
2414 return true;
2415 }
2416 return false;
2417 }
2418 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2419};
2420} // namespace
2421
2422OMPThreadPrivateDecl *
2423Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2424 SmallVector<Expr *, 8> Vars;
2425 for (Expr *RefExpr : VarList) {
2426 auto *DE = cast<DeclRefExpr>(RefExpr);
2427 auto *VD = cast<VarDecl>(DE->getDecl());
2428 SourceLocation ILoc = DE->getExprLoc();
2429
2430 // Mark variable as used.
2431 VD->setReferenced();
2432 VD->markUsed(Context);
2433
2434 QualType QType = VD->getType();
2435 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2436 // It will be analyzed later.
2437 Vars.push_back(DE);
2438 continue;
2439 }
2440
2441 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2442 // A threadprivate variable must not have an incomplete type.
2443 if (RequireCompleteType(ILoc, VD->getType(),
2444 diag::err_omp_threadprivate_incomplete_type)) {
2445 continue;
2446 }
2447
2448 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2449 // A threadprivate variable must not have a reference type.
2450 if (VD->getType()->isReferenceType()) {
2451 Diag(ILoc, diag::err_omp_ref_type_arg)
2452 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2453 bool IsDecl =
2454 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2455 Diag(VD->getLocation(),
2456 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2457 << VD;
2458 continue;
2459 }
2460
2461 // Check if this is a TLS variable. If TLS is not being supported, produce
2462 // the corresponding diagnostic.
2463 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2464 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2465 getLangOpts().OpenMPUseTLS &&
2466 getASTContext().getTargetInfo().isTLSSupported())) ||
2467 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2468 !VD->isLocalVarDecl())) {
2469 Diag(ILoc, diag::err_omp_var_thread_local)
2470 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2471 bool IsDecl =
2472 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2473 Diag(VD->getLocation(),
2474 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2475 << VD;
2476 continue;
2477 }
2478
2479 // Check if initial value of threadprivate variable reference variable with
2480 // local storage (it is not supported by runtime).
2481 if (const Expr *Init = VD->getAnyInitializer()) {
2482 LocalVarRefChecker Checker(*this);
2483 if (Checker.Visit(Init))
2484 continue;
2485 }
2486
2487 Vars.push_back(RefExpr);
2488 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_threadprivate);
2489 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2490 Context, SourceRange(Loc, Loc)));
2491 if (ASTMutationListener *ML = Context.getASTMutationListener())
2492 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2493 }
2494 OMPThreadPrivateDecl *D = nullptr;
2495 if (!Vars.empty()) {
2496 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2497 Vars);
2498 D->setAccess(AS_public);
2499 }
2500 return D;
2501}
2502
2503static OMPAllocateDeclAttr::AllocatorTypeTy
2504getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2505 if (!Allocator)
2506 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2507 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2508 Allocator->isInstantiationDependent() ||
2509 Allocator->containsUnexpandedParameterPack())
2510 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2511 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2512 const Expr *AE = Allocator->IgnoreParenImpCasts();
2513 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2514 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2515 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2516 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2517 llvm::FoldingSetNodeID AEId, DAEId;
2518 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2519 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2520 if (AEId == DAEId) {
2521 AllocatorKindRes = AllocatorKind;
2522 break;
2523 }
2524 }
2525 return AllocatorKindRes;
2526}
2527
2528static bool checkPreviousOMPAllocateAttribute(
2529 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2530 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2531 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2532 return false;
2533 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2534 Expr *PrevAllocator = A->getAllocator();
2535 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2536 getAllocatorKind(S, Stack, PrevAllocator);
2537 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2538 if (AllocatorsMatch &&
2539 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2540 Allocator && PrevAllocator) {
2541 const Expr *AE = Allocator->IgnoreParenImpCasts();
2542 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2543 llvm::FoldingSetNodeID AEId, PAEId;
2544 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2545 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2546 AllocatorsMatch = AEId == PAEId;
2547 }
2548 if (!AllocatorsMatch) {
2549 SmallString<256> AllocatorBuffer;
2550 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2551 if (Allocator)
2552 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2553 SmallString<256> PrevAllocatorBuffer;
2554 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2555 if (PrevAllocator)
2556 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2557 S.getPrintingPolicy());
2558
2559 SourceLocation AllocatorLoc =
2560 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2561 SourceRange AllocatorRange =
2562 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2563 SourceLocation PrevAllocatorLoc =
2564 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2565 SourceRange PrevAllocatorRange =
2566 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2567 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2568 << (Allocator ? 1 : 0) << AllocatorStream.str()
2569 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2570 << AllocatorRange;
2571 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2572 << PrevAllocatorRange;
2573 return true;
2574 }
2575 return false;
2576}
2577
2578static void
2579applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2580 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2581 Expr *Allocator, SourceRange SR) {
2582 if (VD->hasAttr<OMPAllocateDeclAttr>())
2583 return;
2584 if (Allocator &&
2585 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2586 Allocator->isInstantiationDependent() ||
2587 Allocator->containsUnexpandedParameterPack()))
2588 return;
2589 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2590 Allocator, SR);
2591 VD->addAttr(A);
2592 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2593 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2594}
2595
2596Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2597 SourceLocation Loc, ArrayRef<Expr *> VarList,
2598 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2599 assert(Clauses.size() <= 1 && "Expected at most one clause.")((Clauses.size() <= 1 && "Expected at most one clause."
) ? static_cast<void> (0) : __assert_fail ("Clauses.size() <= 1 && \"Expected at most one clause.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 2599, __PRETTY_FUNCTION__))
;
2600 Expr *Allocator = nullptr;
2601 if (Clauses.empty()) {
2602 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2603 // allocate directives that appear in a target region must specify an
2604 // allocator clause unless a requires directive with the dynamic_allocators
2605 // clause is present in the same compilation unit.
2606 if (LangOpts.OpenMPIsDevice &&
2607 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
2608 targetDiag(Loc, diag::err_expected_allocator_clause);
2609 } else {
2610 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
2611 }
2612 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2613 getAllocatorKind(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Allocator);
2614 SmallVector<Expr *, 8> Vars;
2615 for (Expr *RefExpr : VarList) {
2616 auto *DE = cast<DeclRefExpr>(RefExpr);
2617 auto *VD = cast<VarDecl>(DE->getDecl());
2618
2619 // Check if this is a TLS variable or global register.
2620 if (VD->getTLSKind() != VarDecl::TLS_None ||
2621 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2622 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2623 !VD->isLocalVarDecl()))
2624 continue;
2625
2626 // If the used several times in the allocate directive, the same allocator
2627 // must be used.
2628 if (checkPreviousOMPAllocateAttribute(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, RefExpr, VD,
2629 AllocatorKind, Allocator))
2630 continue;
2631
2632 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2633 // If a list item has a static storage type, the allocator expression in the
2634 // allocator clause must be a constant expression that evaluates to one of
2635 // the predefined memory allocator values.
2636 if (Allocator && VD->hasGlobalStorage()) {
2637 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
2638 Diag(Allocator->getExprLoc(),
2639 diag::err_omp_expected_predefined_allocator)
2640 << Allocator->getSourceRange();
2641 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2642 VarDecl::DeclarationOnly;
2643 Diag(VD->getLocation(),
2644 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2645 << VD;
2646 continue;
2647 }
2648 }
2649
2650 Vars.push_back(RefExpr);
2651 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2652 DE->getSourceRange());
2653 }
2654 if (Vars.empty())
2655 return nullptr;
2656 if (!Owner)
2657 Owner = getCurLexicalContext();
2658 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
2659 D->setAccess(AS_public);
2660 Owner->addDecl(D);
2661 return DeclGroupPtrTy::make(DeclGroupRef(D));
2662}
2663
2664Sema::DeclGroupPtrTy
2665Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2666 ArrayRef<OMPClause *> ClauseList) {
2667 OMPRequiresDecl *D = nullptr;
2668 if (!CurContext->isFileContext()) {
2669 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2670 } else {
2671 D = CheckOMPRequiresDecl(Loc, ClauseList);
2672 if (D) {
2673 CurContext->addDecl(D);
2674 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addRequiresDecl(D);
2675 }
2676 }
2677 return DeclGroupPtrTy::make(DeclGroupRef(D));
2678}
2679
2680OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2681 ArrayRef<OMPClause *> ClauseList) {
2682 /// For target specific clauses, the requires directive cannot be
2683 /// specified after the handling of any of the target regions in the
2684 /// current compilation unit.
2685 ArrayRef<SourceLocation> TargetLocations =
2686 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getEncounteredTargetLocs();
2687 if (!TargetLocations.empty()) {
2688 for (const OMPClause *CNew : ClauseList) {
2689 // Check if any of the requires clauses affect target regions.
2690 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2691 isa<OMPUnifiedAddressClause>(CNew) ||
2692 isa<OMPReverseOffloadClause>(CNew) ||
2693 isa<OMPDynamicAllocatorsClause>(CNew)) {
2694 Diag(Loc, diag::err_omp_target_before_requires)
2695 << getOpenMPClauseName(CNew->getClauseKind());
2696 for (SourceLocation TargetLoc : TargetLocations) {
2697 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2698 }
2699 }
2700 }
2701 }
2702
2703 if (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDuplicateRequiresClause(ClauseList))
2704 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2705 ClauseList);
2706 return nullptr;
2707}
2708
2709static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2710 const ValueDecl *D,
2711 const DSAStackTy::DSAVarData &DVar,
2712 bool IsLoopIterVar = false) {
2713 if (DVar.RefExpr) {
2714 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2715 << getOpenMPClauseName(DVar.CKind);
2716 return;
2717 }
2718 enum {
2719 PDSA_StaticMemberShared,
2720 PDSA_StaticLocalVarShared,
2721 PDSA_LoopIterVarPrivate,
2722 PDSA_LoopIterVarLinear,
2723 PDSA_LoopIterVarLastprivate,
2724 PDSA_ConstVarShared,
2725 PDSA_GlobalVarShared,
2726 PDSA_TaskVarFirstprivate,
2727 PDSA_LocalVarPrivate,
2728 PDSA_Implicit
2729 } Reason = PDSA_Implicit;
2730 bool ReportHint = false;
2731 auto ReportLoc = D->getLocation();
2732 auto *VD = dyn_cast<VarDecl>(D);
2733 if (IsLoopIterVar) {
2734 if (DVar.CKind == OMPC_private)
2735 Reason = PDSA_LoopIterVarPrivate;
2736 else if (DVar.CKind == OMPC_lastprivate)
2737 Reason = PDSA_LoopIterVarLastprivate;
2738 else
2739 Reason = PDSA_LoopIterVarLinear;
2740 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2741 DVar.CKind == OMPC_firstprivate) {
2742 Reason = PDSA_TaskVarFirstprivate;
2743 ReportLoc = DVar.ImplicitDSALoc;
2744 } else if (VD && VD->isStaticLocal())
2745 Reason = PDSA_StaticLocalVarShared;
2746 else if (VD && VD->isStaticDataMember())
2747 Reason = PDSA_StaticMemberShared;
2748 else if (VD && VD->isFileVarDecl())
2749 Reason = PDSA_GlobalVarShared;
2750 else if (D->getType().isConstant(SemaRef.getASTContext()))
2751 Reason = PDSA_ConstVarShared;
2752 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2753 ReportHint = true;
2754 Reason = PDSA_LocalVarPrivate;
2755 }
2756 if (Reason != PDSA_Implicit) {
2757 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2758 << Reason << ReportHint
2759 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2760 } else if (DVar.ImplicitDSALoc.isValid()) {
2761 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2762 << getOpenMPClauseName(DVar.CKind);
2763 }
2764}
2765
2766namespace {
2767class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2768 DSAStackTy *Stack;
2769 Sema &SemaRef;
2770 bool ErrorFound = false;
2771 bool TryCaptureCXXThisMembers = false;
2772 CapturedStmt *CS = nullptr;
2773 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2774 llvm::SmallVector<Expr *, 4> ImplicitMap;
2775 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2776 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2777
2778 void VisitSubCaptures(OMPExecutableDirective *S) {
2779 // Check implicitly captured variables.
2780 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2781 return;
2782 visitSubCaptures(S->getInnermostCapturedStmt());
2783 // Try to capture inner this->member references to generate correct mappings
2784 // and diagnostics.
2785 if (TryCaptureCXXThisMembers ||
2786 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2787 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2788 [](const CapturedStmt::Capture &C) {
2789 return C.capturesThis();
2790 }))) {
2791 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2792 TryCaptureCXXThisMembers = true;
2793 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2794 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2795 }
2796 }
2797
2798public:
2799 void VisitDeclRefExpr(DeclRefExpr *E) {
2800 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2801 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2802 E->isInstantiationDependent())
2803 return;
2804 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2805 // Check the datasharing rules for the expressions in the clauses.
2806 if (!CS) {
2807 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2808 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2809 Visit(CED->getInit());
2810 return;
2811 }
2812 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2813 // Do not analyze internal variables and do not enclose them into
2814 // implicit clauses.
2815 return;
2816 VD = VD->getCanonicalDecl();
2817 // Skip internally declared variables.
2818 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
2819 return;
2820
2821 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2822 // Check if the variable has explicit DSA set and stop analysis if it so.
2823 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2824 return;
2825
2826 // Skip internally declared static variables.
2827 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2828 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2829 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
2830 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2831 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2832 return;
2833
2834 SourceLocation ELoc = E->getExprLoc();
2835 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2836 // The default(none) clause requires that each variable that is referenced
2837 // in the construct, and does not have a predetermined data-sharing
2838 // attribute, must have its data-sharing attribute explicitly determined
2839 // by being listed in a data-sharing attribute clause.
2840 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2841 isImplicitOrExplicitTaskingRegion(DKind) &&
2842 VarsWithInheritedDSA.count(VD) == 0) {
2843 VarsWithInheritedDSA[VD] = E;
2844 return;
2845 }
2846
2847 if (isOpenMPTargetExecutionDirective(DKind) &&
2848 !Stack->isLoopControlVariable(VD).first) {
2849 if (!Stack->checkMappableExprComponentListsForDecl(
2850 VD, /*CurrentRegionOnly=*/true,
2851 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2852 StackComponents,
2853 OpenMPClauseKind) {
2854 // Variable is used if it has been marked as an array, array
2855 // section or the variable iself.
2856 return StackComponents.size() == 1 ||
2857 std::all_of(
2858 std::next(StackComponents.rbegin()),
2859 StackComponents.rend(),
2860 [](const OMPClauseMappableExprCommon::
2861 MappableComponent &MC) {
2862 return MC.getAssociatedDeclaration() ==
2863 nullptr &&
2864 (isa<OMPArraySectionExpr>(
2865 MC.getAssociatedExpression()) ||
2866 isa<ArraySubscriptExpr>(
2867 MC.getAssociatedExpression()));
2868 });
2869 })) {
2870 bool IsFirstprivate = false;
2871 // By default lambdas are captured as firstprivates.
2872 if (const auto *RD =
2873 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2874 IsFirstprivate = RD->isLambda();
2875 IsFirstprivate =
2876 IsFirstprivate ||
2877 (VD->getType().getNonReferenceType()->isScalarType() &&
2878 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2879 if (IsFirstprivate)
2880 ImplicitFirstprivate.emplace_back(E);
2881 else
2882 ImplicitMap.emplace_back(E);
2883 return;
2884 }
2885 }
2886
2887 // OpenMP [2.9.3.6, Restrictions, p.2]
2888 // A list item that appears in a reduction clause of the innermost
2889 // enclosing worksharing or parallel construct may not be accessed in an
2890 // explicit task.
2891 DVar = Stack->hasInnermostDSA(
2892 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2893 [](OpenMPDirectiveKind K) {
2894 return isOpenMPParallelDirective(K) ||
2895 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2896 },
2897 /*FromParent=*/true);
2898 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2899 ErrorFound = true;
2900 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2901 reportOriginalDsa(SemaRef, Stack, VD, DVar);
2902 return;
2903 }
2904
2905 // Define implicit data-sharing attributes for task.
2906 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2907 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2908 !Stack->isLoopControlVariable(VD).first) {
2909 ImplicitFirstprivate.push_back(E);
2910 return;
2911 }
2912
2913 // Store implicitly used globals with declare target link for parent
2914 // target.
2915 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2916 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2917 Stack->addToParentTargetRegionLinkGlobals(E);
2918 return;
2919 }
2920 }
2921 }
2922 void VisitMemberExpr(MemberExpr *E) {
2923 if (E->isTypeDependent() || E->isValueDependent() ||
2924 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2925 return;
2926 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2927 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2928 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2929 if (!FD)
2930 return;
2931 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2932 // Check if the variable has explicit DSA set and stop analysis if it
2933 // so.
2934 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2935 return;
2936
2937 if (isOpenMPTargetExecutionDirective(DKind) &&
2938 !Stack->isLoopControlVariable(FD).first &&
2939 !Stack->checkMappableExprComponentListsForDecl(
2940 FD, /*CurrentRegionOnly=*/true,
2941 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2942 StackComponents,
2943 OpenMPClauseKind) {
2944 return isa<CXXThisExpr>(
2945 cast<MemberExpr>(
2946 StackComponents.back().getAssociatedExpression())
2947 ->getBase()
2948 ->IgnoreParens());
2949 })) {
2950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2951 // A bit-field cannot appear in a map clause.
2952 //
2953 if (FD->isBitField())
2954 return;
2955
2956 // Check to see if the member expression is referencing a class that
2957 // has already been explicitly mapped
2958 if (Stack->isClassPreviouslyMapped(TE->getType()))
2959 return;
2960
2961 ImplicitMap.emplace_back(E);
2962 return;
2963 }
2964
2965 SourceLocation ELoc = E->getExprLoc();
2966 // OpenMP [2.9.3.6, Restrictions, p.2]
2967 // A list item that appears in a reduction clause of the innermost
2968 // enclosing worksharing or parallel construct may not be accessed in
2969 // an explicit task.
2970 DVar = Stack->hasInnermostDSA(
2971 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2972 [](OpenMPDirectiveKind K) {
2973 return isOpenMPParallelDirective(K) ||
2974 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2975 },
2976 /*FromParent=*/true);
2977 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2978 ErrorFound = true;
2979 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2980 reportOriginalDsa(SemaRef, Stack, FD, DVar);
2981 return;
2982 }
2983
2984 // Define implicit data-sharing attributes for task.
2985 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2986 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2987 !Stack->isLoopControlVariable(FD).first) {
2988 // Check if there is a captured expression for the current field in the
2989 // region. Do not mark it as firstprivate unless there is no captured
2990 // expression.
2991 // TODO: try to make it firstprivate.
2992 if (DVar.CKind != OMPC_unknown)
2993 ImplicitFirstprivate.push_back(E);
2994 }
2995 return;
2996 }
2997 if (isOpenMPTargetExecutionDirective(DKind)) {
2998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2999 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3000 /*NoDiagnose=*/true))
3001 return;
3002 const auto *VD = cast<ValueDecl>(
3003 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3004 if (!Stack->checkMappableExprComponentListsForDecl(
3005 VD, /*CurrentRegionOnly=*/true,
3006 [&CurComponents](
3007 OMPClauseMappableExprCommon::MappableExprComponentListRef
3008 StackComponents,
3009 OpenMPClauseKind) {
3010 auto CCI = CurComponents.rbegin();
3011 auto CCE = CurComponents.rend();
3012 for (const auto &SC : llvm::reverse(StackComponents)) {
3013 // Do both expressions have the same kind?
3014 if (CCI->getAssociatedExpression()->getStmtClass() !=
3015 SC.getAssociatedExpression()->getStmtClass())
3016 if (!(isa<OMPArraySectionExpr>(
3017 SC.getAssociatedExpression()) &&
3018 isa<ArraySubscriptExpr>(
3019 CCI->getAssociatedExpression())))
3020 return false;
3021
3022 const Decl *CCD = CCI->getAssociatedDeclaration();
3023 const Decl *SCD = SC.getAssociatedDeclaration();
3024 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3025 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3026 if (SCD != CCD)
3027 return false;
3028 std::advance(CCI, 1);
3029 if (CCI == CCE)
3030 break;
3031 }
3032 return true;
3033 })) {
3034 Visit(E->getBase());
3035 }
3036 } else if (!TryCaptureCXXThisMembers) {
3037 Visit(E->getBase());
3038 }
3039 }
3040 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3041 for (OMPClause *C : S->clauses()) {
3042 // Skip analysis of arguments of implicitly defined firstprivate clause
3043 // for task|target directives.
3044 // Skip analysis of arguments of implicitly defined map clause for target
3045 // directives.
3046 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3047 C->isImplicit())) {
3048 for (Stmt *CC : C->children()) {
3049 if (CC)
3050 Visit(CC);
3051 }
3052 }
3053 }
3054 // Check implicitly captured variables.
3055 VisitSubCaptures(S);
3056 }
3057 void VisitStmt(Stmt *S) {
3058 for (Stmt *C : S->children()) {
3059 if (C) {
3060 // Check implicitly captured variables in the task-based directives to
3061 // check if they must be firstprivatized.
3062 Visit(C);
3063 }
3064 }
3065 }
3066
3067 void visitSubCaptures(CapturedStmt *S) {
3068 for (const CapturedStmt::Capture &Cap : S->captures()) {
3069 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3070 continue;
3071 VarDecl *VD = Cap.getCapturedVar();
3072 // Do not try to map the variable if it or its sub-component was mapped
3073 // already.
3074 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3075 Stack->checkMappableExprComponentListsForDecl(
3076 VD, /*CurrentRegionOnly=*/true,
3077 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3078 OpenMPClauseKind) { return true; }))
3079 continue;
3080 DeclRefExpr *DRE = buildDeclRefExpr(
3081 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3082 Cap.getLocation(), /*RefersToCapture=*/true);
3083 Visit(DRE);
3084 }
3085 }
3086 bool isErrorFound() const { return ErrorFound; }
3087 ArrayRef<Expr *> getImplicitFirstprivate() const {
3088 return ImplicitFirstprivate;
3089 }
3090 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
3091 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3092 return VarsWithInheritedDSA;
3093 }
3094
3095 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3096 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3097 // Process declare target link variables for the target directives.
3098 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3099 for (DeclRefExpr *E : Stack->getLinkGlobals())
3100 Visit(E);
3101 }
3102 }
3103};
3104} // namespace
3105
3106void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3107 switch (DKind) {
3108 case OMPD_parallel:
3109 case OMPD_parallel_for:
3110 case OMPD_parallel_for_simd:
3111 case OMPD_parallel_sections:
3112 case OMPD_teams:
3113 case OMPD_teams_distribute:
3114 case OMPD_teams_distribute_simd: {
3115 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3118 Sema::CapturedParamNameType Params[] = {
3119 std::make_pair(".global_tid.", KmpInt32PtrTy),
3120 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3121 std::make_pair(StringRef(), QualType()) // __context with shared vars
3122 };
3123 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3124 Params);
3125 break;
3126 }
3127 case OMPD_target_teams:
3128 case OMPD_target_parallel:
3129 case OMPD_target_parallel_for:
3130 case OMPD_target_parallel_for_simd:
3131 case OMPD_target_teams_distribute:
3132 case OMPD_target_teams_distribute_simd: {
3133 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3134 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3135 QualType KmpInt32PtrTy =
3136 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3137 QualType Args[] = {VoidPtrTy};
3138 FunctionProtoType::ExtProtoInfo EPI;
3139 EPI.Variadic = true;
3140 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3141 Sema::CapturedParamNameType Params[] = {
3142 std::make_pair(".global_tid.", KmpInt32Ty),
3143 std::make_pair(".part_id.", KmpInt32PtrTy),
3144 std::make_pair(".privates.", VoidPtrTy),
3145 std::make_pair(
3146 ".copy_fn.",
3147 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3148 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
3151 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3152 Params, /*OpenMPCaptureLevel=*/0);
3153 // Mark this captured region as inlined, because we don't use outlined
3154 // function directly.
3155 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3156 AlwaysInlineAttr::CreateImplicit(
3157 Context, {}, AttributeCommonInfo::AS_Keyword,
3158 AlwaysInlineAttr::Keyword_forceinline));
3159 Sema::CapturedParamNameType ParamsTarget[] = {
3160 std::make_pair(StringRef(), QualType()) // __context with shared vars
3161 };
3162 // Start a captured region for 'target' with no implicit parameters.
3163 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3164 ParamsTarget, /*OpenMPCaptureLevel=*/1);
3165 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3166 std::make_pair(".global_tid.", KmpInt32PtrTy),
3167 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3168 std::make_pair(StringRef(), QualType()) // __context with shared vars
3169 };
3170 // Start a captured region for 'teams' or 'parallel'. Both regions have
3171 // the same implicit parameters.
3172 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3173 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3174 break;
3175 }
3176 case OMPD_target:
3177 case OMPD_target_simd: {
3178 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3179 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3180 QualType KmpInt32PtrTy =
3181 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3182 QualType Args[] = {VoidPtrTy};
3183 FunctionProtoType::ExtProtoInfo EPI;
3184 EPI.Variadic = true;
3185 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3186 Sema::CapturedParamNameType Params[] = {
3187 std::make_pair(".global_tid.", KmpInt32Ty),
3188 std::make_pair(".part_id.", KmpInt32PtrTy),
3189 std::make_pair(".privates.", VoidPtrTy),
3190 std::make_pair(
3191 ".copy_fn.",
3192 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3193 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3194 std::make_pair(StringRef(), QualType()) // __context with shared vars
3195 };
3196 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3197 Params, /*OpenMPCaptureLevel=*/0);
3198 // Mark this captured region as inlined, because we don't use outlined
3199 // function directly.
3200 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3201 AlwaysInlineAttr::CreateImplicit(
3202 Context, {}, AttributeCommonInfo::AS_Keyword,
3203 AlwaysInlineAttr::Keyword_forceinline));
3204 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3205 std::make_pair(StringRef(), QualType()),
3206 /*OpenMPCaptureLevel=*/1);
3207 break;
3208 }
3209 case OMPD_simd:
3210 case OMPD_for:
3211 case OMPD_for_simd:
3212 case OMPD_sections:
3213 case OMPD_section:
3214 case OMPD_single:
3215 case OMPD_master:
3216 case OMPD_critical:
3217 case OMPD_taskgroup:
3218 case OMPD_distribute:
3219 case OMPD_distribute_simd:
3220 case OMPD_ordered:
3221 case OMPD_atomic:
3222 case OMPD_target_data: {
3223 Sema::CapturedParamNameType Params[] = {
3224 std::make_pair(StringRef(), QualType()) // __context with shared vars
3225 };
3226 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3227 Params);
3228 break;
3229 }
3230 case OMPD_task: {
3231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3232 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3233 QualType KmpInt32PtrTy =
3234 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3235 QualType Args[] = {VoidPtrTy};
3236 FunctionProtoType::ExtProtoInfo EPI;
3237 EPI.Variadic = true;
3238 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3239 Sema::CapturedParamNameType Params[] = {
3240 std::make_pair(".global_tid.", KmpInt32Ty),
3241 std::make_pair(".part_id.", KmpInt32PtrTy),
3242 std::make_pair(".privates.", VoidPtrTy),
3243 std::make_pair(
3244 ".copy_fn.",
3245 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3246 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3247 std::make_pair(StringRef(), QualType()) // __context with shared vars
3248 };
3249 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3250 Params);
3251 // Mark this captured region as inlined, because we don't use outlined
3252 // function directly.
3253 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3254 AlwaysInlineAttr::CreateImplicit(
3255 Context, {}, AttributeCommonInfo::AS_Keyword,
3256 AlwaysInlineAttr::Keyword_forceinline));
3257 break;
3258 }
3259 case OMPD_taskloop:
3260 case OMPD_taskloop_simd:
3261 case OMPD_master_taskloop:
3262 case OMPD_master_taskloop_simd: {
3263 QualType KmpInt32Ty =
3264 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3265 .withConst();
3266 QualType KmpUInt64Ty =
3267 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3268 .withConst();
3269 QualType KmpInt64Ty =
3270 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3271 .withConst();
3272 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3273 QualType KmpInt32PtrTy =
3274 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3275 QualType Args[] = {VoidPtrTy};
3276 FunctionProtoType::ExtProtoInfo EPI;
3277 EPI.Variadic = true;
3278 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3279 Sema::CapturedParamNameType Params[] = {
3280 std::make_pair(".global_tid.", KmpInt32Ty),
3281 std::make_pair(".part_id.", KmpInt32PtrTy),
3282 std::make_pair(".privates.", VoidPtrTy),
3283 std::make_pair(
3284 ".copy_fn.",
3285 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3286 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3287 std::make_pair(".lb.", KmpUInt64Ty),
3288 std::make_pair(".ub.", KmpUInt64Ty),
3289 std::make_pair(".st.", KmpInt64Ty),
3290 std::make_pair(".liter.", KmpInt32Ty),
3291 std::make_pair(".reductions.", VoidPtrTy),
3292 std::make_pair(StringRef(), QualType()) // __context with shared vars
3293 };
3294 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3295 Params);
3296 // Mark this captured region as inlined, because we don't use outlined
3297 // function directly.
3298 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3299 AlwaysInlineAttr::CreateImplicit(
3300 Context, {}, AttributeCommonInfo::AS_Keyword,
3301 AlwaysInlineAttr::Keyword_forceinline));
3302 break;
3303 }
3304 case OMPD_parallel_master_taskloop:
3305 case OMPD_parallel_master_taskloop_simd: {
3306 QualType KmpInt32Ty =
3307 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3308 .withConst();
3309 QualType KmpUInt64Ty =
3310 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3311 .withConst();
3312 QualType KmpInt64Ty =
3313 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3314 .withConst();
3315 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3316 QualType KmpInt32PtrTy =
3317 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3318 Sema::CapturedParamNameType ParamsParallel[] = {
3319 std::make_pair(".global_tid.", KmpInt32PtrTy),
3320 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3321 std::make_pair(StringRef(), QualType()) // __context with shared vars
3322 };
3323 // Start a captured region for 'parallel'.
3324 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3325 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3326 QualType Args[] = {VoidPtrTy};
3327 FunctionProtoType::ExtProtoInfo EPI;
3328 EPI.Variadic = true;
3329 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3330 Sema::CapturedParamNameType Params[] = {
3331 std::make_pair(".global_tid.", KmpInt32Ty),
3332 std::make_pair(".part_id.", KmpInt32PtrTy),
3333 std::make_pair(".privates.", VoidPtrTy),
3334 std::make_pair(
3335 ".copy_fn.",
3336 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3337 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3338 std::make_pair(".lb.", KmpUInt64Ty),
3339 std::make_pair(".ub.", KmpUInt64Ty),
3340 std::make_pair(".st.", KmpInt64Ty),
3341 std::make_pair(".liter.", KmpInt32Ty),
3342 std::make_pair(".reductions.", VoidPtrTy),
3343 std::make_pair(StringRef(), QualType()) // __context with shared vars
3344 };
3345 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3346 Params, /*OpenMPCaptureLevel=*/2);
3347 // Mark this captured region as inlined, because we don't use outlined
3348 // function directly.
3349 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3350 AlwaysInlineAttr::CreateImplicit(
3351 Context, {}, AttributeCommonInfo::AS_Keyword,
3352 AlwaysInlineAttr::Keyword_forceinline));
3353 break;
3354 }
3355 case OMPD_distribute_parallel_for_simd:
3356 case OMPD_distribute_parallel_for: {
3357 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3358 QualType KmpInt32PtrTy =
3359 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3360 Sema::CapturedParamNameType Params[] = {
3361 std::make_pair(".global_tid.", KmpInt32PtrTy),
3362 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3363 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3364 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3365 std::make_pair(StringRef(), QualType()) // __context with shared vars
3366 };
3367 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3368 Params);
3369 break;
3370 }
3371 case OMPD_target_teams_distribute_parallel_for:
3372 case OMPD_target_teams_distribute_parallel_for_simd: {
3373 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3374 QualType KmpInt32PtrTy =
3375 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3376 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3377
3378 QualType Args[] = {VoidPtrTy};
3379 FunctionProtoType::ExtProtoInfo EPI;
3380 EPI.Variadic = true;
3381 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3382 Sema::CapturedParamNameType Params[] = {
3383 std::make_pair(".global_tid.", KmpInt32Ty),
3384 std::make_pair(".part_id.", KmpInt32PtrTy),
3385 std::make_pair(".privates.", VoidPtrTy),
3386 std::make_pair(
3387 ".copy_fn.",
3388 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3389 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3390 std::make_pair(StringRef(), QualType()) // __context with shared vars
3391 };
3392 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3393 Params, /*OpenMPCaptureLevel=*/0);
3394 // Mark this captured region as inlined, because we don't use outlined
3395 // function directly.
3396 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3397 AlwaysInlineAttr::CreateImplicit(
3398 Context, {}, AttributeCommonInfo::AS_Keyword,
3399 AlwaysInlineAttr::Keyword_forceinline));
3400 Sema::CapturedParamNameType ParamsTarget[] = {
3401 std::make_pair(StringRef(), QualType()) // __context with shared vars
3402 };
3403 // Start a captured region for 'target' with no implicit parameters.
3404 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3405 ParamsTarget, /*OpenMPCaptureLevel=*/1);
3406
3407 Sema::CapturedParamNameType ParamsTeams[] = {
3408 std::make_pair(".global_tid.", KmpInt32PtrTy),
3409 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3410 std::make_pair(StringRef(), QualType()) // __context with shared vars
3411 };
3412 // Start a captured region for 'target' with no implicit parameters.
3413 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3414 ParamsTeams, /*OpenMPCaptureLevel=*/2);
3415
3416 Sema::CapturedParamNameType ParamsParallel[] = {
3417 std::make_pair(".global_tid.", KmpInt32PtrTy),
3418 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3419 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3420 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3421 std::make_pair(StringRef(), QualType()) // __context with shared vars
3422 };
3423 // Start a captured region for 'teams' or 'parallel'. Both regions have
3424 // the same implicit parameters.
3425 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3426 ParamsParallel, /*OpenMPCaptureLevel=*/3);
3427 break;
3428 }
3429
3430 case OMPD_teams_distribute_parallel_for:
3431 case OMPD_teams_distribute_parallel_for_simd: {
3432 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3433 QualType KmpInt32PtrTy =
3434 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3435
3436 Sema::CapturedParamNameType ParamsTeams[] = {
3437 std::make_pair(".global_tid.", KmpInt32PtrTy),
3438 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3439 std::make_pair(StringRef(), QualType()) // __context with shared vars
3440 };
3441 // Start a captured region for 'target' with no implicit parameters.
3442 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3443 ParamsTeams, /*OpenMPCaptureLevel=*/0);
3444
3445 Sema::CapturedParamNameType ParamsParallel[] = {
3446 std::make_pair(".global_tid.", KmpInt32PtrTy),
3447 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3448 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3449 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3450 std::make_pair(StringRef(), QualType()) // __context with shared vars
3451 };
3452 // Start a captured region for 'teams' or 'parallel'. Both regions have
3453 // the same implicit parameters.
3454 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3455 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3456 break;
3457 }
3458 case OMPD_target_update:
3459 case OMPD_target_enter_data:
3460 case OMPD_target_exit_data: {
3461 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3462 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3463 QualType KmpInt32PtrTy =
3464 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
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(StringRef(), QualType()) // __context with shared vars
3478 };
3479 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3480 Params);
3481 // Mark this captured region as inlined, because we don't use outlined
3482 // function directly.
3483 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3484 AlwaysInlineAttr::CreateImplicit(
3485 Context, {}, AttributeCommonInfo::AS_Keyword,
3486 AlwaysInlineAttr::Keyword_forceinline));
3487 break;
3488 }
3489 case OMPD_threadprivate:
3490 case OMPD_allocate:
3491 case OMPD_taskyield:
3492 case OMPD_barrier:
3493 case OMPD_taskwait:
3494 case OMPD_cancellation_point:
3495 case OMPD_cancel:
3496 case OMPD_flush:
3497 case OMPD_declare_reduction:
3498 case OMPD_declare_mapper:
3499 case OMPD_declare_simd:
3500 case OMPD_declare_target:
3501 case OMPD_end_declare_target:
3502 case OMPD_requires:
3503 case OMPD_declare_variant:
3504 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 3504)
;
3505 case OMPD_unknown:
3506 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 3506)
;
3507 }
3508}
3509
3510int Sema::getNumberOfConstructScopes(unsigned Level) const {
3511 return getOpenMPCaptureLevels(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
3512}
3513
3514int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3515 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3516 getOpenMPCaptureRegions(CaptureRegions, DKind);
3517 return CaptureRegions.size();
3518}
3519
3520static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
3521 Expr *CaptureExpr, bool WithInit,
3522 bool AsExpression) {
3523 assert(CaptureExpr)((CaptureExpr) ? static_cast<void> (0) : __assert_fail (
"CaptureExpr", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 3523, __PRETTY_FUNCTION__))
;
3524 ASTContext &C = S.getASTContext();
3525 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
3526 QualType Ty = Init->getType();
3527 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
3528 if (S.getLangOpts().CPlusPlus) {
3529 Ty = C.getLValueReferenceType(Ty);
3530 } else {
3531 Ty = C.getPointerType(Ty);
3532 ExprResult Res =
3533 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3534 if (!Res.isUsable())
3535 return nullptr;
3536 Init = Res.get();
3537 }
3538 WithInit = true;
3539 }
3540 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
3541 CaptureExpr->getBeginLoc());
3542 if (!WithInit)
3543 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
3544 S.CurContext->addHiddenDecl(CED);
3545 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
3546 return CED;
3547}
3548
3549static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3550 bool WithInit) {
3551 OMPCapturedExprDecl *CD;
3552 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
5
Calling 'Sema::isOpenMPCapturedDecl'
3553 CD = cast<OMPCapturedExprDecl>(VD);
3554 else
3555 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3556 /*AsExpression=*/false);
3557 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3558 CaptureExpr->getExprLoc());
3559}
3560
3561static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
3562 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
3563 if (!Ref) {
3564 OMPCapturedExprDecl *CD = buildCaptureDecl(
3565 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3566 /*WithInit=*/true, /*AsExpression=*/true);
3567 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3568 CaptureExpr->getExprLoc());
3569 }
3570 ExprResult Res = Ref;
3571 if (!S.getLangOpts().CPlusPlus &&
3572 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
3573 Ref->getType()->isPointerType()) {
3574 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
3575 if (!Res.isUsable())
3576 return ExprError();
3577 }
3578 return S.DefaultLvalueConversion(Res.get());
3579}
3580
3581namespace {
3582// OpenMP directives parsed in this section are represented as a
3583// CapturedStatement with an associated statement. If a syntax error
3584// is detected during the parsing of the associated statement, the
3585// compiler must abort processing and close the CapturedStatement.
3586//
3587// Combined directives such as 'target parallel' have more than one
3588// nested CapturedStatements. This RAII ensures that we unwind out
3589// of all the nested CapturedStatements when an error is found.
3590class CaptureRegionUnwinderRAII {
3591private:
3592 Sema &S;
3593 bool &ErrorFound;
3594 OpenMPDirectiveKind DKind = OMPD_unknown;
3595
3596public:
3597 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3598 OpenMPDirectiveKind DKind)
3599 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3600 ~CaptureRegionUnwinderRAII() {
3601 if (ErrorFound) {
3602 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3603 while (--ThisCaptureLevel >= 0)
3604 S.ActOnCapturedRegionError();
3605 }
3606 }
3607};
3608} // namespace
3609
3610void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3611 // Capture variables captured by reference in lambdas for target-based
3612 // directives.
3613 if (!CurContext->isDependentContext() &&
3614 (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) ||
3615 isOpenMPTargetDataManagementDirective(
3616 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))) {
3617 QualType Type = V->getType();
3618 if (const auto *RD = Type.getCanonicalType()
3619 .getNonReferenceType()
3620 ->getAsCXXRecordDecl()) {
3621 bool SavedForceCaptureByReferenceInTargetExecutable =
3622 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable();
3623 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
3624 /*V=*/true);
3625 if (RD->isLambda()) {
3626 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3627 FieldDecl *ThisCapture;
3628 RD->getCaptureFields(Captures, ThisCapture);
3629 for (const LambdaCapture &LC : RD->captures()) {
3630 if (LC.getCaptureKind() == LCK_ByRef) {
3631 VarDecl *VD = LC.getCapturedVar();
3632 DeclContext *VDC = VD->getDeclContext();
3633 if (!VDC->Encloses(CurContext))
3634 continue;
3635 MarkVariableReferenced(LC.getLocation(), VD);
3636 } else if (LC.getCaptureKind() == LCK_This) {
3637 QualType ThisTy = getCurrentThisType();
3638 if (!ThisTy.isNull() &&
3639 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3640 CheckCXXThisCapture(LC.getLocation());
3641 }
3642 }
3643 }
3644 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
3645 SavedForceCaptureByReferenceInTargetExecutable);
3646 }
3647 }
3648}
3649
3650StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3651 ArrayRef<OMPClause *> Clauses) {
3652 bool ErrorFound = false;
3653 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3654 *this, ErrorFound, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3655 if (!S.isUsable()) {
3656 ErrorFound = true;
3657 return StmtError();
3658 }
3659
3660 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3661 getOpenMPCaptureRegions(CaptureRegions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3662 OMPOrderedClause *OC = nullptr;
3663 OMPScheduleClause *SC = nullptr;
3664 SmallVector<const OMPLinearClause *, 4> LCs;
3665 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
3666 // This is required for proper codegen.
3667 for (OMPClause *Clause : Clauses) {
3668 if (isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
3669 Clause->getClauseKind() == OMPC_in_reduction) {
3670 // Capture taskgroup task_reduction descriptors inside the tasking regions
3671 // with the corresponding in_reduction items.
3672 auto *IRC = cast<OMPInReductionClause>(Clause);
3673 for (Expr *E : IRC->taskgroup_descriptors())
3674 if (E)
3675 MarkDeclarationsReferencedInExpr(E);
3676 }
3677 if (isOpenMPPrivate(Clause->getClauseKind()) ||
3678 Clause->getClauseKind() == OMPC_copyprivate ||
3679 (getLangOpts().OpenMPUseTLS &&
3680 getASTContext().getTargetInfo().isTLSSupported() &&
3681 Clause->getClauseKind() == OMPC_copyin)) {
3682 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
3683 // Mark all variables in private list clauses as used in inner region.
3684 for (Stmt *VarRef : Clause->children()) {
3685 if (auto *E = cast_or_null<Expr>(VarRef)) {
3686 MarkDeclarationsReferencedInExpr(E);
3687 }
3688 }
3689 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(/*V=*/false);
3690 } else if (CaptureRegions.size() > 1 ||
3691 CaptureRegions.back() != OMPD_unknown) {
3692 if (auto *C = OMPClauseWithPreInit::get(Clause))
3693 PICs.push_back(C);
3694 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
3695 if (Expr *E = C->getPostUpdateExpr())
3696 MarkDeclarationsReferencedInExpr(E);
3697 }
3698 }
3699 if (Clause->getClauseKind() == OMPC_schedule)
3700 SC = cast<OMPScheduleClause>(Clause);
3701 else if (Clause->getClauseKind() == OMPC_ordered)
3702 OC = cast<OMPOrderedClause>(Clause);
3703 else if (Clause->getClauseKind() == OMPC_linear)
3704 LCs.push_back(cast<OMPLinearClause>(Clause));
3705 }
3706 // OpenMP, 2.7.1 Loop Construct, Restrictions
3707 // The nonmonotonic modifier cannot be specified if an ordered clause is
3708 // specified.
3709 if (SC &&
3710 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3711 SC->getSecondScheduleModifier() ==
3712 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3713 OC) {
3714 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3715 ? SC->getFirstScheduleModifierLoc()
3716 : SC->getSecondScheduleModifierLoc(),
3717 diag::err_omp_schedule_nonmonotonic_ordered)
3718 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3719 ErrorFound = true;
3720 }
3721 if (!LCs.empty() && OC && OC->getNumForLoops()) {
3722 for (const OMPLinearClause *C : LCs) {
3723 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
3724 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3725 }
3726 ErrorFound = true;
3727 }
3728 if (isOpenMPWorksharingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
3729 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) && OC &&
3730 OC->getNumForLoops()) {
3731 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
3732 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3733 ErrorFound = true;
3734 }
3735 if (ErrorFound) {
3736 return StmtError();
3737 }
3738 StmtResult SR = S;
3739 unsigned CompletedRegions = 0;
3740 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
3741 // Mark all variables in private list clauses as used in inner region.
3742 // Required for proper codegen of combined directives.
3743 // TODO: add processing for other clauses.
3744 if (ThisCaptureRegion != OMPD_unknown) {
3745 for (const clang::OMPClauseWithPreInit *C : PICs) {
3746 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3747 // Find the particular capture region for the clause if the
3748 // directive is a combined one with multiple capture regions.
3749 // If the directive is not a combined one, the capture region
3750 // associated with the clause is OMPD_unknown and is generated
3751 // only once.
3752 if (CaptureRegion == ThisCaptureRegion ||
3753 CaptureRegion == OMPD_unknown) {
3754 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
3755 for (Decl *D : DS->decls())
3756 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3757 }
3758 }
3759 }
3760 }
3761 if (++CompletedRegions == CaptureRegions.size())
3762 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setBodyComplete();
3763 SR = ActOnCapturedRegionEnd(SR.get());
3764 }
3765 return SR;
3766}
3767
3768static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3769 OpenMPDirectiveKind CancelRegion,
3770 SourceLocation StartLoc) {
3771 // CancelRegion is only needed for cancel and cancellation_point.
3772 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3773 return false;
3774
3775 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3776 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3777 return false;
3778
3779 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3780 << getOpenMPDirectiveName(CancelRegion);
3781 return true;
3782}
3783
3784static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3785 OpenMPDirectiveKind CurrentRegion,
3786 const DeclarationNameInfo &CurrentName,
3787 OpenMPDirectiveKind CancelRegion,
3788 SourceLocation StartLoc) {
3789 if (Stack->getCurScope()) {
3790 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3791 OpenMPDirectiveKind OffendingRegion = ParentRegion;
3792 bool NestingProhibited = false;
3793 bool CloseNesting = true;
3794 bool OrphanSeen = false;
3795 enum {
3796 NoRecommend,
3797 ShouldBeInParallelRegion,
3798 ShouldBeInOrderedRegion,
3799 ShouldBeInTargetRegion,
3800 ShouldBeInTeamsRegion
3801 } Recommend = NoRecommend;
3802 if (isOpenMPSimdDirective(ParentRegion) &&
3803 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
3804 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
3805 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
3806 // OpenMP [2.16, Nesting of Regions]
3807 // OpenMP constructs may not be nested inside a simd region.
3808 // OpenMP [2.8.1,simd Construct, Restrictions]
3809 // An ordered construct with the simd clause is the only OpenMP
3810 // construct that can appear in the simd region.
3811 // Allowing a SIMD construct nested in another SIMD construct is an
3812 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3813 // message.
3814 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
3815 // The only OpenMP constructs that can be encountered during execution of
3816 // a simd region are the atomic construct, the loop construct, the simd
3817 // construct and the ordered construct with the simd clause.
3818 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3819 ? diag::err_omp_prohibited_region_simd
3820 : diag::warn_omp_nesting_simd)
3821 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
3822 return CurrentRegion != OMPD_simd;
3823 }
3824 if (ParentRegion == OMPD_atomic) {
3825 // OpenMP [2.16, Nesting of Regions]
3826 // OpenMP constructs may not be nested inside an atomic region.
3827 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3828 return true;
3829 }
3830 if (CurrentRegion == OMPD_section) {
3831 // OpenMP [2.7.2, sections Construct, Restrictions]
3832 // Orphaned section directives are prohibited. That is, the section
3833 // directives must appear within the sections construct and must not be
3834 // encountered elsewhere in the sections region.
3835 if (ParentRegion != OMPD_sections &&
3836 ParentRegion != OMPD_parallel_sections) {
3837 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3838 << (ParentRegion != OMPD_unknown)
3839 << getOpenMPDirectiveName(ParentRegion);
3840 return true;
3841 }
3842 return false;
3843 }
3844 // Allow some constructs (except teams and cancellation constructs) to be
3845 // orphaned (they could be used in functions, called from OpenMP regions
3846 // with the required preconditions).
3847 if (ParentRegion == OMPD_unknown &&
3848 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3849 CurrentRegion != OMPD_cancellation_point &&
3850 CurrentRegion != OMPD_cancel)
3851 return false;
3852 if (CurrentRegion == OMPD_cancellation_point ||
3853 CurrentRegion == OMPD_cancel) {
3854 // OpenMP [2.16, Nesting of Regions]
3855 // A cancellation point construct for which construct-type-clause is
3856 // taskgroup must be nested inside a task construct. A cancellation
3857 // point construct for which construct-type-clause is not taskgroup must
3858 // be closely nested inside an OpenMP construct that matches the type
3859 // specified in construct-type-clause.
3860 // A cancel construct for which construct-type-clause is taskgroup must be
3861 // nested inside a task construct. A cancel construct for which
3862 // construct-type-clause is not taskgroup must be closely nested inside an
3863 // OpenMP construct that matches the type specified in
3864 // construct-type-clause.
3865 NestingProhibited =
3866 !((CancelRegion == OMPD_parallel &&
3867 (ParentRegion == OMPD_parallel ||
3868 ParentRegion == OMPD_target_parallel)) ||
3869 (CancelRegion == OMPD_for &&
3870 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3871 ParentRegion == OMPD_target_parallel_for ||
3872 ParentRegion == OMPD_distribute_parallel_for ||
3873 ParentRegion == OMPD_teams_distribute_parallel_for ||
3874 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3875 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3876 (CancelRegion == OMPD_sections &&
3877 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3878 ParentRegion == OMPD_parallel_sections)));
3879 OrphanSeen = ParentRegion == OMPD_unknown;
3880 } else if (CurrentRegion == OMPD_master) {
3881 // OpenMP [2.16, Nesting of Regions]
3882 // A master region may not be closely nested inside a worksharing,
3883 // atomic, or explicit task region.
3884 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3885 isOpenMPTaskingDirective(ParentRegion);
3886 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3887 // OpenMP [2.16, Nesting of Regions]
3888 // A critical region may not be nested (closely or otherwise) inside a
3889 // critical region with the same name. Note that this restriction is not
3890 // sufficient to prevent deadlock.
3891 SourceLocation PreviousCriticalLoc;
3892 bool DeadLock = Stack->hasDirective(
3893 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3894 const DeclarationNameInfo &DNI,
3895 SourceLocation Loc) {
3896 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3897 PreviousCriticalLoc = Loc;
3898 return true;
3899 }
3900 return false;
3901 },
3902 false /* skip top directive */);
3903 if (DeadLock) {
3904 SemaRef.Diag(StartLoc,
3905 diag::err_omp_prohibited_region_critical_same_name)
3906 << CurrentName.getName();
3907 if (PreviousCriticalLoc.isValid())
3908 SemaRef.Diag(PreviousCriticalLoc,
3909 diag::note_omp_previous_critical_region);
3910 return true;
3911 }
3912 } else if (CurrentRegion == OMPD_barrier) {
3913 // OpenMP [2.16, Nesting of Regions]
3914 // A barrier region may not be closely nested inside a worksharing,
3915 // explicit task, critical, ordered, atomic, or master region.
3916 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3917 isOpenMPTaskingDirective(ParentRegion) ||
3918 ParentRegion == OMPD_master ||
3919 ParentRegion == OMPD_critical ||
3920 ParentRegion == OMPD_ordered;
3921 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3922 !isOpenMPParallelDirective(CurrentRegion) &&
3923 !isOpenMPTeamsDirective(CurrentRegion)) {
3924 // OpenMP [2.16, Nesting of Regions]
3925 // A worksharing region may not be closely nested inside a worksharing,
3926 // explicit task, critical, ordered, atomic, or master region.
3927 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3928 isOpenMPTaskingDirective(ParentRegion) ||
3929 ParentRegion == OMPD_master ||
3930 ParentRegion == OMPD_critical ||
3931 ParentRegion == OMPD_ordered;
3932 Recommend = ShouldBeInParallelRegion;
3933 } else if (CurrentRegion == OMPD_ordered) {
3934 // OpenMP [2.16, Nesting of Regions]
3935 // An ordered region may not be closely nested inside a critical,
3936 // atomic, or explicit task region.
3937 // An ordered region must be closely nested inside a loop region (or
3938 // parallel loop region) with an ordered clause.
3939 // OpenMP [2.8.1,simd Construct, Restrictions]
3940 // An ordered construct with the simd clause is the only OpenMP construct
3941 // that can appear in the simd region.
3942 NestingProhibited = ParentRegion == OMPD_critical ||
3943 isOpenMPTaskingDirective(ParentRegion) ||
3944 !(isOpenMPSimdDirective(ParentRegion) ||
3945 Stack->isParentOrderedRegion());
3946 Recommend = ShouldBeInOrderedRegion;
3947 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3948 // OpenMP [2.16, Nesting of Regions]
3949 // If specified, a teams construct must be contained within a target
3950 // construct.
3951 NestingProhibited =
3952 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3953 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3954 ParentRegion != OMPD_target);
3955 OrphanSeen = ParentRegion == OMPD_unknown;
3956 Recommend = ShouldBeInTargetRegion;
3957 }
3958 if (!NestingProhibited &&
3959 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3960 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3961 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3962 // OpenMP [2.16, Nesting of Regions]
3963 // distribute, parallel, parallel sections, parallel workshare, and the
3964 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3965 // constructs that can be closely nested in the teams region.
3966 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3967 !isOpenMPDistributeDirective(CurrentRegion);
3968 Recommend = ShouldBeInParallelRegion;
3969 }
3970 if (!NestingProhibited &&
3971 isOpenMPNestingDistributeDirective(CurrentRegion)) {
3972 // OpenMP 4.5 [2.17 Nesting of Regions]
3973 // The region associated with the distribute construct must be strictly
3974 // nested inside a teams region
3975 NestingProhibited =
3976 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3977 Recommend = ShouldBeInTeamsRegion;
3978 }
3979 if (!NestingProhibited &&
3980 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3981 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3982 // OpenMP 4.5 [2.17 Nesting of Regions]
3983 // If a target, target update, target data, target enter data, or
3984 // target exit data construct is encountered during execution of a
3985 // target region, the behavior is unspecified.
3986 NestingProhibited = Stack->hasDirective(
3987 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3988 SourceLocation) {
3989 if (isOpenMPTargetExecutionDirective(K)) {
3990 OffendingRegion = K;
3991 return true;
3992 }
3993 return false;
3994 },
3995 false /* don't skip top directive */);
3996 CloseNesting = false;
3997 }
3998 if (NestingProhibited) {
3999 if (OrphanSeen) {
4000 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4001 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4002 } else {
4003 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4004 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4005 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4006 }
4007 return true;
4008 }
4009 }
4010 return false;
4011}
4012
4013static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4014 ArrayRef<OMPClause *> Clauses,
4015 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4016 bool ErrorFound = false;
4017 unsigned NamedModifiersNumber = 0;
4018 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
4019 OMPD_unknown + 1);
4020 SmallVector<SourceLocation, 4> NameModifierLoc;
4021 for (const OMPClause *C : Clauses) {
4022 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4023 // At most one if clause without a directive-name-modifier can appear on
4024 // the directive.
4025 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4026 if (FoundNameModifiers[CurNM]) {
4027 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4028 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4029 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4030 ErrorFound = true;
4031 } else if (CurNM != OMPD_unknown) {
4032 NameModifierLoc.push_back(IC->getNameModifierLoc());
4033 ++NamedModifiersNumber;
4034 }
4035 FoundNameModifiers[CurNM] = IC;
4036 if (CurNM == OMPD_unknown)
4037 continue;
4038 // Check if the specified name modifier is allowed for the current
4039 // directive.
4040 // At most one if clause with the particular directive-name-modifier can
4041 // appear on the directive.
4042 bool MatchFound = false;
4043 for (auto NM : AllowedNameModifiers) {
4044 if (CurNM == NM) {
4045 MatchFound = true;
4046 break;
4047 }
4048 }
4049 if (!MatchFound) {
4050 S.Diag(IC->getNameModifierLoc(),
4051 diag::err_omp_wrong_if_directive_name_modifier)
4052 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4053 ErrorFound = true;
4054 }
4055 }
4056 }
4057 // If any if clause on the directive includes a directive-name-modifier then
4058 // all if clauses on the directive must include a directive-name-modifier.
4059 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4060 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4061 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4062 diag::err_omp_no_more_if_clause);
4063 } else {
4064 std::string Values;
4065 std::string Sep(", ");
4066 unsigned AllowedCnt = 0;
4067 unsigned TotalAllowedNum =
4068 AllowedNameModifiers.size() - NamedModifiersNumber;
4069 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4070 ++Cnt) {
4071 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4072 if (!FoundNameModifiers[NM]) {
4073 Values += "'";
4074 Values += getOpenMPDirectiveName(NM);
4075 Values += "'";
4076 if (AllowedCnt + 2 == TotalAllowedNum)
4077 Values += " or ";
4078 else if (AllowedCnt + 1 != TotalAllowedNum)
4079 Values += Sep;
4080 ++AllowedCnt;
4081 }
4082 }
4083 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4084 diag::err_omp_unnamed_if_clause)
4085 << (TotalAllowedNum > 1) << Values;
4086 }
4087 for (SourceLocation Loc : NameModifierLoc) {
4088 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4089 }
4090 ErrorFound = true;
4091 }
4092 return ErrorFound;
4093}
4094
4095static std::pair<ValueDecl *, bool>
4096getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4097 SourceRange &ERange, bool AllowArraySection = false) {
4098 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4099 RefExpr->containsUnexpandedParameterPack())
4100 return std::make_pair(nullptr, true);
4101
4102 // OpenMP [3.1, C/C++]
4103 // A list item is a variable name.
4104 // OpenMP [2.9.3.3, Restrictions, p.1]
4105 // A variable that is part of another variable (as an array or
4106 // structure element) cannot appear in a private clause.
4107 RefExpr = RefExpr->IgnoreParens();
4108 enum {
4109 NoArrayExpr = -1,
4110 ArraySubscript = 0,
4111 OMPArraySection = 1
4112 } IsArrayExpr = NoArrayExpr;
4113 if (AllowArraySection) {
4114 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4115 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4116 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4117 Base = TempASE->getBase()->IgnoreParenImpCasts();
4118 RefExpr = Base;
4119 IsArrayExpr = ArraySubscript;
4120 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4121 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4122 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4123 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4124 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4125 Base = TempASE->getBase()->IgnoreParenImpCasts();
4126 RefExpr = Base;
4127 IsArrayExpr = OMPArraySection;
4128 }
4129 }
4130 ELoc = RefExpr->getExprLoc();
4131 ERange = RefExpr->getSourceRange();
4132 RefExpr = RefExpr->IgnoreParenImpCasts();
4133 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4134 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4135 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4136 (S.getCurrentThisType().isNull() || !ME ||
4137 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4138 !isa<FieldDecl>(ME->getMemberDecl()))) {
4139 if (IsArrayExpr != NoArrayExpr) {
4140 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4141 << ERange;
4142 } else {
4143 S.Diag(ELoc,
4144 AllowArraySection
4145 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4146 : diag::err_omp_expected_var_name_member_expr)
4147 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4148 }
4149 return std::make_pair(nullptr, false);
4150 }
4151 return std::make_pair(
4152 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4153}
4154
4155static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
4156 ArrayRef<OMPClause *> Clauses) {
4157 assert(!S.CurContext->isDependentContext() &&((!S.CurContext->isDependentContext() && "Expected non-dependent context."
) ? static_cast<void> (0) : __assert_fail ("!S.CurContext->isDependentContext() && \"Expected non-dependent context.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4158, __PRETTY_FUNCTION__))
4158 "Expected non-dependent context.")((!S.CurContext->isDependentContext() && "Expected non-dependent context."
) ? static_cast<void> (0) : __assert_fail ("!S.CurContext->isDependentContext() && \"Expected non-dependent context.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4158, __PRETTY_FUNCTION__))
;
4159 auto AllocateRange =
4160 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
4161 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4162 DeclToCopy;
4163 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4164 return isOpenMPPrivate(C->getClauseKind());
4165 });
4166 for (OMPClause *Cl : PrivateRange) {
4167 MutableArrayRef<Expr *>::iterator I, It, Et;
4168 if (Cl->getClauseKind() == OMPC_private) {
4169 auto *PC = cast<OMPPrivateClause>(Cl);
4170 I = PC->private_copies().begin();
4171 It = PC->varlist_begin();
4172 Et = PC->varlist_end();
4173 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4174 auto *PC = cast<OMPFirstprivateClause>(Cl);
4175 I = PC->private_copies().begin();
4176 It = PC->varlist_begin();
4177 Et = PC->varlist_end();
4178 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4179 auto *PC = cast<OMPLastprivateClause>(Cl);
4180 I = PC->private_copies().begin();
4181 It = PC->varlist_begin();
4182 Et = PC->varlist_end();
4183 } else if (Cl->getClauseKind() == OMPC_linear) {
4184 auto *PC = cast<OMPLinearClause>(Cl);
4185 I = PC->privates().begin();
4186 It = PC->varlist_begin();
4187 Et = PC->varlist_end();
4188 } else if (Cl->getClauseKind() == OMPC_reduction) {
4189 auto *PC = cast<OMPReductionClause>(Cl);
4190 I = PC->privates().begin();
4191 It = PC->varlist_begin();
4192 Et = PC->varlist_end();
4193 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4194 auto *PC = cast<OMPTaskReductionClause>(Cl);
4195 I = PC->privates().begin();
4196 It = PC->varlist_begin();
4197 Et = PC->varlist_end();
4198 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4199 auto *PC = cast<OMPInReductionClause>(Cl);
4200 I = PC->privates().begin();
4201 It = PC->varlist_begin();
4202 Et = PC->varlist_end();
4203 } else {
4204 llvm_unreachable("Expected private clause.")::llvm::llvm_unreachable_internal("Expected private clause.",
"/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4204)
;
4205 }
4206 for (Expr *E : llvm::make_range(It, Et)) {
4207 if (!*I) {
4208 ++I;
4209 continue;
4210 }
4211 SourceLocation ELoc;
4212 SourceRange ERange;
4213 Expr *SimpleRefExpr = E;
4214 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4215 /*AllowArraySection=*/true);
4216 DeclToCopy.try_emplace(Res.first,
4217 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4218 ++I;
4219 }
4220 }
4221 for (OMPClause *C : AllocateRange) {
4222 auto *AC = cast<OMPAllocateClause>(C);
4223 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4224 getAllocatorKind(S, Stack, AC->getAllocator());
4225 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4226 // For task, taskloop or target directives, allocation requests to memory
4227 // allocators with the trait access set to thread result in unspecified
4228 // behavior.
4229 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4230 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4231 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4232 S.Diag(AC->getAllocator()->getExprLoc(),
4233 diag::warn_omp_allocate_thread_on_task_target_directive)
4234 << getOpenMPDirectiveName(Stack->getCurrentDirective());
4235 }
4236 for (Expr *E : AC->varlists()) {
4237 SourceLocation ELoc;
4238 SourceRange ERange;
4239 Expr *SimpleRefExpr = E;
4240 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4241 ValueDecl *VD = Res.first;
4242 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4243 if (!isOpenMPPrivate(Data.CKind)) {
4244 S.Diag(E->getExprLoc(),
4245 diag::err_omp_expected_private_copy_for_allocate);
4246 continue;
4247 }
4248 VarDecl *PrivateVD = DeclToCopy[VD];
4249 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4250 AllocatorKind, AC->getAllocator()))
4251 continue;
4252 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4253 E->getSourceRange());
4254 }
4255 }
4256}
4257
4258StmtResult Sema::ActOnOpenMPExecutableDirective(
4259 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4260 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4261 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4262 StmtResult Res = StmtError();
4263 // First check CancelRegion which is then used in checkNestingOfRegions.
4264 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4265 checkNestingOfRegions(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Kind, DirName, CancelRegion,
4266 StartLoc))
4267 return StmtError();
4268
4269 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
4270 VarsWithInheritedDSAType VarsWithInheritedDSA;
4271 bool ErrorFound = false;
4272 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
4273 if (AStmt && !CurContext->isDependentContext()) {
4274 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4274, __PRETTY_FUNCTION__))
;
4275
4276 // Check default data sharing attributes for referenced variables.
4277 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, cast<CapturedStmt>(AStmt));
4278 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4279 Stmt *S = AStmt;
4280 while (--ThisCaptureLevel >= 0)
4281 S = cast<CapturedStmt>(S)->getCapturedStmt();
4282 DSAChecker.Visit(S);
4283 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4284 !isOpenMPTaskingDirective(Kind)) {
4285 // Visit subcaptures to generate implicit clauses for captured vars.
4286 auto *CS = cast<CapturedStmt>(AStmt);
4287 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4288 getOpenMPCaptureRegions(CaptureRegions, Kind);
4289 // Ignore outer tasking regions for target directives.
4290 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4291 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4292 DSAChecker.visitSubCaptures(CS);
4293 }
4294 if (DSAChecker.isErrorFound())
4295 return StmtError();
4296 // Generate list of implicitly defined firstprivate variables.
4297 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
4298
4299 SmallVector<Expr *, 4> ImplicitFirstprivates(
4300 DSAChecker.getImplicitFirstprivate().begin(),
4301 DSAChecker.getImplicitFirstprivate().end());
4302 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4303 DSAChecker.getImplicitMap().end());
4304 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
4305 for (OMPClause *C : Clauses) {
4306 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
4307 for (Expr *E : IRC->taskgroup_descriptors())
4308 if (E)
4309 ImplicitFirstprivates.emplace_back(E);
4310 }
4311 }
4312 if (!ImplicitFirstprivates.empty()) {
4313 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
4314 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4315 SourceLocation())) {
4316 ClausesWithImplicit.push_back(Implicit);
4317 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
4318 ImplicitFirstprivates.size();
4319 } else {
4320 ErrorFound = true;
4321 }
4322 }
4323 if (!ImplicitMaps.empty()) {
4324 CXXScopeSpec MapperIdScopeSpec;
4325 DeclarationNameInfo MapperId;
4326 if (OMPClause *Implicit = ActOnOpenMPMapClause(
4327 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4328 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4329 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
4330 ClausesWithImplicit.emplace_back(Implicit);
4331 ErrorFound |=
4332 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
4333 } else {
4334 ErrorFound = true;
4335 }
4336 }
4337 }
4338
4339 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
4340 switch (Kind) {
4341 case OMPD_parallel:
4342 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4343 EndLoc);
4344 AllowedNameModifiers.push_back(OMPD_parallel);
4345 break;
4346 case OMPD_simd:
4347 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4348 VarsWithInheritedDSA);
4349 break;
4350 case OMPD_for:
4351 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4352 VarsWithInheritedDSA);
4353 break;
4354 case OMPD_for_simd:
4355 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4356 EndLoc, VarsWithInheritedDSA);
4357 break;
4358 case OMPD_sections:
4359 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4360 EndLoc);
4361 break;
4362 case OMPD_section:
4363 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp section' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4364, __PRETTY_FUNCTION__))
4364 "No clauses are allowed for 'omp section' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp section' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4364, __PRETTY_FUNCTION__))
;
4365 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4366 break;
4367 case OMPD_single:
4368 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4369 EndLoc);
4370 break;
4371 case OMPD_master:
4372 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp master' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4373, __PRETTY_FUNCTION__))
4373 "No clauses are allowed for 'omp master' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp master' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4373, __PRETTY_FUNCTION__))
;
4374 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4375 break;
4376 case OMPD_critical:
4377 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4378 StartLoc, EndLoc);
4379 break;
4380 case OMPD_parallel_for:
4381 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4382 EndLoc, VarsWithInheritedDSA);
4383 AllowedNameModifiers.push_back(OMPD_parallel);
4384 break;
4385 case OMPD_parallel_for_simd:
4386 Res = ActOnOpenMPParallelForSimdDirective(
4387 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4388 AllowedNameModifiers.push_back(OMPD_parallel);
4389 break;
4390 case OMPD_parallel_sections:
4391 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4392 StartLoc, EndLoc);
4393 AllowedNameModifiers.push_back(OMPD_parallel);
4394 break;
4395 case OMPD_task:
4396 Res =
4397 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4398 AllowedNameModifiers.push_back(OMPD_task);
4399 break;
4400 case OMPD_taskyield:
4401 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4402, __PRETTY_FUNCTION__))
4402 "No clauses are allowed for 'omp taskyield' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4402, __PRETTY_FUNCTION__))
;
4403 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4404, __PRETTY_FUNCTION__))
4404 "No associated statement allowed for 'omp taskyield' directive")((AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4404, __PRETTY_FUNCTION__))
;
4405 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4406 break;
4407 case OMPD_barrier:
4408 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4409, __PRETTY_FUNCTION__))
4409 "No clauses are allowed for 'omp barrier' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4409, __PRETTY_FUNCTION__))
;
4410 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4411, __PRETTY_FUNCTION__))
4411 "No associated statement allowed for 'omp barrier' directive")((AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4411, __PRETTY_FUNCTION__))
;
4412 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4413 break;
4414 case OMPD_taskwait:
4415 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4416, __PRETTY_FUNCTION__))
4416 "No clauses are allowed for 'omp taskwait' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4416, __PRETTY_FUNCTION__))
;
4417 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4418, __PRETTY_FUNCTION__))
4418 "No associated statement allowed for 'omp taskwait' directive")((AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4418, __PRETTY_FUNCTION__))
;
4419 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4420 break;
4421 case OMPD_taskgroup:
4422 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4423 EndLoc);
4424 break;
4425 case OMPD_flush:
4426 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp flush' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4427, __PRETTY_FUNCTION__))
4427 "No associated statement allowed for 'omp flush' directive")((AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp flush' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4427, __PRETTY_FUNCTION__))
;
4428 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4429 break;
4430 case OMPD_ordered:
4431 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4432 EndLoc);
4433 break;
4434 case OMPD_atomic:
4435 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4436 EndLoc);
4437 break;
4438 case OMPD_teams:
4439 Res =
4440 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4441 break;
4442 case OMPD_target:
4443 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4444 EndLoc);
4445 AllowedNameModifiers.push_back(OMPD_target);
4446 break;
4447 case OMPD_target_parallel:
4448 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4449 StartLoc, EndLoc);
4450 AllowedNameModifiers.push_back(OMPD_target);
4451 AllowedNameModifiers.push_back(OMPD_parallel);
4452 break;
4453 case OMPD_target_parallel_for:
4454 Res = ActOnOpenMPTargetParallelForDirective(
4455 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4456 AllowedNameModifiers.push_back(OMPD_target);
4457 AllowedNameModifiers.push_back(OMPD_parallel);
4458 break;
4459 case OMPD_cancellation_point:
4460 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4461, __PRETTY_FUNCTION__))
4461 "No clauses are allowed for 'omp cancellation point' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4461, __PRETTY_FUNCTION__))
;
4462 assert(AStmt == nullptr && "No associated statement allowed for 'omp "((AStmt == nullptr && "No associated statement allowed for 'omp "
"cancellation point' directive") ? static_cast<void> (
0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp \" \"cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4463, __PRETTY_FUNCTION__))
4463 "cancellation point' directive")((AStmt == nullptr && "No associated statement allowed for 'omp "
"cancellation point' directive") ? static_cast<void> (
0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp \" \"cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4463, __PRETTY_FUNCTION__))
;
4464 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4465 break;
4466 case OMPD_cancel:
4467 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp cancel' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4468, __PRETTY_FUNCTION__))
4468 "No associated statement allowed for 'omp cancel' directive")((AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp cancel' directive\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4468, __PRETTY_FUNCTION__))
;
4469 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4470 CancelRegion);
4471 AllowedNameModifiers.push_back(OMPD_cancel);
4472 break;
4473 case OMPD_target_data:
4474 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4475 EndLoc);
4476 AllowedNameModifiers.push_back(OMPD_target_data);
4477 break;
4478 case OMPD_target_enter_data:
4479 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
4480 EndLoc, AStmt);
4481 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4482 break;
4483 case OMPD_target_exit_data:
4484 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
4485 EndLoc, AStmt);
4486 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4487 break;
4488 case OMPD_taskloop:
4489 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4490 EndLoc, VarsWithInheritedDSA);
4491 AllowedNameModifiers.push_back(OMPD_taskloop);
4492 break;
4493 case OMPD_taskloop_simd:
4494 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4495 EndLoc, VarsWithInheritedDSA);
4496 AllowedNameModifiers.push_back(OMPD_taskloop);
4497 break;
4498 case OMPD_master_taskloop:
4499 Res = ActOnOpenMPMasterTaskLoopDirective(
4500 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4501 AllowedNameModifiers.push_back(OMPD_taskloop);
4502 break;
4503 case OMPD_master_taskloop_simd:
4504 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4505 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4506 AllowedNameModifiers.push_back(OMPD_taskloop);
4507 break;
4508 case OMPD_parallel_master_taskloop:
4509 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4510 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4511 AllowedNameModifiers.push_back(OMPD_taskloop);
4512 AllowedNameModifiers.push_back(OMPD_parallel);
4513 break;
4514 case OMPD_parallel_master_taskloop_simd:
4515 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4516 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4517 AllowedNameModifiers.push_back(OMPD_taskloop);
4518 AllowedNameModifiers.push_back(OMPD_parallel);
4519 break;
4520 case OMPD_distribute:
4521 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4522 EndLoc, VarsWithInheritedDSA);
4523 break;
4524 case OMPD_target_update:
4525 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4526 EndLoc, AStmt);
4527 AllowedNameModifiers.push_back(OMPD_target_update);
4528 break;
4529 case OMPD_distribute_parallel_for:
4530 Res = ActOnOpenMPDistributeParallelForDirective(
4531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4532 AllowedNameModifiers.push_back(OMPD_parallel);
4533 break;
4534 case OMPD_distribute_parallel_for_simd:
4535 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4536 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4537 AllowedNameModifiers.push_back(OMPD_parallel);
4538 break;
4539 case OMPD_distribute_simd:
4540 Res = ActOnOpenMPDistributeSimdDirective(
4541 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4542 break;
4543 case OMPD_target_parallel_for_simd:
4544 Res = ActOnOpenMPTargetParallelForSimdDirective(
4545 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4546 AllowedNameModifiers.push_back(OMPD_target);
4547 AllowedNameModifiers.push_back(OMPD_parallel);
4548 break;
4549 case OMPD_target_simd:
4550 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4551 EndLoc, VarsWithInheritedDSA);
4552 AllowedNameModifiers.push_back(OMPD_target);
4553 break;
4554 case OMPD_teams_distribute:
4555 Res = ActOnOpenMPTeamsDistributeDirective(
4556 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4557 break;
4558 case OMPD_teams_distribute_simd:
4559 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4560 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4561 break;
4562 case OMPD_teams_distribute_parallel_for_simd:
4563 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4564 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4565 AllowedNameModifiers.push_back(OMPD_parallel);
4566 break;
4567 case OMPD_teams_distribute_parallel_for:
4568 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4569 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4570 AllowedNameModifiers.push_back(OMPD_parallel);
4571 break;
4572 case OMPD_target_teams:
4573 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4574 EndLoc);
4575 AllowedNameModifiers.push_back(OMPD_target);
4576 break;
4577 case OMPD_target_teams_distribute:
4578 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4579 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4580 AllowedNameModifiers.push_back(OMPD_target);
4581 break;
4582 case OMPD_target_teams_distribute_parallel_for:
4583 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4584 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4585 AllowedNameModifiers.push_back(OMPD_target);
4586 AllowedNameModifiers.push_back(OMPD_parallel);
4587 break;
4588 case OMPD_target_teams_distribute_parallel_for_simd:
4589 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4590 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4591 AllowedNameModifiers.push_back(OMPD_target);
4592 AllowedNameModifiers.push_back(OMPD_parallel);
4593 break;
4594 case OMPD_target_teams_distribute_simd:
4595 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4596 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4597 AllowedNameModifiers.push_back(OMPD_target);
4598 break;
4599 case OMPD_declare_target:
4600 case OMPD_end_declare_target:
4601 case OMPD_threadprivate:
4602 case OMPD_allocate:
4603 case OMPD_declare_reduction:
4604 case OMPD_declare_mapper:
4605 case OMPD_declare_simd:
4606 case OMPD_requires:
4607 case OMPD_declare_variant:
4608 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4608)
;
4609 case OMPD_unknown:
4610 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4610)
;
4611 }
4612
4613 ErrorFound = Res.isInvalid() || ErrorFound;
4614
4615 // Check variables in the clauses if default(none) was specified.
4616 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none) {
4617 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, nullptr);
4618 for (OMPClause *C : Clauses) {
4619 switch (C->getClauseKind()) {
4620 case OMPC_num_threads:
4621 case OMPC_dist_schedule:
4622 // Do not analyse if no parent teams directive.
4623 if (isOpenMPTeamsDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
4624 break;
4625 continue;
4626 case OMPC_if:
4627 if (isOpenMPTeamsDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
4628 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4629 break;
4630 continue;
4631 case OMPC_schedule:
4632 break;
4633 case OMPC_grainsize:
4634 case OMPC_num_tasks:
4635 case OMPC_final:
4636 case OMPC_priority:
4637 // Do not analyze if no parent parallel directive.
4638 if (isOpenMPParallelDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
4639 break;
4640 continue;
4641 case OMPC_ordered:
4642 case OMPC_device:
4643 case OMPC_num_teams:
4644 case OMPC_thread_limit:
4645 case OMPC_hint:
4646 case OMPC_collapse:
4647 case OMPC_safelen:
4648 case OMPC_simdlen:
4649 case OMPC_default:
4650 case OMPC_proc_bind:
4651 case OMPC_private:
4652 case OMPC_firstprivate:
4653 case OMPC_lastprivate:
4654 case OMPC_shared:
4655 case OMPC_reduction:
4656 case OMPC_task_reduction:
4657 case OMPC_in_reduction:
4658 case OMPC_linear:
4659 case OMPC_aligned:
4660 case OMPC_copyin:
4661 case OMPC_copyprivate:
4662 case OMPC_nowait:
4663 case OMPC_untied:
4664 case OMPC_mergeable:
4665 case OMPC_allocate:
4666 case OMPC_read:
4667 case OMPC_write:
4668 case OMPC_update:
4669 case OMPC_capture:
4670 case OMPC_seq_cst:
4671 case OMPC_depend:
4672 case OMPC_threads:
4673 case OMPC_simd:
4674 case OMPC_map:
4675 case OMPC_nogroup:
4676 case OMPC_defaultmap:
4677 case OMPC_to:
4678 case OMPC_from:
4679 case OMPC_use_device_ptr:
4680 case OMPC_is_device_ptr:
4681 continue;
4682 case OMPC_allocator:
4683 case OMPC_flush:
4684 case OMPC_threadprivate:
4685 case OMPC_uniform:
4686 case OMPC_unknown:
4687 case OMPC_unified_address:
4688 case OMPC_unified_shared_memory:
4689 case OMPC_reverse_offload:
4690 case OMPC_dynamic_allocators:
4691 case OMPC_atomic_default_mem_order:
4692 case OMPC_device_type:
4693 case OMPC_match:
4694 llvm_unreachable("Unexpected clause")::llvm::llvm_unreachable_internal("Unexpected clause", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4694)
;
4695 }
4696 for (Stmt *CC : C->children()) {
4697 if (CC)
4698 DSAChecker.Visit(CC);
4699 }
4700 }
4701 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4702 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4703 }
4704 for (const auto &P : VarsWithInheritedDSA) {
4705 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4706 continue;
4707 ErrorFound = true;
4708 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4709 << P.first << P.second->getSourceRange();
4710 Diag(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4711 }
4712
4713 if (!AllowedNameModifiers.empty())
4714 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4715 ErrorFound;
4716
4717 if (ErrorFound)
4718 return StmtError();
4719
4720 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4721 Res.getAs<OMPExecutableDirective>()
4722 ->getStructuredBlock()
4723 ->setIsOMPStructuredBlock(true);
4724 }
4725
4726 if (!CurContext->isDependentContext() &&
4727 isOpenMPTargetExecutionDirective(Kind) &&
4728 !(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4729 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4730 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4731 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4732 // Register target to DSA Stack.
4733 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addTargetDirLocation(StartLoc);
4734 }
4735
4736 return Res;
4737}
4738
4739Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4740 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
4741 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
4742 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4743 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
4744 assert(Aligneds.size() == Alignments.size())((Aligneds.size() == Alignments.size()) ? static_cast<void
> (0) : __assert_fail ("Aligneds.size() == Alignments.size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4744, __PRETTY_FUNCTION__))
;
4745 assert(Linears.size() == LinModifiers.size())((Linears.size() == LinModifiers.size()) ? static_cast<void
> (0) : __assert_fail ("Linears.size() == LinModifiers.size()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4745, __PRETTY_FUNCTION__))
;
4746 assert(Linears.size() == Steps.size())((Linears.size() == Steps.size()) ? static_cast<void> (
0) : __assert_fail ("Linears.size() == Steps.size()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 4746, __PRETTY_FUNCTION__))
;
4747 if (!DG || DG.get().isNull())
4748 return DeclGroupPtrTy();
4749
4750 const int SimdId = 0;
4751 if (!DG.get().isSingleDecl()) {
4752 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4753 << SimdId;
4754 return DG;
4755 }
4756 Decl *ADecl = DG.get().getSingleDecl();
4757 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4758 ADecl = FTD->getTemplatedDecl();
4759
4760 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4761 if (!FD) {
4762 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
4763 return DeclGroupPtrTy();
4764 }
4765
4766 // OpenMP [2.8.2, declare simd construct, Description]
4767 // The parameter of the simdlen clause must be a constant positive integer
4768 // expression.
4769 ExprResult SL;
4770 if (Simdlen)
4771 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
4772 // OpenMP [2.8.2, declare simd construct, Description]
4773 // The special this pointer can be used as if was one of the arguments to the
4774 // function in any of the linear, aligned, or uniform clauses.
4775 // The uniform clause declares one or more arguments to have an invariant
4776 // value for all concurrent invocations of the function in the execution of a
4777 // single SIMD loop.
4778 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4779 const Expr *UniformedLinearThis = nullptr;
4780 for (const Expr *E : Uniforms) {
4781 E = E->IgnoreParenImpCasts();
4782 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4783 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4784 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4785 FD->getParamDecl(PVD->getFunctionScopeIndex())
4786 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
4787 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
4788 continue;
4789 }
4790 if (isa<CXXThisExpr>(E)) {
4791 UniformedLinearThis = E;
4792 continue;
4793 }
4794 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4795 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4796 }
4797 // OpenMP [2.8.2, declare simd construct, Description]
4798 // The aligned clause declares that the object to which each list item points
4799 // is aligned to the number of bytes expressed in the optional parameter of
4800 // the aligned clause.
4801 // The special this pointer can be used as if was one of the arguments to the
4802 // function in any of the linear, aligned, or uniform clauses.
4803 // The type of list items appearing in the aligned clause must be array,
4804 // pointer, reference to array, or reference to pointer.
4805 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4806 const Expr *AlignedThis = nullptr;
4807 for (const Expr *E : Aligneds) {
4808 E = E->IgnoreParenImpCasts();
4809 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4810 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4811 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4812 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4813 FD->getParamDecl(PVD->getFunctionScopeIndex())
4814 ->getCanonicalDecl() == CanonPVD) {
4815 // OpenMP [2.8.1, simd construct, Restrictions]
4816 // A list-item cannot appear in more than one aligned clause.
4817 if (AlignedArgs.count(CanonPVD) > 0) {
4818 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4819 << 1 << E->getSourceRange();
4820 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4821 diag::note_omp_explicit_dsa)
4822 << getOpenMPClauseName(OMPC_aligned);
4823 continue;
4824 }
4825 AlignedArgs[CanonPVD] = E;
4826 QualType QTy = PVD->getType()
4827 .getNonReferenceType()
4828 .getUnqualifiedType()
4829 .getCanonicalType();
4830 const Type *Ty = QTy.getTypePtrOrNull();
4831 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4832 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4833 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4834 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4835 }
4836 continue;
4837 }
4838 }
4839 if (isa<CXXThisExpr>(E)) {
4840 if (AlignedThis) {
4841 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4842 << 2 << E->getSourceRange();
4843 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4844 << getOpenMPClauseName(OMPC_aligned);
4845 }
4846 AlignedThis = E;
4847 continue;
4848 }
4849 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4850 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4851 }
4852 // The optional parameter of the aligned clause, alignment, must be a constant
4853 // positive integer expression. If no optional parameter is specified,
4854 // implementation-defined default alignments for SIMD instructions on the
4855 // target platforms are assumed.
4856 SmallVector<const Expr *, 4> NewAligns;
4857 for (Expr *E : Alignments) {
4858 ExprResult Align;
4859 if (E)
4860 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4861 NewAligns.push_back(Align.get());
4862 }
4863 // OpenMP [2.8.2, declare simd construct, Description]
4864 // The linear clause declares one or more list items to be private to a SIMD
4865 // lane and to have a linear relationship with respect to the iteration space
4866 // of a loop.
4867 // The special this pointer can be used as if was one of the arguments to the
4868 // function in any of the linear, aligned, or uniform clauses.
4869 // When a linear-step expression is specified in a linear clause it must be
4870 // either a constant integer expression or an integer-typed parameter that is
4871 // specified in a uniform clause on the directive.
4872 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
4873 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4874 auto MI = LinModifiers.begin();
4875 for (const Expr *E : Linears) {
4876 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4877 ++MI;
4878 E = E->IgnoreParenImpCasts();
4879 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4880 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4881 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4882 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4883 FD->getParamDecl(PVD->getFunctionScopeIndex())
4884 ->getCanonicalDecl() == CanonPVD) {
4885 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4886 // A list-item cannot appear in more than one linear clause.
4887 if (LinearArgs.count(CanonPVD) > 0) {
4888 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4889 << getOpenMPClauseName(OMPC_linear)
4890 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4891 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4892 diag::note_omp_explicit_dsa)
4893 << getOpenMPClauseName(OMPC_linear);
4894 continue;
4895 }
4896 // Each argument can appear in at most one uniform or linear clause.
4897 if (UniformedArgs.count(CanonPVD) > 0) {
4898 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4899 << getOpenMPClauseName(OMPC_linear)
4900 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4901 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4902 diag::note_omp_explicit_dsa)
4903 << getOpenMPClauseName(OMPC_uniform);
4904 continue;
4905 }
4906 LinearArgs[CanonPVD] = E;
4907 if (E->isValueDependent() || E->isTypeDependent() ||
4908 E->isInstantiationDependent() ||
4909 E->containsUnexpandedParameterPack())
4910 continue;
4911 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4912 PVD->getOriginalType());
4913 continue;
4914 }
4915 }
4916 if (isa<CXXThisExpr>(E)) {
4917 if (UniformedLinearThis) {
4918 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4919 << getOpenMPClauseName(OMPC_linear)
4920 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4921 << E->getSourceRange();
4922 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4923 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4924 : OMPC_linear);
4925 continue;
4926 }
4927 UniformedLinearThis = E;
4928 if (E->isValueDependent() || E->isTypeDependent() ||
4929 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4930 continue;
4931 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4932 E->getType());
4933 continue;
4934 }
4935 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4936 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4937 }
4938 Expr *Step = nullptr;
4939 Expr *NewStep = nullptr;
4940 SmallVector<Expr *, 4> NewSteps;
4941 for (Expr *E : Steps) {
4942 // Skip the same step expression, it was checked already.
4943 if (Step == E || !E) {
4944 NewSteps.push_back(E ? NewStep : nullptr);
4945 continue;
4946 }
4947 Step = E;
4948 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4949 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4950 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4951 if (UniformedArgs.count(CanonPVD) == 0) {
4952 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4953 << Step->getSourceRange();
4954 } else if (E->isValueDependent() || E->isTypeDependent() ||
4955 E->isInstantiationDependent() ||
4956 E->containsUnexpandedParameterPack() ||
4957 CanonPVD->getType()->hasIntegerRepresentation()) {
4958 NewSteps.push_back(Step);
4959 } else {
4960 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4961 << Step->getSourceRange();
4962 }
4963 continue;
4964 }
4965 NewStep = Step;
4966 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4967 !Step->isInstantiationDependent() &&
4968 !Step->containsUnexpandedParameterPack()) {
4969 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4970 .get();
4971 if (NewStep)
4972 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4973 }
4974 NewSteps.push_back(NewStep);
4975 }
4976 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4977 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
4978 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
4979 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4980 const_cast<Expr **>(Linears.data()), Linears.size(),
4981 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4982 NewSteps.data(), NewSteps.size(), SR);
4983 ADecl->addAttr(NewAttr);
4984 return DG;
4985}
4986
4987Optional<std::pair<FunctionDecl *, Expr *>>
4988Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
4989 Expr *VariantRef, SourceRange SR) {
4990 if (!DG || DG.get().isNull())
4991 return None;
4992
4993 const int VariantId = 1;
4994 // Must be applied only to single decl.
4995 if (!DG.get().isSingleDecl()) {
4996 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4997 << VariantId << SR;
4998 return None;
4999 }
5000 Decl *ADecl = DG.get().getSingleDecl();
5001 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5002 ADecl = FTD->getTemplatedDecl();
5003
5004 // Decl must be a function.
5005 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5006 if (!FD) {
5007 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5008 << VariantId << SR;
5009 return None;
5010 }
5011
5012 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5013 return FD->hasAttrs() &&
5014 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5015 FD->hasAttr<TargetAttr>());
5016 };
5017 // OpenMP is not compatible with CPU-specific attributes.
5018 if (HasMultiVersionAttributes(FD)) {
5019 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5020 << SR;
5021 return None;
5022 }
5023
5024 // Allow #pragma omp declare variant only if the function is not used.
5025 if (FD->isUsed(false))
5026 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
5027 << FD->getLocation();
5028
5029 // Check if the function was emitted already.
5030 const FunctionDecl *Definition;
5031 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5032 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
5033 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5034 << FD->getLocation();
5035
5036 // The VariantRef must point to function.
5037 if (!VariantRef) {
5038 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
5039 return None;
5040 }
5041
5042 // Do not check templates, wait until instantiation.
5043 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5044 VariantRef->containsUnexpandedParameterPack() ||
5045 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5046 return std::make_pair(FD, VariantRef);
5047
5048 // Convert VariantRef expression to the type of the original function to
5049 // resolve possible conflicts.
5050 ExprResult VariantRefCast;
5051 if (LangOpts.CPlusPlus) {
5052 QualType FnPtrType;
5053 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5054 if (Method && !Method->isStatic()) {
5055 const Type *ClassType =
5056 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5057 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5058 ExprResult ER;
5059 {
5060 // Build adrr_of unary op to correctly handle type checks for member
5061 // functions.
5062 Sema::TentativeAnalysisScope Trap(*this);
5063 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5064 VariantRef);
5065 }
5066 if (!ER.isUsable()) {
5067 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5068 << VariantId << VariantRef->getSourceRange();
5069 return None;
5070 }
5071 VariantRef = ER.get();
5072 } else {
5073 FnPtrType = Context.getPointerType(FD->getType());
5074 }
5075 ImplicitConversionSequence ICS =
5076 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5077 /*SuppressUserConversions=*/false,
5078 /*AllowExplicit=*/false,
5079 /*InOverloadResolution=*/false,
5080 /*CStyle=*/false,
5081 /*AllowObjCWritebackConversion=*/false);
5082 if (ICS.isFailure()) {
5083 Diag(VariantRef->getExprLoc(),
5084 diag::err_omp_declare_variant_incompat_types)
5085 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
5086 return None;
5087 }
5088 VariantRefCast = PerformImplicitConversion(
5089 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5090 if (!VariantRefCast.isUsable())
5091 return None;
5092 // Drop previously built artificial addr_of unary op for member functions.
5093 if (Method && !Method->isStatic()) {
5094 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5095 if (auto *UO = dyn_cast<UnaryOperator>(
5096 PossibleAddrOfVariantRef->IgnoreImplicit()))
5097 VariantRefCast = UO->getSubExpr();
5098 }
5099 } else {
5100 VariantRefCast = VariantRef;
5101 }
5102
5103 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5104 if (!ER.isUsable() ||
5105 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5106 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5107 << VariantId << VariantRef->getSourceRange();
5108 return None;
5109 }
5110
5111 // The VariantRef must point to function.
5112 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5113 if (!DRE) {
5114 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5115 << VariantId << VariantRef->getSourceRange();
5116 return None;
5117 }
5118 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5119 if (!NewFD) {
5120 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5121 << VariantId << VariantRef->getSourceRange();
5122 return None;
5123 }
5124
5125 // Check if variant function is not marked with declare variant directive.
5126 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5127 Diag(VariantRef->getExprLoc(),
5128 diag::warn_omp_declare_variant_marked_as_declare_variant)
5129 << VariantRef->getSourceRange();
5130 SourceRange SR =
5131 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5132 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
5133 return None;
5134 }
5135
5136 enum DoesntSupport {
5137 VirtFuncs = 1,
5138 Constructors = 3,
5139 Destructors = 4,
5140 DeletedFuncs = 5,
5141 DefaultedFuncs = 6,
5142 ConstexprFuncs = 7,
5143 ConstevalFuncs = 8,
5144 };
5145 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5146 if (CXXFD->isVirtual()) {
5147 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5148 << VirtFuncs;
5149 return None;
5150 }
5151
5152 if (isa<CXXConstructorDecl>(FD)) {
5153 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5154 << Constructors;
5155 return None;
5156 }
5157
5158 if (isa<CXXDestructorDecl>(FD)) {
5159 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5160 << Destructors;
5161 return None;
5162 }
5163 }
5164
5165 if (FD->isDeleted()) {
5166 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5167 << DeletedFuncs;
5168 return None;
5169 }
5170
5171 if (FD->isDefaulted()) {
5172 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5173 << DefaultedFuncs;
5174 return None;
5175 }
5176
5177 if (FD->isConstexpr()) {
5178 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5179 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
5180 return None;
5181 }
5182
5183 // Check general compatibility.
5184 if (areMultiversionVariantFunctionsCompatible(
5185 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5186 PartialDiagnosticAt(
5187 SR.getBegin(),
5188 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5189 PartialDiagnosticAt(
5190 VariantRef->getExprLoc(),
5191 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5192 PartialDiagnosticAt(VariantRef->getExprLoc(),
5193 PDiag(diag::err_omp_declare_variant_diff)
5194 << FD->getLocation()),
5195 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5196 /*CLinkageMayDiffer=*/true))
5197 return None;
5198 return std::make_pair(FD, cast<Expr>(DRE));
5199}
5200
5201void Sema::ActOnOpenMPDeclareVariantDirective(
5202 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
5203 ArrayRef<OMPCtxSelectorData> Data) {
5204 if (Data.empty())
5205 return;
5206 SmallVector<Expr *, 4> CtxScores;
5207 SmallVector<unsigned, 4> CtxSets;
5208 SmallVector<unsigned, 4> Ctxs;
5209 SmallVector<StringRef, 4> ImplVendors;
5210 bool IsError = false;
5211 for (const OMPCtxSelectorData &D : Data) {
5212 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5213 OpenMPContextSelectorKind Ctx = D.Ctx;
5214 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5215 return;
5216 Expr *Score = nullptr;
5217 if (D.Score.isUsable()) {
5218 Score = D.Score.get();
5219 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5220 !Score->isInstantiationDependent() &&
5221 !Score->containsUnexpandedParameterPack()) {
5222 Score =
5223 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5224 .get();
5225 if (Score)
5226 Score = VerifyIntegerConstantExpression(Score).get();
5227 }
5228 } else {
5229 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
5230 }
5231 switch (CtxSet) {
5232 case OMP_CTX_SET_implementation:
5233 switch (Ctx) {
5234 case OMP_CTX_vendor:
5235 ImplVendors.append(D.Names.begin(), D.Names.end());
5236 break;
5237 case OMP_CTX_unknown:
5238 llvm_unreachable("Unexpected context selector kind.")::llvm::llvm_unreachable_internal("Unexpected context selector kind."
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5238)
;
5239 }
5240 break;
5241 case OMP_CTX_SET_unknown:
5242 llvm_unreachable("Unexpected context selector set kind.")::llvm::llvm_unreachable_internal("Unexpected context selector set kind."
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5242)
;
5243 }
5244 IsError = IsError || !Score;
5245 CtxSets.push_back(CtxSet);
5246 Ctxs.push_back(Ctx);
5247 CtxScores.push_back(Score);
5248 }
5249 if (!IsError) {
5250 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5251 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5252 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
5253 ImplVendors.begin(), ImplVendors.size(), SR);
5254 FD->addAttr(NewAttr);
5255 }
5256}
5257
5258void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5259 FunctionDecl *Func,
5260 bool MightBeOdrUse) {
5261 assert(LangOpts.OpenMP && "Expected OpenMP mode.")((LangOpts.OpenMP && "Expected OpenMP mode.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"Expected OpenMP mode.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5261, __PRETTY_FUNCTION__))
;
5262
5263 if (!Func->isDependentContext() && Func->hasAttrs()) {
5264 for (OMPDeclareVariantAttr *A :
5265 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5266 // TODO: add checks for active OpenMP context where possible.
5267 Expr *VariantRef = A->getVariantFuncRef();
5268 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5269 auto *F = cast<FunctionDecl>(DRE->getDecl());
5270 if (!F->isDefined() && F->isTemplateInstantiation())
5271 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5272 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5273 }
5274 }
5275}
5276
5277StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5278 Stmt *AStmt,
5279 SourceLocation StartLoc,
5280 SourceLocation EndLoc) {
5281 if (!AStmt)
5282 return StmtError();
5283
5284 auto *CS = cast<CapturedStmt>(AStmt);
5285 // 1.2.2 OpenMP Language Terminology
5286 // Structured block - An executable statement with a single entry at the
5287 // top and a single exit at the bottom.
5288 // The point of exit cannot be a branch out of the structured block.
5289 // longjmp() and throw() must not violate the entry/exit criteria.
5290 CS->getCapturedDecl()->setNothrow();
5291
5292 setFunctionHasBranchProtectedScope();
5293
5294 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5295 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5296}
5297
5298namespace {
5299/// Iteration space of a single for loop.
5300struct LoopIterationSpace final {
5301 /// True if the condition operator is the strict compare operator (<, > or
5302 /// !=).
5303 bool IsStrictCompare = false;
5304 /// Condition of the loop.
5305 Expr *PreCond = nullptr;
5306 /// This expression calculates the number of iterations in the loop.
5307 /// It is always possible to calculate it before starting the loop.
5308 Expr *NumIterations = nullptr;
5309 /// The loop counter variable.
5310 Expr *CounterVar = nullptr;
5311 /// Private loop counter variable.
5312 Expr *PrivateCounterVar = nullptr;
5313 /// This is initializer for the initial value of #CounterVar.
5314 Expr *CounterInit = nullptr;
5315 /// This is step for the #CounterVar used to generate its update:
5316 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5317 Expr *CounterStep = nullptr;
5318 /// Should step be subtracted?
5319 bool Subtract = false;
5320 /// Source range of the loop init.
5321 SourceRange InitSrcRange;
5322 /// Source range of the loop condition.
5323 SourceRange CondSrcRange;
5324 /// Source range of the loop increment.
5325 SourceRange IncSrcRange;
5326 /// Minimum value that can have the loop control variable. Used to support
5327 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5328 /// since only such variables can be used in non-loop invariant expressions.
5329 Expr *MinValue = nullptr;
5330 /// Maximum value that can have the loop control variable. Used to support
5331 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5332 /// since only such variables can be used in non-loop invariant expressions.
5333 Expr *MaxValue = nullptr;
5334 /// true, if the lower bound depends on the outer loop control var.
5335 bool IsNonRectangularLB = false;
5336 /// true, if the upper bound depends on the outer loop control var.
5337 bool IsNonRectangularUB = false;
5338 /// Index of the loop this loop depends on and forms non-rectangular loop
5339 /// nest.
5340 unsigned LoopDependentIdx = 0;
5341 /// Final condition for the non-rectangular loop nest support. It is used to
5342 /// check that the number of iterations for this particular counter must be
5343 /// finished.
5344 Expr *FinalCondition = nullptr;
5345};
5346
5347/// Helper class for checking canonical form of the OpenMP loops and
5348/// extracting iteration space of each loop in the loop nest, that will be used
5349/// for IR generation.
5350class OpenMPIterationSpaceChecker {
5351 /// Reference to Sema.
5352 Sema &SemaRef;
5353 /// Data-sharing stack.
5354 DSAStackTy &Stack;
5355 /// A location for diagnostics (when there is no some better location).
5356 SourceLocation DefaultLoc;
5357 /// A location for diagnostics (when increment is not compatible).
5358 SourceLocation ConditionLoc;
5359 /// A source location for referring to loop init later.
5360 SourceRange InitSrcRange;
5361 /// A source location for referring to condition later.
5362 SourceRange ConditionSrcRange;
5363 /// A source location for referring to increment later.
5364 SourceRange IncrementSrcRange;
5365 /// Loop variable.
5366 ValueDecl *LCDecl = nullptr;
5367 /// Reference to loop variable.
5368 Expr *LCRef = nullptr;
5369 /// Lower bound (initializer for the var).
5370 Expr *LB = nullptr;
5371 /// Upper bound.
5372 Expr *UB = nullptr;
5373 /// Loop step (increment).
5374 Expr *Step = nullptr;
5375 /// This flag is true when condition is one of:
5376 /// Var < UB
5377 /// Var <= UB
5378 /// UB > Var
5379 /// UB >= Var
5380 /// This will have no value when the condition is !=
5381 llvm::Optional<bool> TestIsLessOp;
5382 /// This flag is true when condition is strict ( < or > ).
5383 bool TestIsStrictOp = false;
5384 /// This flag is true when step is subtracted on each iteration.
5385 bool SubtractStep = false;
5386 /// The outer loop counter this loop depends on (if any).
5387 const ValueDecl *DepDecl = nullptr;
5388 /// Contains number of loop (starts from 1) on which loop counter init
5389 /// expression of this loop depends on.
5390 Optional<unsigned> InitDependOnLC;
5391 /// Contains number of loop (starts from 1) on which loop counter condition
5392 /// expression of this loop depends on.
5393 Optional<unsigned> CondDependOnLC;
5394 /// Checks if the provide statement depends on the loop counter.
5395 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
5396 /// Original condition required for checking of the exit condition for
5397 /// non-rectangular loop.
5398 Expr *Condition = nullptr;
5399
5400public:
5401 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5402 SourceLocation DefaultLoc)
5403 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5404 ConditionLoc(DefaultLoc) {}
5405 /// Check init-expr for canonical loop form and save loop counter
5406 /// variable - #Var and its initialization value - #LB.
5407 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
5408 /// Check test-expr for canonical form, save upper-bound (#UB), flags
5409 /// for less/greater and for strict/non-strict comparison.
5410 bool checkAndSetCond(Expr *S);
5411 /// Check incr-expr for canonical loop form and return true if it
5412 /// does not conform, otherwise save loop step (#Step).
5413 bool checkAndSetInc(Expr *S);
5414 /// Return the loop counter variable.
5415 ValueDecl *getLoopDecl() const { return LCDecl; }
5416 /// Return the reference expression to loop counter variable.
5417 Expr *getLoopDeclRefExpr() const { return LCRef; }
5418 /// Source range of the loop init.
5419 SourceRange getInitSrcRange() const { return InitSrcRange; }
5420 /// Source range of the loop condition.
5421 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
5422 /// Source range of the loop increment.
5423 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
5424 /// True if the step should be subtracted.
5425 bool shouldSubtractStep() const { return SubtractStep; }
5426 /// True, if the compare operator is strict (<, > or !=).
5427 bool isStrictTestOp() const { return TestIsStrictOp; }
5428 /// Build the expression to calculate the number of iterations.
5429 Expr *buildNumIterations(
5430 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
5431 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5432 /// Build the precondition expression for the loops.
5433 Expr *
5434 buildPreCond(Scope *S, Expr *Cond,
5435 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5436 /// Build reference expression to the counter be used for codegen.
5437 DeclRefExpr *
5438 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5439 DSAStackTy &DSA) const;
5440 /// Build reference expression to the private counter be used for
5441 /// codegen.
5442 Expr *buildPrivateCounterVar() const;
5443 /// Build initialization of the counter be used for codegen.
5444 Expr *buildCounterInit() const;
5445 /// Build step of the counter be used for codegen.
5446 Expr *buildCounterStep() const;
5447 /// Build loop data with counter value for depend clauses in ordered
5448 /// directives.
5449 Expr *
5450 buildOrderedLoopData(Scope *S, Expr *Counter,
5451 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5452 SourceLocation Loc, Expr *Inc = nullptr,
5453 OverloadedOperatorKind OOK = OO_Amp);
5454 /// Builds the minimum value for the loop counter.
5455 std::pair<Expr *, Expr *> buildMinMaxValues(
5456 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5457 /// Builds final condition for the non-rectangular loops.
5458 Expr *buildFinalCondition(Scope *S) const;
5459 /// Return true if any expression is dependent.
5460 bool dependent() const;
5461 /// Returns true if the initializer forms non-rectangular loop.
5462 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5463 /// Returns true if the condition forms non-rectangular loop.
5464 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5465 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5466 unsigned getLoopDependentIdx() const {
5467 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5468 }
5469
5470private:
5471 /// Check the right-hand side of an assignment in the increment
5472 /// expression.
5473 bool checkAndSetIncRHS(Expr *RHS);
5474 /// Helper to set loop counter variable and its initializer.
5475 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5476 bool EmitDiags);
5477 /// Helper to set upper bound.
5478 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5479 SourceRange SR, SourceLocation SL);
5480 /// Helper to set loop increment.
5481 bool setStep(Expr *NewStep, bool Subtract);
5482};
5483
5484bool OpenMPIterationSpaceChecker::dependent() const {
5485 if (!LCDecl) {
5486 assert(!LB && !UB && !Step)((!LB && !UB && !Step) ? static_cast<void>
(0) : __assert_fail ("!LB && !UB && !Step", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5486, __PRETTY_FUNCTION__))
;
5487 return false;
5488 }
5489 return LCDecl->getType()->isDependentType() ||
5490 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5491 (Step && Step->isValueDependent());
5492}
5493
5494bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
5495 Expr *NewLCRefExpr,
5496 Expr *NewLB, bool EmitDiags) {
5497 // State consistency checking to ensure correct usage.
5498 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5499, __PRETTY_FUNCTION__))
5499 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5499, __PRETTY_FUNCTION__))
;
5500 if (!NewLCDecl || !NewLB)
5501 return true;
5502 LCDecl = getCanonicalDecl(NewLCDecl);
5503 LCRef = NewLCRefExpr;
5504 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5505 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
5506 if ((Ctor->isCopyOrMoveConstructor() ||
5507 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5508 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
5509 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
5510 LB = NewLB;
5511 if (EmitDiags)
5512 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
5513 return false;
5514}
5515
5516bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5517 llvm::Optional<bool> LessOp,
5518 bool StrictOp, SourceRange SR,
5519 SourceLocation SL) {
5520 // State consistency checking to ensure correct usage.
5521 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5522, __PRETTY_FUNCTION__))
5522 Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5522, __PRETTY_FUNCTION__))
;
5523 if (!NewUB)
5524 return true;
5525 UB = NewUB;
5526 if (LessOp)
5527 TestIsLessOp = LessOp;
5528 TestIsStrictOp = StrictOp;
5529 ConditionSrcRange = SR;
5530 ConditionLoc = SL;
5531 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
5532 return false;
5533}
5534
5535bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
5536 // State consistency checking to ensure correct usage.
5537 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr)((LCDecl != nullptr && LB != nullptr && Step ==
nullptr) ? static_cast<void> (0) : __assert_fail ("LCDecl != nullptr && LB != nullptr && Step == nullptr"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaOpenMP.cpp"
, 5537, __PRETTY_FUNCTION__))
;
5538 if (!NewStep)
5539 return true;
5540 if (!NewStep->isValueDependent()) {
5541 // Check that the step is integer expression.
5542 SourceLocation StepLoc = NewStep->getBeginLoc();
5543 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5544 StepLoc, getExprAsWritten(NewStep));
5545 if (Val.isInvalid())
5546 return true;
5547 NewStep = Val.get();
5548
5549 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5550 // If test-expr is of form var relational-op b and relational-op is < or
5551 // <= then incr-expr must cause var to increase on each iteration of the
5552 // loop. If test-expr is of form var relational-op b and relational-op is
5553 // > or >= then incr-expr must cause var to decrease on each iteration of
5554 // the loop.
5555 // If test-expr is of form b relational-op var and relational-op is < or
5556 // <= then incr-expr must cause var to decrease on each iteration of the
5557 // loop. If test-expr is of form b relational-op var and relational-op is
5558 // > or >= then incr-expr must cause var to increase on each iteration of
5559 // the loop.
5560 llvm::APSInt Result;
5561 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5562 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5563 bool IsConstNeg =
5564 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
5565 bool IsConstPos =
5566 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
5567 bool IsConstZero = IsConstant && !Result.getBoolValue();
5568
5569 // != with increment is treated as