Bug Summary

File:clang/lib/Sema/SemaOpenMP.cpp
Warning:line 3939, column 5
Value stored to 'ErrorFound' is never read

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